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,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/EditorFeatures/CSharpTest/SplitComment/SplitCommentCommandHandlerTests.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.Editor.UnitTests.SplitComment; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SplitComment { [UseExportProvider] public class SplitCommentCommandHandlerTests : AbstractSplitCommentCommandHandlerTests { protected override TestWorkspace CreateWorkspace(string markup) => TestWorkspace.CreateCSharp(markup); [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestWithSelection() { TestHandled( @"public class Program { public static void Main(string[] args) { //[|Test|] Comment } }", @"public class Program { public static void Main(string[] args) { // //Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestWithAllWhitespaceSelection() { TestHandled( @"public class Program { public static void Main(string[] args) { // [| |] Test Comment } }", @"public class Program { public static void Main(string[] args) { // // Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestMissingInSlashes() { TestNotHandled( @"public class Program { public static void Main(string[] args) { /[||]/Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestMissingAtEndOfFile() { TestNotHandled( @"public class Program { public static void Main(string[] args) { //Test Comment[||]"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestMissingBeforeSlashes() { TestNotHandled( @"public class Program { public static void Main(string[] args) { [||]//Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestMissingWithMultiSelection() { TestNotHandled( @"public class Program { public static void Main(string[] args) { //[||]Test[||] Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitStartOfComment() { TestHandled( @"public class Program { public static void Main(string[] args) { //[||]Test Comment } }", @"public class Program { public static void Main(string[] args) { // //Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitStartOfQuadComment() { TestHandled( @"public class Program { public static void Main(string[] args) { ////[||]Test Comment } }", @"public class Program { public static void Main(string[] args) { //// ////Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitMiddleOfQuadComment() { TestNotHandled( @"public class Program { public static void Main(string[] args) { //[||]//Test Comment } }"); } [WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitWithCommentAfterwards1() { TestNotHandled( @"public class Program { public static void Main(string[] args) { // goo[||] //Test Comment } }"); } [WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitWithCommentAfterwards2() { TestNotHandled( @"public class Program { public static void Main(string[] args) { // goo [||] //Test Comment } }"); } [WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitWithCommentAfterwards3() { TestNotHandled( @"public class Program { public static void Main(string[] args) { // goo [||]//Test Comment } }"); } [WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitWithCommentAfterwards4() { TestNotHandled( @"public class Program { public static void Main(string[] args) { // [|goo|] //Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitStartOfCommentWithLeadingSpace1() { TestHandled( @"public class Program { public static void Main(string[] args) { // [||]Test Comment } }", @"public class Program { public static void Main(string[] args) { // // Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitStartOfCommentWithLeadingSpace2() { TestHandled( @"public class Program { public static void Main(string[] args) { //[||] Test Comment } }", @"public class Program { public static void Main(string[] args) { // //Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfTheory, Trait(Traits.Feature, Traits.Features.SplitComment)] [InlineData("X[||]Test Comment")] [InlineData("X [||]Test Comment")] [InlineData("X[||] Test Comment")] [InlineData("X [||] Test Comment")] public void TestCommentWithMultipleLeadingSpaces(string commentValue) { TestHandled( @$"public class Program {{ public static void Main(string[] args) {{ // {commentValue} }} }}", @"public class Program { public static void Main(string[] args) { // X // Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfTheory, Trait(Traits.Feature, Traits.Features.SplitComment)] [InlineData("X[||]Test Comment")] [InlineData("X [||]Test Comment")] [InlineData("X[||] Test Comment")] [InlineData("X [||] Test Comment")] [InlineData("X[| |]Test Comment")] public void TestQuadCommentWithMultipleLeadingSpaces(string commentValue) { TestHandled( @$"public class Program {{ public static void Main(string[] args) {{ //// {commentValue} }} }}", @"public class Program { public static void Main(string[] args) { //// X //// Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitMiddleOfComment() { TestHandled( @"public class Program { public static void Main(string[] args) { // Test [||]Comment } }", @"public class Program { public static void Main(string[] args) { // Test // Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitEndOfComment() { TestNotHandled( @"public class Program { public static void Main(string[] args) { // Test Comment[||] } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitCommentEndOfLine1() { TestHandled( @"public class Program { public static void Main(string[] args) // Test [||]Comment { } }", @"public class Program { public static void Main(string[] args) // Test // Comment { } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitCommentEndOfLine2() { TestHandled( @"public class Program { public static void Main(string[] args) // Test[||] Comment { } }", @"public class Program { public static void Main(string[] args) // Test // Comment { } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestUseTabs() { TestHandled( @"public class Program { public static void Main(string[] args) { // X[||]Test Comment } }", @"public class Program { public static void Main(string[] args) { // X // Test Comment } }", useTabs: true); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestDoesNotHandleDocComments() { TestNotHandled( @"namespace TestNamespace { public class Program { /// <summary>Test [||]Comment</summary> public static void Main(string[] args) { } } }"); } } }
// Licensed to the .NET Foundation under one or more 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.Editor.UnitTests.SplitComment; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SplitComment { [UseExportProvider] public class SplitCommentCommandHandlerTests : AbstractSplitCommentCommandHandlerTests { protected override TestWorkspace CreateWorkspace(string markup) => TestWorkspace.CreateCSharp(markup); [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestWithSelection() { TestHandled( @"public class Program { public static void Main(string[] args) { //[|Test|] Comment } }", @"public class Program { public static void Main(string[] args) { // //Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestWithAllWhitespaceSelection() { TestHandled( @"public class Program { public static void Main(string[] args) { // [| |] Test Comment } }", @"public class Program { public static void Main(string[] args) { // // Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestMissingInSlashes() { TestNotHandled( @"public class Program { public static void Main(string[] args) { /[||]/Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestMissingAtEndOfFile() { TestNotHandled( @"public class Program { public static void Main(string[] args) { //Test Comment[||]"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestMissingBeforeSlashes() { TestNotHandled( @"public class Program { public static void Main(string[] args) { [||]//Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestMissingWithMultiSelection() { TestNotHandled( @"public class Program { public static void Main(string[] args) { //[||]Test[||] Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitStartOfComment() { TestHandled( @"public class Program { public static void Main(string[] args) { //[||]Test Comment } }", @"public class Program { public static void Main(string[] args) { // //Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitStartOfQuadComment() { TestHandled( @"public class Program { public static void Main(string[] args) { ////[||]Test Comment } }", @"public class Program { public static void Main(string[] args) { //// ////Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitMiddleOfQuadComment() { TestNotHandled( @"public class Program { public static void Main(string[] args) { //[||]//Test Comment } }"); } [WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitWithCommentAfterwards1() { TestNotHandled( @"public class Program { public static void Main(string[] args) { // goo[||] //Test Comment } }"); } [WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitWithCommentAfterwards2() { TestNotHandled( @"public class Program { public static void Main(string[] args) { // goo [||] //Test Comment } }"); } [WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitWithCommentAfterwards3() { TestNotHandled( @"public class Program { public static void Main(string[] args) { // goo [||]//Test Comment } }"); } [WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitWithCommentAfterwards4() { TestNotHandled( @"public class Program { public static void Main(string[] args) { // [|goo|] //Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitStartOfCommentWithLeadingSpace1() { TestHandled( @"public class Program { public static void Main(string[] args) { // [||]Test Comment } }", @"public class Program { public static void Main(string[] args) { // // Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitStartOfCommentWithLeadingSpace2() { TestHandled( @"public class Program { public static void Main(string[] args) { //[||] Test Comment } }", @"public class Program { public static void Main(string[] args) { // //Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfTheory, Trait(Traits.Feature, Traits.Features.SplitComment)] [InlineData("X[||]Test Comment")] [InlineData("X [||]Test Comment")] [InlineData("X[||] Test Comment")] [InlineData("X [||] Test Comment")] public void TestCommentWithMultipleLeadingSpaces(string commentValue) { TestHandled( @$"public class Program {{ public static void Main(string[] args) {{ // {commentValue} }} }}", @"public class Program { public static void Main(string[] args) { // X // Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfTheory, Trait(Traits.Feature, Traits.Features.SplitComment)] [InlineData("X[||]Test Comment")] [InlineData("X [||]Test Comment")] [InlineData("X[||] Test Comment")] [InlineData("X [||] Test Comment")] [InlineData("X[| |]Test Comment")] public void TestQuadCommentWithMultipleLeadingSpaces(string commentValue) { TestHandled( @$"public class Program {{ public static void Main(string[] args) {{ //// {commentValue} }} }}", @"public class Program { public static void Main(string[] args) { //// X //// Test Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitMiddleOfComment() { TestHandled( @"public class Program { public static void Main(string[] args) { // Test [||]Comment } }", @"public class Program { public static void Main(string[] args) { // Test // Comment } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitEndOfComment() { TestNotHandled( @"public class Program { public static void Main(string[] args) { // Test Comment[||] } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitCommentEndOfLine1() { TestHandled( @"public class Program { public static void Main(string[] args) // Test [||]Comment { } }", @"public class Program { public static void Main(string[] args) // Test // Comment { } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestSplitCommentEndOfLine2() { TestHandled( @"public class Program { public static void Main(string[] args) // Test[||] Comment { } }", @"public class Program { public static void Main(string[] args) // Test // Comment { } }"); } [WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")] [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestUseTabs() { TestHandled( @"public class Program { public static void Main(string[] args) { // X[||]Test Comment } }", @"public class Program { public static void Main(string[] args) { // X // Test Comment } }", useTabs: true); } [WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)] public void TestDoesNotHandleDocComments() { TestNotHandled( @"namespace TestNamespace { public class Program { /// <summary>Test [||]Comment</summary> public static void Main(string[] args) { } } }"); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Workspaces/Remote/ServiceHub/Services/TodoCommentsDiscovery/RemoteTodoCommentsIncrementalAnalyzerProvider.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.SolutionCrawler; using Microsoft.CodeAnalysis.TodoComments; using Microsoft.ServiceHub.Framework; namespace Microsoft.CodeAnalysis.Remote { /// <remarks>Note: this is explicitly <b>not</b> exported. We don't want the <see /// cref="RemoteWorkspace"/> to automatically load this. Instead, VS waits until it is ready /// and then calls into OOP to tell it to start analyzing the solution. At that point we'll get /// created and added to the solution crawler. /// </remarks> internal sealed class RemoteTodoCommentsIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { private readonly RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public RemoteTodoCommentsIncrementalAnalyzerProvider(RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) => new RemoteTodoCommentsIncrementalAnalyzer(_callback, _callbackId); } }
// Licensed to the .NET Foundation under one or more 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.SolutionCrawler; using Microsoft.CodeAnalysis.TodoComments; using Microsoft.ServiceHub.Framework; namespace Microsoft.CodeAnalysis.Remote { /// <remarks>Note: this is explicitly <b>not</b> exported. We don't want the <see /// cref="RemoteWorkspace"/> to automatically load this. Instead, VS waits until it is ready /// and then calls into OOP to tell it to start analyzing the solution. At that point we'll get /// created and added to the solution crawler. /// </remarks> internal sealed class RemoteTodoCommentsIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { private readonly RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> _callback; private readonly RemoteServiceCallbackId _callbackId; public RemoteTodoCommentsIncrementalAnalyzerProvider(RemoteCallback<IRemoteTodoCommentsDiscoveryService.ICallback> callback, RemoteServiceCallbackId callbackId) { _callback = callback; _callbackId = callbackId; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) => new RemoteTodoCommentsIncrementalAnalyzer(_callback, _callbackId); } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedContainer.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.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.CSharp.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A container synthesized for a lambda, iterator method, async method, or dynamic-sites. /// </summary> internal abstract class SynthesizedContainer : NamedTypeSymbol { private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly ImmutableArray<TypeParameterSymbol> _constructedFromTypeParameters; protected SynthesizedContainer(string name, int parameterCount, bool returnsVoid) { Debug.Assert(name != null); Name = name; TypeMap = TypeMap.Empty; _typeParameters = CreateTypeParameters(parameterCount, returnsVoid); _constructedFromTypeParameters = default(ImmutableArray<TypeParameterSymbol>); } protected SynthesizedContainer(string name, MethodSymbol containingMethod) { Debug.Assert(name != null); Name = name; if (containingMethod == null) { TypeMap = TypeMap.Empty; _typeParameters = ImmutableArray<TypeParameterSymbol>.Empty; } else { TypeMap = TypeMap.Empty.WithConcatAlphaRename(containingMethod, this, out _typeParameters, out _constructedFromTypeParameters); } } protected SynthesizedContainer(string name, ImmutableArray<TypeParameterSymbol> typeParameters, TypeMap typeMap) { Debug.Assert(name != null); Debug.Assert(!typeParameters.IsDefault); Debug.Assert(typeMap != null); Name = name; _typeParameters = typeParameters; TypeMap = typeMap; } private ImmutableArray<TypeParameterSymbol> CreateTypeParameters(int parameterCount, bool returnsVoid) { var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(parameterCount + (returnsVoid ? 0 : 1)); for (int i = 0; i < parameterCount; i++) { typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(this, i, "T" + (i + 1))); } if (!returnsVoid) { typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(this, parameterCount, "TResult")); } return typeParameters.ToImmutableAndFree(); } internal TypeMap TypeMap { get; } internal virtual MethodSymbol Constructor => null; internal sealed override bool IsInterface => this.TypeKind == TypeKind.Interface; internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (ContainingSymbol.Kind == SymbolKind.NamedType && ContainingSymbol.IsImplicitlyDeclared) { return; } var compilation = ContainingSymbol.DeclaringCompilation; // this can only happen if frame is not nested in a source type/namespace (so far we do not do this) // if this happens for whatever reason, we do not need "CompilerGenerated" anyways Debug.Assert(compilation != null, "SynthesizedClass is not contained in a source module?"); AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) => throw ExceptionUtilities.Unreachable; /// <summary> /// Note: Can be default if this SynthesizedContainer was constructed with <see cref="SynthesizedContainer(string, int, bool)"/> /// </summary> internal ImmutableArray<TypeParameterSymbol> ConstructedFromTypeParameters => _constructedFromTypeParameters; public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters => _typeParameters; public sealed override string Name { get; } public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override IEnumerable<string> MemberNames => SpecializedCollections.EmptyEnumerable<string>(); public override NamedTypeSymbol ConstructedFrom => this; public override bool IsSealed => true; public override bool IsAbstract => (object)Constructor == null && this.TypeKind != TypeKind.Struct; internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return GetTypeParametersAsTypeArguments(); } } internal override bool HasCodeAnalysisEmbeddedAttribute => false; internal sealed override bool IsInterpolatedStringHandlerType => false; public override ImmutableArray<Symbol> GetMembers() { Symbol constructor = this.Constructor; return (object)constructor == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(constructor); } public override ImmutableArray<Symbol> GetMembers(string name) { var ctor = Constructor; return ((object)ctor != null && name == ctor.Name) ? ImmutableArray.Create<Symbol>(ctor) : ImmutableArray<Symbol>.Empty; } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { foreach (var m in this.GetMembers()) { switch (m.Kind) { case SymbolKind.Field: yield return (FieldSymbol)m; break; } } } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() => this.GetMembersUnordered(); internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) => this.GetMembers(name); public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) => ImmutableArray<NamedTypeSymbol>.Empty; public override Accessibility DeclaredAccessibility => Accessibility.Private; public override bool IsStatic => false; public sealed override bool IsRefLikeType => false; public sealed override bool IsReadOnly => false; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved) => ImmutableArray<NamedTypeSymbol>.Empty; internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() => CalculateInterfacesToEmit(); internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => ContainingAssembly.GetSpecialType(this.TypeKind == TypeKind.Struct ? SpecialType.System_ValueType : SpecialType.System_Object); internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved) => BaseTypeNoUseSiteDiagnostics; internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved) => InterfacesNoUseSiteDiagnostics(basesBeingResolved); public override bool MightContainExtensionMethods => false; public override int Arity => TypeParameters.Length; internal override bool MangleName => Arity > 0; public override bool IsImplicitlyDeclared => true; internal override bool ShouldAddWinRTMembers => false; internal override bool IsWindowsRuntimeImport => false; internal override bool IsComImport => false; internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; internal sealed override ImmutableArray<string> GetAppliedConditionalSymbols() => ImmutableArray<string>.Empty; internal override bool HasDeclarativeSecurity => false; internal override CharSet MarshallingCharSet => DefaultMarshallingCharSet; public override bool IsSerializable => false; internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override AttributeUsageInfo GetAttributeUsageInfo() => default(AttributeUsageInfo); internal override TypeLayout Layout => default(TypeLayout); internal override bool HasSpecialName => false; internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable; internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>(); } } }
// Licensed to the .NET Foundation under one or more 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.Runtime.InteropServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.CSharp.Emit; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A container synthesized for a lambda, iterator method, async method, or dynamic-sites. /// </summary> internal abstract class SynthesizedContainer : NamedTypeSymbol { private readonly ImmutableArray<TypeParameterSymbol> _typeParameters; private readonly ImmutableArray<TypeParameterSymbol> _constructedFromTypeParameters; protected SynthesizedContainer(string name, int parameterCount, bool returnsVoid) { Debug.Assert(name != null); Name = name; TypeMap = TypeMap.Empty; _typeParameters = CreateTypeParameters(parameterCount, returnsVoid); _constructedFromTypeParameters = default(ImmutableArray<TypeParameterSymbol>); } protected SynthesizedContainer(string name, MethodSymbol containingMethod) { Debug.Assert(name != null); Name = name; if (containingMethod == null) { TypeMap = TypeMap.Empty; _typeParameters = ImmutableArray<TypeParameterSymbol>.Empty; } else { TypeMap = TypeMap.Empty.WithConcatAlphaRename(containingMethod, this, out _typeParameters, out _constructedFromTypeParameters); } } protected SynthesizedContainer(string name, ImmutableArray<TypeParameterSymbol> typeParameters, TypeMap typeMap) { Debug.Assert(name != null); Debug.Assert(!typeParameters.IsDefault); Debug.Assert(typeMap != null); Name = name; _typeParameters = typeParameters; TypeMap = typeMap; } private ImmutableArray<TypeParameterSymbol> CreateTypeParameters(int parameterCount, bool returnsVoid) { var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(parameterCount + (returnsVoid ? 0 : 1)); for (int i = 0; i < parameterCount; i++) { typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(this, i, "T" + (i + 1))); } if (!returnsVoid) { typeParameters.Add(new AnonymousTypeManager.AnonymousTypeParameterSymbol(this, parameterCount, "TResult")); } return typeParameters.ToImmutableAndFree(); } internal TypeMap TypeMap { get; } internal virtual MethodSymbol Constructor => null; internal sealed override bool IsInterface => this.TypeKind == TypeKind.Interface; internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (ContainingSymbol.Kind == SymbolKind.NamedType && ContainingSymbol.IsImplicitlyDeclared) { return; } var compilation = ContainingSymbol.DeclaringCompilation; // this can only happen if frame is not nested in a source type/namespace (so far we do not do this) // if this happens for whatever reason, we do not need "CompilerGenerated" anyways Debug.Assert(compilation != null, "SynthesizedClass is not contained in a source module?"); AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) => throw ExceptionUtilities.Unreachable; /// <summary> /// Note: Can be default if this SynthesizedContainer was constructed with <see cref="SynthesizedContainer(string, int, bool)"/> /// </summary> internal ImmutableArray<TypeParameterSymbol> ConstructedFromTypeParameters => _constructedFromTypeParameters; public sealed override ImmutableArray<TypeParameterSymbol> TypeParameters => _typeParameters; public sealed override string Name { get; } public override ImmutableArray<Location> Locations => ImmutableArray<Location>.Empty; public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => ImmutableArray<SyntaxReference>.Empty; public override IEnumerable<string> MemberNames => SpecializedCollections.EmptyEnumerable<string>(); public override NamedTypeSymbol ConstructedFrom => this; public override bool IsSealed => true; public override bool IsAbstract => (object)Constructor == null && this.TypeKind != TypeKind.Struct; internal override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return GetTypeParametersAsTypeArguments(); } } internal override bool HasCodeAnalysisEmbeddedAttribute => false; internal sealed override bool IsInterpolatedStringHandlerType => false; public override ImmutableArray<Symbol> GetMembers() { Symbol constructor = this.Constructor; return (object)constructor == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(constructor); } public override ImmutableArray<Symbol> GetMembers(string name) { var ctor = Constructor; return ((object)ctor != null && name == ctor.Name) ? ImmutableArray.Create<Symbol>(ctor) : ImmutableArray<Symbol>.Empty; } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { foreach (var m in this.GetMembers()) { switch (m.Kind) { case SymbolKind.Field: yield return (FieldSymbol)m; break; } } } internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() => this.GetMembersUnordered(); internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) => this.GetMembers(name); public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) => ImmutableArray<NamedTypeSymbol>.Empty; public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) => ImmutableArray<NamedTypeSymbol>.Empty; public override Accessibility DeclaredAccessibility => Accessibility.Private; public override bool IsStatic => false; public sealed override bool IsRefLikeType => false; public sealed override bool IsReadOnly => false; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved) => ImmutableArray<NamedTypeSymbol>.Empty; internal override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() => CalculateInterfacesToEmit(); internal override NamedTypeSymbol BaseTypeNoUseSiteDiagnostics => ContainingAssembly.GetSpecialType(this.TypeKind == TypeKind.Struct ? SpecialType.System_ValueType : SpecialType.System_Object); internal override NamedTypeSymbol GetDeclaredBaseType(ConsList<TypeSymbol> basesBeingResolved) => BaseTypeNoUseSiteDiagnostics; internal override ImmutableArray<NamedTypeSymbol> GetDeclaredInterfaces(ConsList<TypeSymbol> basesBeingResolved) => InterfacesNoUseSiteDiagnostics(basesBeingResolved); public override bool MightContainExtensionMethods => false; public override int Arity => TypeParameters.Length; internal override bool MangleName => Arity > 0; public override bool IsImplicitlyDeclared => true; internal override bool ShouldAddWinRTMembers => false; internal override bool IsWindowsRuntimeImport => false; internal override bool IsComImport => false; internal sealed override ObsoleteAttributeData ObsoleteAttributeData => null; internal sealed override ImmutableArray<string> GetAppliedConditionalSymbols() => ImmutableArray<string>.Empty; internal override bool HasDeclarativeSecurity => false; internal override CharSet MarshallingCharSet => DefaultMarshallingCharSet; public override bool IsSerializable => false; internal override IEnumerable<Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override AttributeUsageInfo GetAttributeUsageInfo() => default(AttributeUsageInfo); internal override TypeLayout Layout => default(TypeLayout); internal override bool HasSpecialName => false; internal sealed override NamedTypeSymbol AsNativeInteger() => throw ExceptionUtilities.Unreachable; internal sealed override NamedTypeSymbol NativeIntegerUnderlyingType => null; internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { return SpecializedCollections.EmptyEnumerable<(MethodSymbol Body, MethodSymbol Implemented)>(); } } }
-1
dotnet/roslyn
55,745
Use document with partial semantic for completion
Closes #51407
genlu
2021-08-20T00:37:12Z
2021-08-30T18:26:38Z
ff6ef22170a112ce0f66de5cfb8a00710bce69a2
62213239743be2deec6dd5c2bebe86957c3f53d3
Use document with partial semantic for completion. Closes #51407
./src/Compilers/VisualBasic/Portable/Symbols/Source/SourceMemberMethodSymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a method declared in source. ''' </summary> Friend NotInheritable Class SourceMemberMethodSymbol Inherits SourceNonPropertyAccessorMethodSymbol Private ReadOnly _name As String ' Cache this value upon creation as it is needed for LookupSymbols and is expensive to ' compute by creating the actual type parameters. Private ReadOnly _arity As Integer ' Flags indicates results of quick scan of the attributes Private ReadOnly _quickAttributes As QuickAttributes Private _lazyMetadataName As String ' The explicitly implemented interface methods, or Empty if none. Private _lazyImplementedMethods As ImmutableArray(Of MethodSymbol) ' Type parameters. Nothing if none. Private _lazyTypeParameters As ImmutableArray(Of TypeParameterSymbol) ' The overridden or hidden methods. Private _lazyHandles As ImmutableArray(Of HandledEvent) ''' <summary> ''' If this symbol represents a partial method definition or implementation part, its other part (if any). ''' This should be set, if at all, before this symbol appears among the members of its owner. ''' The implementation part is not listed among the "members" of the enclosing type. ''' </summary> Private _otherPartOfPartial As SourceMemberMethodSymbol ''' <summary> ''' In case the method is an 'Async' method, stores the reference to a state machine type ''' synthesized in AsyncRewriter. Note, that this field is mutable and is being assigned ''' by calling AssignAsyncStateMachineType(...). ''' </summary> Private ReadOnly _asyncStateMachineType As NamedTypeSymbol = Nothing ' lazily evaluated state of the symbol (StateFlags) Private _lazyState As Integer <Flags> Private Enum StateFlags As Integer ''' <summary> ''' If this flag is set this method will be ignored ''' in duplicated signature analysis, see ERR_DuplicateProcDef1 diagnostics. ''' </summary> SuppressDuplicateProcDefDiagnostics = &H1 ''' <summary> ''' Set after all diagnostics have been reported for this symbol. ''' </summary> AllDiagnosticsReported = &H2 End Enum #If DEBUG Then Private _partialMethodInfoIsFrozen As Boolean = False #End If Friend Sub New(containingType As SourceMemberContainerTypeSymbol, name As String, flags As SourceMemberFlags, binder As Binder, syntax As MethodBaseSyntax, arity As Integer, Optional handledEvents As ImmutableArray(Of HandledEvent) = Nothing) MyBase.New(containingType, flags, binder.GetSyntaxReference(syntax)) ' initialized lazily if unset: _lazyHandles = handledEvents _name = name _arity = arity ' Check attributes quickly. _quickAttributes = binder.QuickAttributeChecker.CheckAttributes(syntax.AttributeLists) If Not containingType.AllowsExtensionMethods() Then ' Extension methods in source can only be inside modules. _quickAttributes = _quickAttributes And Not QuickAttributes.Extension End If End Sub Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Protected Overrides ReadOnly Property BoundAttributesSource As SourceMethodSymbol Get Return Me.SourcePartialDefinition End Get End Property Public Overrides ReadOnly Property MetadataName As String Get If _lazyMetadataName Is Nothing Then ' VB has special rules for changing the metadata name of method overloads/overrides. If MethodKind = MethodKind.Ordinary Then OverloadingHelper.SetMetadataNameForAllOverloads(_name, SymbolKind.Method, m_containingType) Else ' Constructors, conversion operators, etc. just use their regular name. SetMetadataName(_name) End If Debug.Assert(_lazyMetadataName IsNot Nothing) End If Return _lazyMetadataName End Get End Property ' Set the metadata name for this symbol. Called from OverloadingHelper.SetMetadataNameForAllOverloads ' for each symbol of the same name in a type. Friend Overrides Sub SetMetadataName(metadataName As String) Dim old = Interlocked.CompareExchange(_lazyMetadataName, metadataName, Nothing) Debug.Assert(old Is Nothing OrElse old = metadataName) ';If there was a race, make sure it was consistent If Me.IsPartial Then Dim partialImpl = Me.OtherPartOfPartial If partialImpl IsNot Nothing Then partialImpl.SetMetadataName(metadataName) End If End If End Sub Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return MyBase.GenerateDebugInfoImpl AndAlso Not IsAsync End Get End Property Protected Overrides Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) If Me.SourcePartialImplementation IsNot Nothing Then Return OneOrMany.Create(ImmutableArray.Create(AttributeDeclarationSyntaxList, Me.SourcePartialImplementation.AttributeDeclarationSyntaxList)) Else Return OneOrMany.Create(AttributeDeclarationSyntaxList) End If End Function Private Function GetQuickAttributes() As QuickAttributes Dim quickAttrs = _quickAttributes If Me.IsPartial Then Dim partialImpl = Me.OtherPartOfPartial If partialImpl IsNot Nothing Then Return quickAttrs Or partialImpl._quickAttributes End If End If Return quickAttrs End Function Friend Overrides ReadOnly Property MayBeReducibleExtensionMethod As Boolean Get Return (GetQuickAttributes() And QuickAttributes.Extension) <> 0 End Get End Property Public Overrides ReadOnly Property IsExtensionMethod As Boolean Get If MayBeReducibleExtensionMethod Then Return MyBase.IsExtensionMethod Else Return False End If End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) If Me.IsAsync OrElse Me.IsIterator Then AddSynthesizedAttribute(attributes, Me.DeclaringCompilation.SynthesizeStateMachineAttribute(Me, compilationState)) If Me.IsAsync Then ' Async kick-off method calls MoveNext, which contains user code. ' This means we need to emit DebuggerStepThroughAttribute in order ' to have correct stepping behavior during debugging. AddSynthesizedAttribute(attributes, Me.DeclaringCompilation.SynthesizeOptionalDebuggerStepThroughAttribute()) End If End If End Sub Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get If (GetQuickAttributes() And QuickAttributes.Obsolete) <> 0 Then Return MyBase.ObsoleteAttributeData Else Return Nothing End If End Get End Property Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) If (_lazyState And StateFlags.AllDiagnosticsReported) <> 0 Then Return End If MyBase.GenerateDeclarationErrors(cancellationToken) Dim diagnostics As BindingDiagnosticBag = BindingDiagnosticBag.GetInstance() ' Ensure explicit implementations are resolved. If Not Me.ExplicitInterfaceImplementations.IsEmpty Then ' Check any constraints against implemented methods. ValidateImplementedMethodConstraints(diagnostics) End If Dim methodImpl As SourceMemberMethodSymbol = If(Me.IsPartial, SourcePartialImplementation, Me) If methodImpl IsNot Nothing AndAlso (methodImpl.IsAsync OrElse methodImpl.IsIterator) AndAlso Not methodImpl.ContainingType.IsInterfaceType() Then Dim container As NamedTypeSymbol = methodImpl.ContainingType Do Dim sourceType = TryCast(container, SourceNamedTypeSymbol) If sourceType IsNot Nothing AndAlso sourceType.HasSecurityCriticalAttributes Then Dim location As Location = methodImpl.NonMergedLocation If location IsNot Nothing Then Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_SecurityCriticalAsyncInClassOrStruct) End If Exit Do End If container = container.ContainingType Loop While container IsNot Nothing If methodImpl.IsAsync AndAlso (methodImpl.ImplementationAttributes And Reflection.MethodImplAttributes.Synchronized) <> 0 Then Dim location As Location = methodImpl.NonMergedLocation If location IsNot Nothing Then Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_SynchronizedAsyncMethod) End If End If End If If methodImpl IsNot Nothing AndAlso methodImpl IsNot Me Then ' Check for parameter default value mismatch. Dim result As SymbolComparisonResults = MethodSignatureComparer.DetailedCompare(Me, methodImpl, SymbolComparisonResults.OptionalParameterValueMismatch Or SymbolComparisonResults.ParamArrayMismatch) If result <> Nothing Then Dim location As Location = methodImpl.NonMergedLocation If location IsNot Nothing Then If (result And SymbolComparisonResults.ParamArrayMismatch) <> 0 Then Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_PartialMethodParamArrayMismatch2, methodImpl, Me) ElseIf (result And SymbolComparisonResults.OptionalParameterValueMismatch) <> 0 Then Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_PartialMethodDefaultParameterValueMismatch2, methodImpl, Me) End If End If End If End If ContainingSourceModule.AtomicSetFlagAndStoreDiagnostics(_lazyState, StateFlags.AllDiagnosticsReported, 0, diagnostics) diagnostics.Free() End Sub #Region "Type Parameters" Public Overrides ReadOnly Property Arity As Integer Get Return _arity End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Dim params = _lazyTypeParameters If params.IsDefault Then Dim diagBag = BindingDiagnosticBag.GetInstance Dim sourceModule = DirectCast(Me.ContainingModule, SourceModuleSymbol) params = GetTypeParameters(sourceModule, diagBag) sourceModule.AtomicStoreArrayAndDiagnostics(_lazyTypeParameters, params, diagBag) diagBag.Free() params = _lazyTypeParameters End If Return params End Get End Property Private Function GetTypeParameters(sourceModule As SourceModuleSymbol, diagBag As BindingDiagnosticBag) As ImmutableArray(Of TypeParameterSymbol) Dim paramList = GetTypeParameterListSyntax(Me.DeclarationSyntax) If paramList Is Nothing Then Return ImmutableArray(Of TypeParameterSymbol).Empty End If Dim binder As Binder = BinderBuilder.CreateBinderForType(sourceModule, Me.SyntaxTree, m_containingType) Dim typeParamsSyntax = paramList.Parameters Dim arity As Integer = typeParamsSyntax.Count Dim typeParameters(0 To arity - 1) As TypeParameterSymbol For i = 0 To arity - 1 Dim typeParamSyntax = typeParamsSyntax(i) Dim ident = typeParamSyntax.Identifier Binder.DisallowTypeCharacter(ident, diagBag, ERRID.ERR_TypeCharOnGenericParam) typeParameters(i) = New SourceTypeParameterOnMethodSymbol(Me, i, ident.ValueText, binder.GetSyntaxReference(typeParamSyntax)) ' method type parameters cannot have same name as containing Function (but can for a Sub) If Me.DeclarationSyntax.Kind = SyntaxKind.FunctionStatement AndAlso CaseInsensitiveComparison.Equals(Me.Name, ident.ValueText) Then Binder.ReportDiagnostic(diagBag, typeParamSyntax, ERRID.ERR_TypeParamNameFunctionNameCollision) End If Next ' Add the type parameters to our binder for binding parameters and return values binder = New MethodTypeParametersBinder(binder, typeParameters.AsImmutableOrNull) Dim containingSourceType = TryCast(ContainingType, SourceNamedTypeSymbol) If containingSourceType IsNot Nothing Then containingSourceType.CheckForDuplicateTypeParameters(typeParameters.AsImmutableOrNull, diagBag) End If Return typeParameters.AsImmutableOrNull End Function #End Region #Region "Explicit Interface Implementations" Friend Function HasExplicitInterfaceImplementations() As Boolean Dim syntax = TryCast(Me.DeclarationSyntax, MethodStatementSyntax) Return syntax IsNot Nothing AndAlso syntax.ImplementsClause IsNot Nothing End Function Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get If _lazyImplementedMethods.IsDefault Then Dim sourceModule = DirectCast(Me.ContainingModule, SourceModuleSymbol) Dim diagnostics = BindingDiagnosticBag.GetInstance() Dim implementedMethods As ImmutableArray(Of MethodSymbol) If Me.IsPartial Then ' Partial method declaration itself cannot have Implements clause (an error should ' be reported) and just returns implemented methods from the implementation ' Report diagnostic if needed Debug.Assert(Me.SyntaxTree IsNot Nothing) Dim syntax = TryCast(Me.DeclarationSyntax, MethodStatementSyntax) If (syntax IsNot Nothing) AndAlso (syntax.ImplementsClause IsNot Nothing) Then ' Don't allow implements on partial method declarations. diagnostics.Add(ERRID.ERR_PartialDeclarationImplements1, syntax.Identifier.GetLocation(), syntax.Identifier.ToString()) End If ' Store implemented interface methods from the partial method implementation. Dim implementation As MethodSymbol = Me.PartialImplementationPart implementedMethods = If(implementation Is Nothing, ImmutableArray(Of MethodSymbol).Empty, implementation.ExplicitInterfaceImplementations) Else implementedMethods = Me.GetExplicitInterfaceImplementations(sourceModule, diagnostics) End If sourceModule.AtomicStoreArrayAndDiagnostics(_lazyImplementedMethods, implementedMethods, diagnostics) diagnostics.Free() End If Return _lazyImplementedMethods End Get End Property Private Function GetExplicitInterfaceImplementations(sourceModule As SourceModuleSymbol, diagBag As BindingDiagnosticBag) As ImmutableArray(Of MethodSymbol) Debug.Assert(Not Me.IsPartial) Dim syntax = TryCast(Me.DeclarationSyntax, MethodStatementSyntax) If (syntax IsNot Nothing) AndAlso (syntax.ImplementsClause IsNot Nothing) Then Dim binder As Binder = BinderBuilder.CreateBinderForType(sourceModule, Me.SyntaxTree, ContainingType) If Me.IsShared And Not ContainingType.IsModuleType Then ' Implementing with shared methods is illegal. ' Module case is caught inside ProcessImplementsClause and has different message. Binder.ReportDiagnostic(diagBag, syntax.Modifiers.First(SyntaxKind.SharedKeyword), ERRID.ERR_SharedOnProcThatImpl, syntax.Identifier.ToString()) ' Don't clear the Shared flag because then you get errors from semantics about needing an object reference to the non-shared member, etc. Else Return ProcessImplementsClause(Of MethodSymbol)(syntax.ImplementsClause, Me, DirectCast(ContainingType, SourceMemberContainerTypeSymbol), binder, diagBag) End If End If Return ImmutableArray(Of MethodSymbol).Empty End Function ''' <summary> ''' Validate method type parameter constraints against implemented methods. ''' </summary> Friend Sub ValidateImplementedMethodConstraints(diagnostics As BindingDiagnosticBag) If Me.IsPartial AndAlso Me.OtherPartOfPartial IsNot Nothing Then Me.OtherPartOfPartial.ValidateImplementedMethodConstraints(diagnostics) Else Dim implementedMethods = ExplicitInterfaceImplementations If implementedMethods.IsEmpty Then Return End If For Each implementedMethod In implementedMethods ImplementsHelper.ValidateImplementedMethodConstraints(Me, implementedMethod, diagnostics) Next End If End Sub #End Region #Region "Partials" Friend Overrides ReadOnly Property HasEmptyBody As Boolean Get If Not MyBase.HasEmptyBody Then Return False End If Dim impl = SourcePartialImplementation Return impl Is Nothing OrElse impl.HasEmptyBody End Get End Property Friend ReadOnly Property IsPartialDefinition As Boolean Get Return Me.IsPartial End Get End Property Friend ReadOnly Property IsPartialImplementation As Boolean Get Return Not IsPartialDefinition AndAlso Me.OtherPartOfPartial IsNot Nothing End Get End Property Public ReadOnly Property SourcePartialDefinition As SourceMemberMethodSymbol Get Return If(IsPartialDefinition, Nothing, Me.OtherPartOfPartial) End Get End Property Public ReadOnly Property SourcePartialImplementation As SourceMemberMethodSymbol Get Return If(IsPartialDefinition, Me.OtherPartOfPartial, Nothing) End Get End Property Public Overrides ReadOnly Property PartialDefinitionPart As MethodSymbol Get Return SourcePartialDefinition End Get End Property Public Overrides ReadOnly Property PartialImplementationPart As MethodSymbol Get Return SourcePartialImplementation End Get End Property Friend Property OtherPartOfPartial As SourceMemberMethodSymbol Get #If DEBUG Then Me._partialMethodInfoIsFrozen = True #End If Return Me._otherPartOfPartial End Get Private Set(value As SourceMemberMethodSymbol) Dim oldValue As SourceMemberMethodSymbol = Me._otherPartOfPartial Me._otherPartOfPartial = value #If DEBUG Then ' As we want to make sure we always validate attributes on partial ' method declaration, we need to make sure we don't validate ' attributes before PartialMethodCounterpart is assigned Debug.Assert(Me.m_lazyCustomAttributesBag Is Nothing) Debug.Assert(Me.m_lazyReturnTypeCustomAttributesBag Is Nothing) For Each param In Me.Parameters Dim complexParam = TryCast(param, SourceComplexParameterSymbol) If complexParam IsNot Nothing Then complexParam.AssertAttributesNotValidatedYet() End If Next ' If partial method info is frozen the new and the old values must be equal Debug.Assert(Not Me._partialMethodInfoIsFrozen OrElse oldValue Is value) Me._partialMethodInfoIsFrozen = True #End If End Set End Property Friend Property SuppressDuplicateProcDefDiagnostics As Boolean Get #If DEBUG Then Me._partialMethodInfoIsFrozen = True #End If Return (_lazyState And StateFlags.SuppressDuplicateProcDefDiagnostics) <> 0 End Get Set(value As Boolean) Dim stateChanged = ThreadSafeFlagOperations.Set(_lazyState, StateFlags.SuppressDuplicateProcDefDiagnostics) #If DEBUG Then ' If partial method info is frozen the new and the old values must be equal Debug.Assert(Not Me._partialMethodInfoIsFrozen OrElse Not stateChanged) Me._partialMethodInfoIsFrozen = True #End If End Set End Property ''' <summary> ''' This method is to be called to assign implementation to a partial method. ''' </summary> Friend Shared Sub InitializePartialMethodParts(definition As SourceMemberMethodSymbol, implementation As SourceMemberMethodSymbol) Debug.Assert(definition.IsPartial) Debug.Assert(implementation Is Nothing OrElse Not implementation.IsPartial) definition.OtherPartOfPartial = implementation If implementation IsNot Nothing Then implementation.OtherPartOfPartial = definition End If End Sub Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock If Me.IsPartial Then Throw ExceptionUtilities.Unreachable End If Return MyBase.GetBoundMethodBody(compilationState, diagnostics, methodBodyBinder) End Function #End Region #Region "Handles" Public Overrides ReadOnly Property HandledEvents As ImmutableArray(Of HandledEvent) Get If _lazyHandles.IsDefault Then Dim sourceModule = DirectCast(Me.ContainingModule, SourceModuleSymbol) Dim diagnostics = BindingDiagnosticBag.GetInstance() Dim boundHandledEvents = Me.GetHandles(sourceModule, diagnostics) sourceModule.AtomicStoreArrayAndDiagnostics(Of HandledEvent)(_lazyHandles, boundHandledEvents, diagnostics) diagnostics.Free() End If Return _lazyHandles End Get End Property Private Function GetHandles(sourceModule As SourceModuleSymbol, diagBag As BindingDiagnosticBag) As ImmutableArray(Of HandledEvent) Dim syntax = TryCast(Me.DeclarationSyntax, MethodStatementSyntax) If (syntax Is Nothing) OrElse (syntax.HandlesClause Is Nothing) Then Return ImmutableArray(Of HandledEvent).Empty End If Dim typeBinder As Binder = BinderBuilder.CreateBinderForType(sourceModule, Me.SyntaxTree, m_containingType) typeBinder = New LocationSpecificBinder(BindingLocation.HandlesClause, Me, typeBinder) Dim handlesBuilder = ArrayBuilder(Of HandledEvent).GetInstance For Each singleHandleClause As HandlesClauseItemSyntax In syntax.HandlesClause.Events Dim handledEventResult = BindSingleHandlesClause(singleHandleClause, typeBinder, diagBag) If handledEventResult IsNot Nothing Then handlesBuilder.Add(handledEventResult) End If Next Return handlesBuilder.ToImmutableAndFree End Function Friend Function BindSingleHandlesClause(singleHandleClause As HandlesClauseItemSyntax, typeBinder As Binder, diagBag As BindingDiagnosticBag, Optional candidateEventSymbols As ArrayBuilder(Of Symbol) = Nothing, Optional candidateWithEventsSymbols As ArrayBuilder(Of Symbol) = Nothing, Optional candidateWithEventsPropertySymbols As ArrayBuilder(Of Symbol) = Nothing, Optional ByRef resultKind As LookupResultKind = Nothing) As HandledEvent Dim handlesKind As HandledEventKind Dim eventContainingType As TypeSymbol = Nothing Dim withEventsSourceProperty As PropertySymbol = Nothing ' This is the WithEvents property that looks as event container to the user. (it could be in a base class) Dim witheventsProperty As PropertySymbol = Nothing ' This is the WithEvents property that will actually used to hookup handlers. (it could be a proxy override) Dim witheventsPropertyInCurrentClass As PropertySymbol = Nothing If Me.ContainingType.IsModuleType AndAlso singleHandleClause.EventContainer.Kind <> SyntaxKind.WithEventsEventContainer Then Binder.ReportDiagnostic(diagBag, singleHandleClause, ERRID.ERR_HandlesSyntaxInModule) Return Nothing End If Dim eventContainerKind = singleHandleClause.EventContainer.Kind Dim useSiteInfo = typeBinder.GetNewCompoundUseSiteInfo(diagBag) If eventContainerKind = SyntaxKind.KeywordEventContainer Then Select Case DirectCast(singleHandleClause.EventContainer, KeywordEventContainerSyntax).Keyword.Kind Case SyntaxKind.MeKeyword handlesKind = HandledEventKind.Me eventContainingType = Me.ContainingType Case SyntaxKind.MyClassKeyword handlesKind = HandledEventKind.MyClass eventContainingType = Me.ContainingType Case SyntaxKind.MyBaseKeyword handlesKind = HandledEventKind.MyBase eventContainingType = Me.ContainingType.BaseTypeNoUseSiteDiagnostics End Select ElseIf eventContainerKind = SyntaxKind.WithEventsEventContainer OrElse eventContainerKind = SyntaxKind.WithEventsPropertyEventContainer Then handlesKind = HandledEventKind.WithEvents Dim witheventsContainer = If(eventContainerKind = SyntaxKind.WithEventsPropertyEventContainer, DirectCast(singleHandleClause.EventContainer, WithEventsPropertyEventContainerSyntax).WithEventsContainer, DirectCast(singleHandleClause.EventContainer, WithEventsEventContainerSyntax)) Dim witheventsName = witheventsContainer.Identifier.ValueText witheventsProperty = FindWithEventsProperty(m_containingType, typeBinder, witheventsName, useSiteInfo, candidateWithEventsSymbols, resultKind) diagBag.Add(singleHandleClause.EventContainer, useSiteInfo) useSiteInfo = New CompoundUseSiteInfo(Of AssemblySymbol)(useSiteInfo) If witheventsProperty Is Nothing Then Binder.ReportDiagnostic(diagBag, singleHandleClause.EventContainer, ERRID.ERR_NoWithEventsVarOnHandlesList) Return Nothing End If Dim isFromBase = Not TypeSymbol.Equals(witheventsProperty.ContainingType, Me.ContainingType, TypeCompareKind.ConsiderEverything) If witheventsProperty.IsShared Then Debug.Assert(Not witheventsProperty.IsOverridable) If Not Me.IsShared Then 'Events of shared WithEvents variables cannot be handled by non-shared methods. Binder.ReportDiagnostic(diagBag, singleHandleClause.EventContainer, ERRID.ERR_SharedEventNeedsSharedHandler) End If If isFromBase Then Binder.ReportDiagnostic(diagBag, singleHandleClause.EventContainer, ERRID.ERR_SharedEventNeedsHandlerInTheSameType) End If End If If eventContainerKind = SyntaxKind.WithEventsPropertyEventContainer Then Dim propName = DirectCast(singleHandleClause.EventContainer, WithEventsPropertyEventContainerSyntax).Property.Identifier.ValueText withEventsSourceProperty = FindProperty(witheventsProperty.Type, typeBinder, propName, useSiteInfo, candidateWithEventsPropertySymbols, resultKind) If withEventsSourceProperty Is Nothing Then Binder.ReportDiagnostic(diagBag, singleHandleClause.EventContainer, ERRID.ERR_HandlesSyntaxInClass) Return Nothing End If eventContainingType = withEventsSourceProperty.Type Else eventContainingType = witheventsProperty.Type End If ' if was found in one of bases, need to override it If isFromBase Then witheventsPropertyInCurrentClass = DirectCast(Me.ContainingType, SourceNamedTypeSymbol).GetOrAddWithEventsOverride(witheventsProperty) Else witheventsPropertyInCurrentClass = witheventsProperty End If typeBinder.ReportDiagnosticsIfObsoleteOrNotSupportedByRuntime(diagBag, witheventsPropertyInCurrentClass, singleHandleClause.EventContainer) Else Binder.ReportDiagnostic(diagBag, singleHandleClause.EventContainer, ERRID.ERR_HandlesSyntaxInClass) Return Nothing End If Dim eventName As String = singleHandleClause.EventMember.Identifier.ValueText Dim eventSymbol As EventSymbol = Nothing If eventContainingType IsNot Nothing Then Binder.ReportUseSite(diagBag, singleHandleClause.EventMember, eventContainingType) ' Bind event symbol eventSymbol = FindEvent(eventContainingType, typeBinder, eventName, handlesKind = HandledEventKind.MyBase, useSiteInfo, candidateEventSymbols, resultKind) End If diagBag.Add(singleHandleClause.EventMember, useSiteInfo) If eventSymbol Is Nothing Then 'Event '{0}' cannot be found. Binder.ReportDiagnostic(diagBag, singleHandleClause.EventMember, ERRID.ERR_EventNotFound1, eventName) Return Nothing End If typeBinder.ReportDiagnosticsIfObsoleteOrNotSupportedByRuntime(diagBag, eventSymbol, singleHandleClause.EventMember) Binder.ReportUseSite(diagBag, singleHandleClause.EventMember, eventSymbol) If eventSymbol.AddMethod IsNot Nothing Then Binder.ReportUseSite(diagBag, singleHandleClause.EventMember, eventSymbol.AddMethod) End If If eventSymbol.RemoveMethod IsNot Nothing Then Binder.ReportUseSite(diagBag, singleHandleClause.EventMember, eventSymbol.RemoveMethod) End If ' For WinRT events, we require that certain well-known members be present (needed in synthesize code). If eventSymbol.IsWindowsRuntimeEvent Then typeBinder.GetWellKnownTypeMember( WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler, singleHandleClause.EventMember, diagBag) typeBinder.GetWellKnownTypeMember( WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler, singleHandleClause.EventMember, diagBag) End If Select Case ContainingType.TypeKind Case TypeKind.Interface, TypeKind.Structure, TypeKind.Enum, TypeKind.Delegate ' Handles clause is invalid in this context. Return Nothing Case TypeKind.Class, TypeKind.Module ' Valid context Case Else Throw ExceptionUtilities.UnexpectedValue(ContainingType.TypeKind) End Select Dim receiverOpt As BoundExpression = Nothing ' synthesize delegate creation (may involve relaxation) Dim hookupMethod As MethodSymbol = Nothing If handlesKind = HandledEventKind.WithEvents Then hookupMethod = witheventsPropertyInCurrentClass.SetMethod Else If eventSymbol.IsShared AndAlso Me.IsShared Then ' if both method and event are shared, host method is shared ctor hookupMethod = Me.ContainingType.SharedConstructors(0) ' There will only be one in a correct program. Else ' if either method, or event are not shared, host method is instance ctor Dim instanceCtors = Me.ContainingType.InstanceConstructors Debug.Assert(Not instanceCtors.IsEmpty, "bind non-type members should have ensured at least one ctor for us") ' any instance ctor will do for our purposes here. ' We will only use "Me" and that does not need to be from a particular ctor. hookupMethod = instanceCtors(0) End If End If Debug.Assert(hookupMethod IsNot Nothing, "bind non-type members should have ensured appropriate host method for handles injection") ' No use site errors, since method is from source (or synthesized) If Not hookupMethod.IsShared Then receiverOpt = New BoundMeReference(singleHandleClause, Me.ContainingType).MakeCompilerGenerated End If Dim handlingMethod As MethodSymbol = Me If Me.PartialDefinitionPart IsNot Nothing Then ' it is ok for a partial method to have Handles, but if there is a definition part, ' it is the definition method that will do the handling handlingMethod = Me.PartialDefinitionPart End If Dim qualificationKind As QualificationKind If hookupMethod.IsShared Then qualificationKind = QualificationKind.QualifiedViaTypeName Else qualificationKind = QualificationKind.QualifiedViaValue End If Dim syntheticMethodGroup = New BoundMethodGroup( singleHandleClause, Nothing, ImmutableArray.Create(Of MethodSymbol)(handlingMethod), LookupResultKind.Good, receiverOpt, qualificationKind:=qualificationKind) ' AddressOf currentMethod Dim syntheticAddressOf = New BoundAddressOfOperator(singleHandleClause, typeBinder, diagBag.AccumulatesDependencies, syntheticMethodGroup).MakeCompilerGenerated ' 9.2.6 Event handling ' ... A handler method M is considered a valid event handler for an event E ' if the statement " AddHandler E, AddressOf M " would also be valid. ' Unlike an AddHandler statement, however, explicit event handlers allow ' handling an event with a method with no arguments regardless of ' whether strict semantics are being used or not. Dim resolutionResult = Binder.InterpretDelegateBinding(syntheticAddressOf, eventSymbol.Type, isForHandles:=True) If Not Conversions.ConversionExists(resolutionResult.DelegateConversions) Then ' TODO: Consider skip reporting this diagnostic if "ERR_SharedEventNeedsSharedHandler" was already reported above. 'Method '{0}' cannot handle event '{1}' because they do not have a compatible signature. Binder.ReportDiagnostic(diagBag, singleHandleClause.EventMember, ERRID.ERR_EventHandlerSignatureIncompatible2, Me.Name, eventName) Return Nothing Else diagBag.AddDependencies(resolutionResult.Diagnostics.Dependencies) End If Dim delegateCreation = typeBinder.ReclassifyAddressOf(syntheticAddressOf, resolutionResult, eventSymbol.Type, diagBag, isForHandles:=True, warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=True) Dim handledEventResult = New HandledEvent(handlesKind, eventSymbol, witheventsProperty, withEventsSourceProperty, delegateCreation, hookupMethod) Return handledEventResult End Function Friend Shared Function FindWithEventsProperty(containingType As TypeSymbol, binder As Binder, name As String, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), Optional candidateEventSymbols As ArrayBuilder(Of Symbol) = Nothing, Optional ByRef resultKind As LookupResultKind = Nothing) As PropertySymbol Dim witheventsLookup = LookupResult.GetInstance ' WithEvents properties are always accessed via Me/MyBase Dim options = LookupOptions.IgnoreExtensionMethods Or LookupOptions.UseBaseReferenceAccessibility binder.LookupMember(witheventsLookup, containingType, name, 0, options, useSiteInfo) If candidateEventSymbols IsNot Nothing Then candidateEventSymbols.AddRange(witheventsLookup.Symbols) resultKind = witheventsLookup.Kind End If Dim result As PropertySymbol = Nothing If witheventsLookup.IsGood Then If witheventsLookup.HasSingleSymbol Then Dim prop = TryCast(witheventsLookup.SingleSymbol, PropertySymbol) If prop IsNot Nothing AndAlso prop.IsWithEvents Then result = prop Else resultKind = LookupResultKind.NotAWithEventsMember End If Else resultKind = LookupResultKind.Ambiguous End If End If witheventsLookup.Free() Return result End Function Friend Shared Function FindEvent(containingType As TypeSymbol, binder As Binder, name As String, isThroughMyBase As Boolean, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), Optional candidateEventSymbols As ArrayBuilder(Of Symbol) = Nothing, Optional ByRef resultKind As LookupResultKind = Nothing) As EventSymbol Dim options = LookupOptions.IgnoreExtensionMethods Or LookupOptions.EventsOnly If isThroughMyBase Then options = options Or LookupOptions.UseBaseReferenceAccessibility End If Dim eventLookup = LookupResult.GetInstance binder.LookupMember(eventLookup, containingType, name, 0, options, useSiteInfo) If candidateEventSymbols IsNot Nothing Then candidateEventSymbols.AddRange(eventLookup.Symbols) resultKind = eventLookup.Kind End If Dim result As EventSymbol = Nothing If eventLookup.IsGood Then If eventLookup.HasSingleSymbol Then result = TryCast(eventLookup.SingleSymbol, EventSymbol) If result Is Nothing Then resultKind = LookupResultKind.NotAnEvent End If Else ' finding more than one item is ambiguous resultKind = LookupResultKind.Ambiguous End If End If eventLookup.Free() Return result End Function Private Shared Function FindProperty(containingType As TypeSymbol, binder As Binder, name As String, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), Optional candidatePropertySymbols As ArrayBuilder(Of Symbol) = Nothing, Optional ByRef resultKind As LookupResultKind = Nothing) As PropertySymbol ' // Note: ' // - we don't support finding the Property if it is overloaded ' // across classes. ' // - Also note that we don't support digging into bases. This was ' // how the previous impl. was. ' // Given that this is not a user feature, we don't bother doing ' // this extra work. Dim options = CType(LookupOptions.IgnoreExtensionMethods Or LookupOptions.NoBaseClassLookup, LookupOptions) Dim propertyLookup = LookupResult.GetInstance binder.LookupMember(propertyLookup, containingType, name, 0, options, useSiteInfo) If candidatePropertySymbols IsNot Nothing Then candidatePropertySymbols.AddRange(propertyLookup.Symbols) resultKind = propertyLookup.Kind End If Dim result As PropertySymbol = Nothing If propertyLookup.IsGood Then Dim symbols = propertyLookup.Symbols For Each symbol In symbols If symbol.Kind = SymbolKind.Property Then 'Function ValidEventSourceProperty( _ ' ByVal [Property] As BCSym.[Property] _ ') As Boolean ' ' // We only care about properties returning classes or interfaces ' ' // because only classes and interfaces can be specified in a ' ' // handles clause. ' ' // ' Return _ ' [Property].ReturnsEventSource() AndAlso _ ' [Property].GetParameterCount() = 0 AndAlso _ ' [Property].GetProperty() IsNot Nothing AndAlso _ ' IsClassOrInterface([Property]._GetType()) ' End Function Dim prop = DirectCast(symbol, PropertySymbol) If prop.Parameters.Any Then Continue For End If ' here we have parameterless property, it must be ours, As long as it is readable. If prop.GetMethod IsNot Nothing AndAlso prop.GetMethod.ReturnType.IsClassOrInterfaceType AndAlso ReturnsEventSource(prop, binder.Compilation) Then ' finding more than one item would seem ambiguous ' not sure if this can happen though, ' regardless, native compiler does not consider it an error ' it just uses the first found item. result = prop Exit For End If End If Next If result Is Nothing Then resultKind = LookupResultKind.Empty End If End If propertyLookup.Free() Return result End Function Private Shared Function ReturnsEventSource(prop As PropertySymbol, compilation As VisualBasicCompilation) As Boolean Dim attrs = prop.GetAttributes() For Each attr In attrs If attr.AttributeClass Is compilation.GetWellKnownType(WellKnownType.System_ComponentModel_DesignerSerializationVisibilityAttribute) Then Dim args = attr.CommonConstructorArguments If args.Length = 1 Then Dim arg = args(0) Const DESIGNERSERIALIZATIONVISIBILITYTYPE_CONTENT As Integer = 2 If arg.Kind <> TypedConstantKind.Array AndAlso CInt(arg.ValueInternal) = DESIGNERSERIALIZATIONVISIBILITYTYPE_CONTENT Then Return True End If End If End If Next Return 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 System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a method declared in source. ''' </summary> Friend NotInheritable Class SourceMemberMethodSymbol Inherits SourceNonPropertyAccessorMethodSymbol Private ReadOnly _name As String ' Cache this value upon creation as it is needed for LookupSymbols and is expensive to ' compute by creating the actual type parameters. Private ReadOnly _arity As Integer ' Flags indicates results of quick scan of the attributes Private ReadOnly _quickAttributes As QuickAttributes Private _lazyMetadataName As String ' The explicitly implemented interface methods, or Empty if none. Private _lazyImplementedMethods As ImmutableArray(Of MethodSymbol) ' Type parameters. Nothing if none. Private _lazyTypeParameters As ImmutableArray(Of TypeParameterSymbol) ' The overridden or hidden methods. Private _lazyHandles As ImmutableArray(Of HandledEvent) ''' <summary> ''' If this symbol represents a partial method definition or implementation part, its other part (if any). ''' This should be set, if at all, before this symbol appears among the members of its owner. ''' The implementation part is not listed among the "members" of the enclosing type. ''' </summary> Private _otherPartOfPartial As SourceMemberMethodSymbol ''' <summary> ''' In case the method is an 'Async' method, stores the reference to a state machine type ''' synthesized in AsyncRewriter. Note, that this field is mutable and is being assigned ''' by calling AssignAsyncStateMachineType(...). ''' </summary> Private ReadOnly _asyncStateMachineType As NamedTypeSymbol = Nothing ' lazily evaluated state of the symbol (StateFlags) Private _lazyState As Integer <Flags> Private Enum StateFlags As Integer ''' <summary> ''' If this flag is set this method will be ignored ''' in duplicated signature analysis, see ERR_DuplicateProcDef1 diagnostics. ''' </summary> SuppressDuplicateProcDefDiagnostics = &H1 ''' <summary> ''' Set after all diagnostics have been reported for this symbol. ''' </summary> AllDiagnosticsReported = &H2 End Enum #If DEBUG Then Private _partialMethodInfoIsFrozen As Boolean = False #End If Friend Sub New(containingType As SourceMemberContainerTypeSymbol, name As String, flags As SourceMemberFlags, binder As Binder, syntax As MethodBaseSyntax, arity As Integer, Optional handledEvents As ImmutableArray(Of HandledEvent) = Nothing) MyBase.New(containingType, flags, binder.GetSyntaxReference(syntax)) ' initialized lazily if unset: _lazyHandles = handledEvents _name = name _arity = arity ' Check attributes quickly. _quickAttributes = binder.QuickAttributeChecker.CheckAttributes(syntax.AttributeLists) If Not containingType.AllowsExtensionMethods() Then ' Extension methods in source can only be inside modules. _quickAttributes = _quickAttributes And Not QuickAttributes.Extension End If End Sub Public Overrides ReadOnly Property Name As String Get Return _name End Get End Property Protected Overrides ReadOnly Property BoundAttributesSource As SourceMethodSymbol Get Return Me.SourcePartialDefinition End Get End Property Public Overrides ReadOnly Property MetadataName As String Get If _lazyMetadataName Is Nothing Then ' VB has special rules for changing the metadata name of method overloads/overrides. If MethodKind = MethodKind.Ordinary Then OverloadingHelper.SetMetadataNameForAllOverloads(_name, SymbolKind.Method, m_containingType) Else ' Constructors, conversion operators, etc. just use their regular name. SetMetadataName(_name) End If Debug.Assert(_lazyMetadataName IsNot Nothing) End If Return _lazyMetadataName End Get End Property ' Set the metadata name for this symbol. Called from OverloadingHelper.SetMetadataNameForAllOverloads ' for each symbol of the same name in a type. Friend Overrides Sub SetMetadataName(metadataName As String) Dim old = Interlocked.CompareExchange(_lazyMetadataName, metadataName, Nothing) Debug.Assert(old Is Nothing OrElse old = metadataName) ';If there was a race, make sure it was consistent If Me.IsPartial Then Dim partialImpl = Me.OtherPartOfPartial If partialImpl IsNot Nothing Then partialImpl.SetMetadataName(metadataName) End If End If End Sub Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return MyBase.GenerateDebugInfoImpl AndAlso Not IsAsync End Get End Property Protected Overrides Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) If Me.SourcePartialImplementation IsNot Nothing Then Return OneOrMany.Create(ImmutableArray.Create(AttributeDeclarationSyntaxList, Me.SourcePartialImplementation.AttributeDeclarationSyntaxList)) Else Return OneOrMany.Create(AttributeDeclarationSyntaxList) End If End Function Private Function GetQuickAttributes() As QuickAttributes Dim quickAttrs = _quickAttributes If Me.IsPartial Then Dim partialImpl = Me.OtherPartOfPartial If partialImpl IsNot Nothing Then Return quickAttrs Or partialImpl._quickAttributes End If End If Return quickAttrs End Function Friend Overrides ReadOnly Property MayBeReducibleExtensionMethod As Boolean Get Return (GetQuickAttributes() And QuickAttributes.Extension) <> 0 End Get End Property Public Overrides ReadOnly Property IsExtensionMethod As Boolean Get If MayBeReducibleExtensionMethod Then Return MyBase.IsExtensionMethod Else Return False End If End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) If Me.IsAsync OrElse Me.IsIterator Then AddSynthesizedAttribute(attributes, Me.DeclaringCompilation.SynthesizeStateMachineAttribute(Me, compilationState)) If Me.IsAsync Then ' Async kick-off method calls MoveNext, which contains user code. ' This means we need to emit DebuggerStepThroughAttribute in order ' to have correct stepping behavior during debugging. AddSynthesizedAttribute(attributes, Me.DeclaringCompilation.SynthesizeOptionalDebuggerStepThroughAttribute()) End If End If End Sub Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get If (GetQuickAttributes() And QuickAttributes.Obsolete) <> 0 Then Return MyBase.ObsoleteAttributeData Else Return Nothing End If End Get End Property Friend Overrides Sub GenerateDeclarationErrors(cancellationToken As CancellationToken) If (_lazyState And StateFlags.AllDiagnosticsReported) <> 0 Then Return End If MyBase.GenerateDeclarationErrors(cancellationToken) Dim diagnostics As BindingDiagnosticBag = BindingDiagnosticBag.GetInstance() ' Ensure explicit implementations are resolved. If Not Me.ExplicitInterfaceImplementations.IsEmpty Then ' Check any constraints against implemented methods. ValidateImplementedMethodConstraints(diagnostics) End If Dim methodImpl As SourceMemberMethodSymbol = If(Me.IsPartial, SourcePartialImplementation, Me) If methodImpl IsNot Nothing AndAlso (methodImpl.IsAsync OrElse methodImpl.IsIterator) AndAlso Not methodImpl.ContainingType.IsInterfaceType() Then Dim container As NamedTypeSymbol = methodImpl.ContainingType Do Dim sourceType = TryCast(container, SourceNamedTypeSymbol) If sourceType IsNot Nothing AndAlso sourceType.HasSecurityCriticalAttributes Then Dim location As Location = methodImpl.NonMergedLocation If location IsNot Nothing Then Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_SecurityCriticalAsyncInClassOrStruct) End If Exit Do End If container = container.ContainingType Loop While container IsNot Nothing If methodImpl.IsAsync AndAlso (methodImpl.ImplementationAttributes And Reflection.MethodImplAttributes.Synchronized) <> 0 Then Dim location As Location = methodImpl.NonMergedLocation If location IsNot Nothing Then Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_SynchronizedAsyncMethod) End If End If End If If methodImpl IsNot Nothing AndAlso methodImpl IsNot Me Then ' Check for parameter default value mismatch. Dim result As SymbolComparisonResults = MethodSignatureComparer.DetailedCompare(Me, methodImpl, SymbolComparisonResults.OptionalParameterValueMismatch Or SymbolComparisonResults.ParamArrayMismatch) If result <> Nothing Then Dim location As Location = methodImpl.NonMergedLocation If location IsNot Nothing Then If (result And SymbolComparisonResults.ParamArrayMismatch) <> 0 Then Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_PartialMethodParamArrayMismatch2, methodImpl, Me) ElseIf (result And SymbolComparisonResults.OptionalParameterValueMismatch) <> 0 Then Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_PartialMethodDefaultParameterValueMismatch2, methodImpl, Me) End If End If End If End If ContainingSourceModule.AtomicSetFlagAndStoreDiagnostics(_lazyState, StateFlags.AllDiagnosticsReported, 0, diagnostics) diagnostics.Free() End Sub #Region "Type Parameters" Public Overrides ReadOnly Property Arity As Integer Get Return _arity End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Dim params = _lazyTypeParameters If params.IsDefault Then Dim diagBag = BindingDiagnosticBag.GetInstance Dim sourceModule = DirectCast(Me.ContainingModule, SourceModuleSymbol) params = GetTypeParameters(sourceModule, diagBag) sourceModule.AtomicStoreArrayAndDiagnostics(_lazyTypeParameters, params, diagBag) diagBag.Free() params = _lazyTypeParameters End If Return params End Get End Property Private Function GetTypeParameters(sourceModule As SourceModuleSymbol, diagBag As BindingDiagnosticBag) As ImmutableArray(Of TypeParameterSymbol) Dim paramList = GetTypeParameterListSyntax(Me.DeclarationSyntax) If paramList Is Nothing Then Return ImmutableArray(Of TypeParameterSymbol).Empty End If Dim binder As Binder = BinderBuilder.CreateBinderForType(sourceModule, Me.SyntaxTree, m_containingType) Dim typeParamsSyntax = paramList.Parameters Dim arity As Integer = typeParamsSyntax.Count Dim typeParameters(0 To arity - 1) As TypeParameterSymbol For i = 0 To arity - 1 Dim typeParamSyntax = typeParamsSyntax(i) Dim ident = typeParamSyntax.Identifier Binder.DisallowTypeCharacter(ident, diagBag, ERRID.ERR_TypeCharOnGenericParam) typeParameters(i) = New SourceTypeParameterOnMethodSymbol(Me, i, ident.ValueText, binder.GetSyntaxReference(typeParamSyntax)) ' method type parameters cannot have same name as containing Function (but can for a Sub) If Me.DeclarationSyntax.Kind = SyntaxKind.FunctionStatement AndAlso CaseInsensitiveComparison.Equals(Me.Name, ident.ValueText) Then Binder.ReportDiagnostic(diagBag, typeParamSyntax, ERRID.ERR_TypeParamNameFunctionNameCollision) End If Next ' Add the type parameters to our binder for binding parameters and return values binder = New MethodTypeParametersBinder(binder, typeParameters.AsImmutableOrNull) Dim containingSourceType = TryCast(ContainingType, SourceNamedTypeSymbol) If containingSourceType IsNot Nothing Then containingSourceType.CheckForDuplicateTypeParameters(typeParameters.AsImmutableOrNull, diagBag) End If Return typeParameters.AsImmutableOrNull End Function #End Region #Region "Explicit Interface Implementations" Friend Function HasExplicitInterfaceImplementations() As Boolean Dim syntax = TryCast(Me.DeclarationSyntax, MethodStatementSyntax) Return syntax IsNot Nothing AndAlso syntax.ImplementsClause IsNot Nothing End Function Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get If _lazyImplementedMethods.IsDefault Then Dim sourceModule = DirectCast(Me.ContainingModule, SourceModuleSymbol) Dim diagnostics = BindingDiagnosticBag.GetInstance() Dim implementedMethods As ImmutableArray(Of MethodSymbol) If Me.IsPartial Then ' Partial method declaration itself cannot have Implements clause (an error should ' be reported) and just returns implemented methods from the implementation ' Report diagnostic if needed Debug.Assert(Me.SyntaxTree IsNot Nothing) Dim syntax = TryCast(Me.DeclarationSyntax, MethodStatementSyntax) If (syntax IsNot Nothing) AndAlso (syntax.ImplementsClause IsNot Nothing) Then ' Don't allow implements on partial method declarations. diagnostics.Add(ERRID.ERR_PartialDeclarationImplements1, syntax.Identifier.GetLocation(), syntax.Identifier.ToString()) End If ' Store implemented interface methods from the partial method implementation. Dim implementation As MethodSymbol = Me.PartialImplementationPart implementedMethods = If(implementation Is Nothing, ImmutableArray(Of MethodSymbol).Empty, implementation.ExplicitInterfaceImplementations) Else implementedMethods = Me.GetExplicitInterfaceImplementations(sourceModule, diagnostics) End If sourceModule.AtomicStoreArrayAndDiagnostics(_lazyImplementedMethods, implementedMethods, diagnostics) diagnostics.Free() End If Return _lazyImplementedMethods End Get End Property Private Function GetExplicitInterfaceImplementations(sourceModule As SourceModuleSymbol, diagBag As BindingDiagnosticBag) As ImmutableArray(Of MethodSymbol) Debug.Assert(Not Me.IsPartial) Dim syntax = TryCast(Me.DeclarationSyntax, MethodStatementSyntax) If (syntax IsNot Nothing) AndAlso (syntax.ImplementsClause IsNot Nothing) Then Dim binder As Binder = BinderBuilder.CreateBinderForType(sourceModule, Me.SyntaxTree, ContainingType) If Me.IsShared And Not ContainingType.IsModuleType Then ' Implementing with shared methods is illegal. ' Module case is caught inside ProcessImplementsClause and has different message. Binder.ReportDiagnostic(diagBag, syntax.Modifiers.First(SyntaxKind.SharedKeyword), ERRID.ERR_SharedOnProcThatImpl, syntax.Identifier.ToString()) ' Don't clear the Shared flag because then you get errors from semantics about needing an object reference to the non-shared member, etc. Else Return ProcessImplementsClause(Of MethodSymbol)(syntax.ImplementsClause, Me, DirectCast(ContainingType, SourceMemberContainerTypeSymbol), binder, diagBag) End If End If Return ImmutableArray(Of MethodSymbol).Empty End Function ''' <summary> ''' Validate method type parameter constraints against implemented methods. ''' </summary> Friend Sub ValidateImplementedMethodConstraints(diagnostics As BindingDiagnosticBag) If Me.IsPartial AndAlso Me.OtherPartOfPartial IsNot Nothing Then Me.OtherPartOfPartial.ValidateImplementedMethodConstraints(diagnostics) Else Dim implementedMethods = ExplicitInterfaceImplementations If implementedMethods.IsEmpty Then Return End If For Each implementedMethod In implementedMethods ImplementsHelper.ValidateImplementedMethodConstraints(Me, implementedMethod, diagnostics) Next End If End Sub #End Region #Region "Partials" Friend Overrides ReadOnly Property HasEmptyBody As Boolean Get If Not MyBase.HasEmptyBody Then Return False End If Dim impl = SourcePartialImplementation Return impl Is Nothing OrElse impl.HasEmptyBody End Get End Property Friend ReadOnly Property IsPartialDefinition As Boolean Get Return Me.IsPartial End Get End Property Friend ReadOnly Property IsPartialImplementation As Boolean Get Return Not IsPartialDefinition AndAlso Me.OtherPartOfPartial IsNot Nothing End Get End Property Public ReadOnly Property SourcePartialDefinition As SourceMemberMethodSymbol Get Return If(IsPartialDefinition, Nothing, Me.OtherPartOfPartial) End Get End Property Public ReadOnly Property SourcePartialImplementation As SourceMemberMethodSymbol Get Return If(IsPartialDefinition, Me.OtherPartOfPartial, Nothing) End Get End Property Public Overrides ReadOnly Property PartialDefinitionPart As MethodSymbol Get Return SourcePartialDefinition End Get End Property Public Overrides ReadOnly Property PartialImplementationPart As MethodSymbol Get Return SourcePartialImplementation End Get End Property Friend Property OtherPartOfPartial As SourceMemberMethodSymbol Get #If DEBUG Then Me._partialMethodInfoIsFrozen = True #End If Return Me._otherPartOfPartial End Get Private Set(value As SourceMemberMethodSymbol) Dim oldValue As SourceMemberMethodSymbol = Me._otherPartOfPartial Me._otherPartOfPartial = value #If DEBUG Then ' As we want to make sure we always validate attributes on partial ' method declaration, we need to make sure we don't validate ' attributes before PartialMethodCounterpart is assigned Debug.Assert(Me.m_lazyCustomAttributesBag Is Nothing) Debug.Assert(Me.m_lazyReturnTypeCustomAttributesBag Is Nothing) For Each param In Me.Parameters Dim complexParam = TryCast(param, SourceComplexParameterSymbol) If complexParam IsNot Nothing Then complexParam.AssertAttributesNotValidatedYet() End If Next ' If partial method info is frozen the new and the old values must be equal Debug.Assert(Not Me._partialMethodInfoIsFrozen OrElse oldValue Is value) Me._partialMethodInfoIsFrozen = True #End If End Set End Property Friend Property SuppressDuplicateProcDefDiagnostics As Boolean Get #If DEBUG Then Me._partialMethodInfoIsFrozen = True #End If Return (_lazyState And StateFlags.SuppressDuplicateProcDefDiagnostics) <> 0 End Get Set(value As Boolean) Dim stateChanged = ThreadSafeFlagOperations.Set(_lazyState, StateFlags.SuppressDuplicateProcDefDiagnostics) #If DEBUG Then ' If partial method info is frozen the new and the old values must be equal Debug.Assert(Not Me._partialMethodInfoIsFrozen OrElse Not stateChanged) Me._partialMethodInfoIsFrozen = True #End If End Set End Property ''' <summary> ''' This method is to be called to assign implementation to a partial method. ''' </summary> Friend Shared Sub InitializePartialMethodParts(definition As SourceMemberMethodSymbol, implementation As SourceMemberMethodSymbol) Debug.Assert(definition.IsPartial) Debug.Assert(implementation Is Nothing OrElse Not implementation.IsPartial) definition.OtherPartOfPartial = implementation If implementation IsNot Nothing Then implementation.OtherPartOfPartial = definition End If End Sub Friend Overrides Function GetBoundMethodBody(compilationState As TypeCompilationState, diagnostics As BindingDiagnosticBag, Optional ByRef methodBodyBinder As Binder = Nothing) As BoundBlock If Me.IsPartial Then Throw ExceptionUtilities.Unreachable End If Return MyBase.GetBoundMethodBody(compilationState, diagnostics, methodBodyBinder) End Function #End Region #Region "Handles" Public Overrides ReadOnly Property HandledEvents As ImmutableArray(Of HandledEvent) Get If _lazyHandles.IsDefault Then Dim sourceModule = DirectCast(Me.ContainingModule, SourceModuleSymbol) Dim diagnostics = BindingDiagnosticBag.GetInstance() Dim boundHandledEvents = Me.GetHandles(sourceModule, diagnostics) sourceModule.AtomicStoreArrayAndDiagnostics(Of HandledEvent)(_lazyHandles, boundHandledEvents, diagnostics) diagnostics.Free() End If Return _lazyHandles End Get End Property Private Function GetHandles(sourceModule As SourceModuleSymbol, diagBag As BindingDiagnosticBag) As ImmutableArray(Of HandledEvent) Dim syntax = TryCast(Me.DeclarationSyntax, MethodStatementSyntax) If (syntax Is Nothing) OrElse (syntax.HandlesClause Is Nothing) Then Return ImmutableArray(Of HandledEvent).Empty End If Dim typeBinder As Binder = BinderBuilder.CreateBinderForType(sourceModule, Me.SyntaxTree, m_containingType) typeBinder = New LocationSpecificBinder(BindingLocation.HandlesClause, Me, typeBinder) Dim handlesBuilder = ArrayBuilder(Of HandledEvent).GetInstance For Each singleHandleClause As HandlesClauseItemSyntax In syntax.HandlesClause.Events Dim handledEventResult = BindSingleHandlesClause(singleHandleClause, typeBinder, diagBag) If handledEventResult IsNot Nothing Then handlesBuilder.Add(handledEventResult) End If Next Return handlesBuilder.ToImmutableAndFree End Function Friend Function BindSingleHandlesClause(singleHandleClause As HandlesClauseItemSyntax, typeBinder As Binder, diagBag As BindingDiagnosticBag, Optional candidateEventSymbols As ArrayBuilder(Of Symbol) = Nothing, Optional candidateWithEventsSymbols As ArrayBuilder(Of Symbol) = Nothing, Optional candidateWithEventsPropertySymbols As ArrayBuilder(Of Symbol) = Nothing, Optional ByRef resultKind As LookupResultKind = Nothing) As HandledEvent Dim handlesKind As HandledEventKind Dim eventContainingType As TypeSymbol = Nothing Dim withEventsSourceProperty As PropertySymbol = Nothing ' This is the WithEvents property that looks as event container to the user. (it could be in a base class) Dim witheventsProperty As PropertySymbol = Nothing ' This is the WithEvents property that will actually used to hookup handlers. (it could be a proxy override) Dim witheventsPropertyInCurrentClass As PropertySymbol = Nothing If Me.ContainingType.IsModuleType AndAlso singleHandleClause.EventContainer.Kind <> SyntaxKind.WithEventsEventContainer Then Binder.ReportDiagnostic(diagBag, singleHandleClause, ERRID.ERR_HandlesSyntaxInModule) Return Nothing End If Dim eventContainerKind = singleHandleClause.EventContainer.Kind Dim useSiteInfo = typeBinder.GetNewCompoundUseSiteInfo(diagBag) If eventContainerKind = SyntaxKind.KeywordEventContainer Then Select Case DirectCast(singleHandleClause.EventContainer, KeywordEventContainerSyntax).Keyword.Kind Case SyntaxKind.MeKeyword handlesKind = HandledEventKind.Me eventContainingType = Me.ContainingType Case SyntaxKind.MyClassKeyword handlesKind = HandledEventKind.MyClass eventContainingType = Me.ContainingType Case SyntaxKind.MyBaseKeyword handlesKind = HandledEventKind.MyBase eventContainingType = Me.ContainingType.BaseTypeNoUseSiteDiagnostics End Select ElseIf eventContainerKind = SyntaxKind.WithEventsEventContainer OrElse eventContainerKind = SyntaxKind.WithEventsPropertyEventContainer Then handlesKind = HandledEventKind.WithEvents Dim witheventsContainer = If(eventContainerKind = SyntaxKind.WithEventsPropertyEventContainer, DirectCast(singleHandleClause.EventContainer, WithEventsPropertyEventContainerSyntax).WithEventsContainer, DirectCast(singleHandleClause.EventContainer, WithEventsEventContainerSyntax)) Dim witheventsName = witheventsContainer.Identifier.ValueText witheventsProperty = FindWithEventsProperty(m_containingType, typeBinder, witheventsName, useSiteInfo, candidateWithEventsSymbols, resultKind) diagBag.Add(singleHandleClause.EventContainer, useSiteInfo) useSiteInfo = New CompoundUseSiteInfo(Of AssemblySymbol)(useSiteInfo) If witheventsProperty Is Nothing Then Binder.ReportDiagnostic(diagBag, singleHandleClause.EventContainer, ERRID.ERR_NoWithEventsVarOnHandlesList) Return Nothing End If Dim isFromBase = Not TypeSymbol.Equals(witheventsProperty.ContainingType, Me.ContainingType, TypeCompareKind.ConsiderEverything) If witheventsProperty.IsShared Then Debug.Assert(Not witheventsProperty.IsOverridable) If Not Me.IsShared Then 'Events of shared WithEvents variables cannot be handled by non-shared methods. Binder.ReportDiagnostic(diagBag, singleHandleClause.EventContainer, ERRID.ERR_SharedEventNeedsSharedHandler) End If If isFromBase Then Binder.ReportDiagnostic(diagBag, singleHandleClause.EventContainer, ERRID.ERR_SharedEventNeedsHandlerInTheSameType) End If End If If eventContainerKind = SyntaxKind.WithEventsPropertyEventContainer Then Dim propName = DirectCast(singleHandleClause.EventContainer, WithEventsPropertyEventContainerSyntax).Property.Identifier.ValueText withEventsSourceProperty = FindProperty(witheventsProperty.Type, typeBinder, propName, useSiteInfo, candidateWithEventsPropertySymbols, resultKind) If withEventsSourceProperty Is Nothing Then Binder.ReportDiagnostic(diagBag, singleHandleClause.EventContainer, ERRID.ERR_HandlesSyntaxInClass) Return Nothing End If eventContainingType = withEventsSourceProperty.Type Else eventContainingType = witheventsProperty.Type End If ' if was found in one of bases, need to override it If isFromBase Then witheventsPropertyInCurrentClass = DirectCast(Me.ContainingType, SourceNamedTypeSymbol).GetOrAddWithEventsOverride(witheventsProperty) Else witheventsPropertyInCurrentClass = witheventsProperty End If typeBinder.ReportDiagnosticsIfObsoleteOrNotSupportedByRuntime(diagBag, witheventsPropertyInCurrentClass, singleHandleClause.EventContainer) Else Binder.ReportDiagnostic(diagBag, singleHandleClause.EventContainer, ERRID.ERR_HandlesSyntaxInClass) Return Nothing End If Dim eventName As String = singleHandleClause.EventMember.Identifier.ValueText Dim eventSymbol As EventSymbol = Nothing If eventContainingType IsNot Nothing Then Binder.ReportUseSite(diagBag, singleHandleClause.EventMember, eventContainingType) ' Bind event symbol eventSymbol = FindEvent(eventContainingType, typeBinder, eventName, handlesKind = HandledEventKind.MyBase, useSiteInfo, candidateEventSymbols, resultKind) End If diagBag.Add(singleHandleClause.EventMember, useSiteInfo) If eventSymbol Is Nothing Then 'Event '{0}' cannot be found. Binder.ReportDiagnostic(diagBag, singleHandleClause.EventMember, ERRID.ERR_EventNotFound1, eventName) Return Nothing End If typeBinder.ReportDiagnosticsIfObsoleteOrNotSupportedByRuntime(diagBag, eventSymbol, singleHandleClause.EventMember) Binder.ReportUseSite(diagBag, singleHandleClause.EventMember, eventSymbol) If eventSymbol.AddMethod IsNot Nothing Then Binder.ReportUseSite(diagBag, singleHandleClause.EventMember, eventSymbol.AddMethod) End If If eventSymbol.RemoveMethod IsNot Nothing Then Binder.ReportUseSite(diagBag, singleHandleClause.EventMember, eventSymbol.RemoveMethod) End If ' For WinRT events, we require that certain well-known members be present (needed in synthesize code). If eventSymbol.IsWindowsRuntimeEvent Then typeBinder.GetWellKnownTypeMember( WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__AddEventHandler, singleHandleClause.EventMember, diagBag) typeBinder.GetWellKnownTypeMember( WellKnownMember.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T__RemoveEventHandler, singleHandleClause.EventMember, diagBag) End If Select Case ContainingType.TypeKind Case TypeKind.Interface, TypeKind.Structure, TypeKind.Enum, TypeKind.Delegate ' Handles clause is invalid in this context. Return Nothing Case TypeKind.Class, TypeKind.Module ' Valid context Case Else Throw ExceptionUtilities.UnexpectedValue(ContainingType.TypeKind) End Select Dim receiverOpt As BoundExpression = Nothing ' synthesize delegate creation (may involve relaxation) Dim hookupMethod As MethodSymbol = Nothing If handlesKind = HandledEventKind.WithEvents Then hookupMethod = witheventsPropertyInCurrentClass.SetMethod Else If eventSymbol.IsShared AndAlso Me.IsShared Then ' if both method and event are shared, host method is shared ctor hookupMethod = Me.ContainingType.SharedConstructors(0) ' There will only be one in a correct program. Else ' if either method, or event are not shared, host method is instance ctor Dim instanceCtors = Me.ContainingType.InstanceConstructors Debug.Assert(Not instanceCtors.IsEmpty, "bind non-type members should have ensured at least one ctor for us") ' any instance ctor will do for our purposes here. ' We will only use "Me" and that does not need to be from a particular ctor. hookupMethod = instanceCtors(0) End If End If Debug.Assert(hookupMethod IsNot Nothing, "bind non-type members should have ensured appropriate host method for handles injection") ' No use site errors, since method is from source (or synthesized) If Not hookupMethod.IsShared Then receiverOpt = New BoundMeReference(singleHandleClause, Me.ContainingType).MakeCompilerGenerated End If Dim handlingMethod As MethodSymbol = Me If Me.PartialDefinitionPart IsNot Nothing Then ' it is ok for a partial method to have Handles, but if there is a definition part, ' it is the definition method that will do the handling handlingMethod = Me.PartialDefinitionPart End If Dim qualificationKind As QualificationKind If hookupMethod.IsShared Then qualificationKind = QualificationKind.QualifiedViaTypeName Else qualificationKind = QualificationKind.QualifiedViaValue End If Dim syntheticMethodGroup = New BoundMethodGroup( singleHandleClause, Nothing, ImmutableArray.Create(Of MethodSymbol)(handlingMethod), LookupResultKind.Good, receiverOpt, qualificationKind:=qualificationKind) ' AddressOf currentMethod Dim syntheticAddressOf = New BoundAddressOfOperator(singleHandleClause, typeBinder, diagBag.AccumulatesDependencies, syntheticMethodGroup).MakeCompilerGenerated ' 9.2.6 Event handling ' ... A handler method M is considered a valid event handler for an event E ' if the statement " AddHandler E, AddressOf M " would also be valid. ' Unlike an AddHandler statement, however, explicit event handlers allow ' handling an event with a method with no arguments regardless of ' whether strict semantics are being used or not. Dim resolutionResult = Binder.InterpretDelegateBinding(syntheticAddressOf, eventSymbol.Type, isForHandles:=True) If Not Conversions.ConversionExists(resolutionResult.DelegateConversions) Then ' TODO: Consider skip reporting this diagnostic if "ERR_SharedEventNeedsSharedHandler" was already reported above. 'Method '{0}' cannot handle event '{1}' because they do not have a compatible signature. Binder.ReportDiagnostic(diagBag, singleHandleClause.EventMember, ERRID.ERR_EventHandlerSignatureIncompatible2, Me.Name, eventName) Return Nothing Else diagBag.AddDependencies(resolutionResult.Diagnostics.Dependencies) End If Dim delegateCreation = typeBinder.ReclassifyAddressOf(syntheticAddressOf, resolutionResult, eventSymbol.Type, diagBag, isForHandles:=True, warnIfResultOfAsyncMethodIsDroppedDueToRelaxation:=True) Dim handledEventResult = New HandledEvent(handlesKind, eventSymbol, witheventsProperty, withEventsSourceProperty, delegateCreation, hookupMethod) Return handledEventResult End Function Friend Shared Function FindWithEventsProperty(containingType As TypeSymbol, binder As Binder, name As String, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), Optional candidateEventSymbols As ArrayBuilder(Of Symbol) = Nothing, Optional ByRef resultKind As LookupResultKind = Nothing) As PropertySymbol Dim witheventsLookup = LookupResult.GetInstance ' WithEvents properties are always accessed via Me/MyBase Dim options = LookupOptions.IgnoreExtensionMethods Or LookupOptions.UseBaseReferenceAccessibility binder.LookupMember(witheventsLookup, containingType, name, 0, options, useSiteInfo) If candidateEventSymbols IsNot Nothing Then candidateEventSymbols.AddRange(witheventsLookup.Symbols) resultKind = witheventsLookup.Kind End If Dim result As PropertySymbol = Nothing If witheventsLookup.IsGood Then If witheventsLookup.HasSingleSymbol Then Dim prop = TryCast(witheventsLookup.SingleSymbol, PropertySymbol) If prop IsNot Nothing AndAlso prop.IsWithEvents Then result = prop Else resultKind = LookupResultKind.NotAWithEventsMember End If Else resultKind = LookupResultKind.Ambiguous End If End If witheventsLookup.Free() Return result End Function Friend Shared Function FindEvent(containingType As TypeSymbol, binder As Binder, name As String, isThroughMyBase As Boolean, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), Optional candidateEventSymbols As ArrayBuilder(Of Symbol) = Nothing, Optional ByRef resultKind As LookupResultKind = Nothing) As EventSymbol Dim options = LookupOptions.IgnoreExtensionMethods Or LookupOptions.EventsOnly If isThroughMyBase Then options = options Or LookupOptions.UseBaseReferenceAccessibility End If Dim eventLookup = LookupResult.GetInstance binder.LookupMember(eventLookup, containingType, name, 0, options, useSiteInfo) If candidateEventSymbols IsNot Nothing Then candidateEventSymbols.AddRange(eventLookup.Symbols) resultKind = eventLookup.Kind End If Dim result As EventSymbol = Nothing If eventLookup.IsGood Then If eventLookup.HasSingleSymbol Then result = TryCast(eventLookup.SingleSymbol, EventSymbol) If result Is Nothing Then resultKind = LookupResultKind.NotAnEvent End If Else ' finding more than one item is ambiguous resultKind = LookupResultKind.Ambiguous End If End If eventLookup.Free() Return result End Function Private Shared Function FindProperty(containingType As TypeSymbol, binder As Binder, name As String, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol), Optional candidatePropertySymbols As ArrayBuilder(Of Symbol) = Nothing, Optional ByRef resultKind As LookupResultKind = Nothing) As PropertySymbol ' // Note: ' // - we don't support finding the Property if it is overloaded ' // across classes. ' // - Also note that we don't support digging into bases. This was ' // how the previous impl. was. ' // Given that this is not a user feature, we don't bother doing ' // this extra work. Dim options = CType(LookupOptions.IgnoreExtensionMethods Or LookupOptions.NoBaseClassLookup, LookupOptions) Dim propertyLookup = LookupResult.GetInstance binder.LookupMember(propertyLookup, containingType, name, 0, options, useSiteInfo) If candidatePropertySymbols IsNot Nothing Then candidatePropertySymbols.AddRange(propertyLookup.Symbols) resultKind = propertyLookup.Kind End If Dim result As PropertySymbol = Nothing If propertyLookup.IsGood Then Dim symbols = propertyLookup.Symbols For Each symbol In symbols If symbol.Kind = SymbolKind.Property Then 'Function ValidEventSourceProperty( _ ' ByVal [Property] As BCSym.[Property] _ ') As Boolean ' ' // We only care about properties returning classes or interfaces ' ' // because only classes and interfaces can be specified in a ' ' // handles clause. ' ' // ' Return _ ' [Property].ReturnsEventSource() AndAlso _ ' [Property].GetParameterCount() = 0 AndAlso _ ' [Property].GetProperty() IsNot Nothing AndAlso _ ' IsClassOrInterface([Property]._GetType()) ' End Function Dim prop = DirectCast(symbol, PropertySymbol) If prop.Parameters.Any Then Continue For End If ' here we have parameterless property, it must be ours, As long as it is readable. If prop.GetMethod IsNot Nothing AndAlso prop.GetMethod.ReturnType.IsClassOrInterfaceType AndAlso ReturnsEventSource(prop, binder.Compilation) Then ' finding more than one item would seem ambiguous ' not sure if this can happen though, ' regardless, native compiler does not consider it an error ' it just uses the first found item. result = prop Exit For End If End If Next If result Is Nothing Then resultKind = LookupResultKind.Empty End If End If propertyLookup.Free() Return result End Function Private Shared Function ReturnsEventSource(prop As PropertySymbol, compilation As VisualBasicCompilation) As Boolean Dim attrs = prop.GetAttributes() For Each attr In attrs If attr.AttributeClass Is compilation.GetWellKnownType(WellKnownType.System_ComponentModel_DesignerSerializationVisibilityAttribute) Then Dim args = attr.CommonConstructorArguments If args.Length = 1 Then Dim arg = args(0) Const DESIGNERSERIALIZATIONVISIBILITYTYPE_CONTENT As Integer = 2 If arg.Kind <> TypedConstantKind.Array AndAlso CInt(arg.ValueInternal) = DESIGNERSERIALIZATIONVISIBILITYTYPE_CONTENT Then Return True End If End If End If Next Return False End Function #End Region End Class End Namespace
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/EditorFeatures/CSharpTest/EditAndContinue/TopLevelEditingTests.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.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class TopLevelEditingTests : EditingTestBase { #region Usings [Fact] public void Using_Global_Insert() { var src1 = @" using System.Collections.Generic; "; var src2 = @" global using D = System.Diagnostics; global using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [global using D = System.Diagnostics;]@2", "Insert [global using System.Collections;]@40"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Delete1() { var src1 = @" using System.Diagnostics; "; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [using System.Diagnostics;]@2"); Assert.IsType<UsingDirectiveSyntax>(edits.Edits.First().OldNode); Assert.Null(edits.Edits.First().NewNode); } [Fact] public void Using_Delete2() { var src1 = @" using D = System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [using D = System.Diagnostics;]@2", "Delete [using System.Collections;]@33"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Insert() { var src1 = @" using System.Collections.Generic; "; var src2 = @" using D = System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using D = System.Diagnostics;]@2", "Insert [using System.Collections;]@33"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update1() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Diagnostics; using X = System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using System.Collections;]@29 -> [using X = System.Collections;]@29"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update2() { var src1 = @" using System.Diagnostics; using X1 = System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Diagnostics; using X2 = System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using X1 = System.Collections;]@29 -> [using X2 = System.Collections;]@29"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update3() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System; using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using System.Diagnostics;]@2 -> [using System;]@2"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Reorder1() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Collections; using System.Collections.Generic; using System.Diagnostics; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [using System.Diagnostics;]@2 -> @64"); } [Fact] public void Using_InsertDelete1() { var src1 = @" namespace N { using System.Collections; } namespace M { } "; var src2 = @" namespace N { } namespace M { using System.Collections; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using System.Collections;]@43", "Delete [using System.Collections;]@22"); } [Fact] public void Using_InsertDelete2() { var src1 = @" namespace N { using System.Collections; } "; var src2 = @" using System.Collections; namespace N { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using System.Collections;]@2", "Delete [using System.Collections;]@22"); } [Fact] public void Using_Delete_ChangesCodeMeaning() { // This test specifically validates the scenario we _don't_ support, namely when inserting or deleting // a using directive, if existing code changes in meaning as a result, we don't issue edits for that code. // If this ever regresses then please buy a lottery ticket because the feature has magically fixed itself. var src1 = @" using System.IO; using DirectoryInfo = N.C; namespace N { public class C { public C(string a) { } public FileAttributes Attributes { get; set; } } public class D { public void M() { var d = new DirectoryInfo(""aa""); var x = directoryInfo.Attributes; } } }"; var src2 = @" using System.IO; namespace N { public class C { public C(string a) { } public FileAttributes Attributes { get; set; } } public class D { public void M() { var d = new DirectoryInfo(""aa""); var x = directoryInfo.Attributes; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [using DirectoryInfo = N.C;]@20"); edits.VerifySemantics(); } [Fact] public void Using_Insert_ForNewCode() { // As distinct from the above, this test validates a real world scenario of inserting a using directive // and changing code that utilizes the new directive to some effect. var src1 = @" namespace N { class Program { static void Main(string[] args) { } } }"; var src2 = @" using System; namespace N { class Program { static void Main(string[] args) { Console.WriteLine(""Hello World!""); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main"))); } [Fact] public void Using_Delete_ForOldCode() { var src1 = @" using System; namespace N { class Program { static void Main(string[] args) { Console.WriteLine(""Hello World!""); } } }"; var src2 = @" namespace N { class Program { static void Main(string[] args) { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main"))); } [Fact] public void Using_Insert_CreatesAmbiguousCode() { // This test validates that we still issue edits for changed valid code, even when unchanged // code has ambiguities after adding a using. var src1 = @" using System.Threading; namespace N { class C { void M() { // Timer exists in System.Threading and System.Timers var t = new Timer(s => System.Console.WriteLine(s)); } } }"; var src2 = @" using System.Threading; using System.Timers; namespace N { class C { void M() { // Timer exists in System.Threading and System.Timers var t = new Timer(s => System.Console.WriteLine(s)); } void M2() { // TimersDescriptionAttribute only exists in System.Timers System.Console.WriteLine(new TimersDescriptionAttribute("""")); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("N.C.M2"))); } #endregion #region Extern Alias [Fact] public void ExternAliasUpdate() { var src1 = "extern alias X;"; var src2 = "extern alias Y;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [extern alias X;]@0 -> [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Update, "extern alias Y;", CSharpFeaturesResources.extern_alias)); } [Fact] public void ExternAliasInsert() { var src1 = ""; var src2 = "extern alias Y;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "extern alias Y;", CSharpFeaturesResources.extern_alias)); } [Fact] public void ExternAliasDelete() { var src1 = "extern alias Y;"; var src2 = ""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.extern_alias)); } #endregion #region Assembly/Module Attributes [Fact] public void Insert_TopLevelAttribute() { var src1 = ""; var src2 = "[assembly: System.Obsolete(\"2\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [[assembly: System.Obsolete(\"2\")]]@0", "Insert [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "[assembly: System.Obsolete(\"2\")]", FeaturesResources.attribute)); } [Fact] public void Delete_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"2\")]"; var src2 = ""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [[assembly: System.Obsolete(\"2\")]]@0", "Delete [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, FeaturesResources.attribute)); } [Fact] public void Update_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"1\")]"; var src2 = "[assembly: System.Obsolete(\"2\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[assembly: System.Obsolete(\"1\")]]@0 -> [[assembly: System.Obsolete(\"2\")]]@0", "Update [System.Obsolete(\"1\")]@11 -> [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Update, "System.Obsolete(\"2\")", FeaturesResources.attribute)); } [Fact] public void Reorder_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"1\")][assembly: System.Obsolete(\"2\")]"; var src2 = "[assembly: System.Obsolete(\"2\")][assembly: System.Obsolete(\"1\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [[assembly: System.Obsolete(\"2\")]]@32 -> @0"); edits.VerifyRudeDiagnostics(); } #endregion #region Types [Theory] [InlineData("class", "struct")] [InlineData("class", "record")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874 [InlineData("class", "record struct")] [InlineData("class", "interface")] [InlineData("struct", "record struct")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874 public void Type_Kind_Update(string oldKeyword, string newKeyword) { var src1 = oldKeyword + " C { }"; var src2 = newKeyword + " C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + oldKeyword + " C { }]@0 -> [" + newKeyword + " C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeKindUpdate, newKeyword + " C")); } [Theory] [InlineData("class", "struct")] [InlineData("class", "record")] [InlineData("class", "record struct")] [InlineData("class", "interface")] [InlineData("struct", "record struct")] public void Type_Kind_Update_Reloadable(string oldKeyword, string newKeyword) { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + newKeyword + " C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }]@145 -> [[CreateNewOnMetadataUpdate]" + newKeyword + " C { }]@145"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Modifiers_Static_Remove() { var src1 = "public static class C { }"; var src2 = "public class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public static class C { }]@0 -> [public class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public class C", FeaturesResources.class_)); } [Theory] [InlineData("public")] [InlineData("protected")] [InlineData("private")] [InlineData("private protected")] [InlineData("internal protected")] public void Type_Modifiers_Accessibility_Change(string accessibility) { var src1 = accessibility + " class C { }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + accessibility + " class C { }]@0 -> [class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", FeaturesResources.class_)); } [Theory] [InlineData("public", "public")] [InlineData("internal", "internal")] [InlineData("", "internal")] [InlineData("internal", "")] [InlineData("protected", "protected")] [InlineData("private", "private")] [InlineData("private protected", "private protected")] [InlineData("internal protected", "internal protected")] public void Type_Modifiers_Accessibility_Partial(string accessibilityA, string accessibilityB) { var srcA1 = accessibilityA + " partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = accessibilityB + " partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(), }); } [Fact] public void Type_Modifiers_Internal_Remove() { var src1 = "internal interface C { }"; var src2 = "interface C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_Modifiers_Internal_Add() { var src1 = "struct C { }"; var src2 = "internal struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_Modifiers_Accessibility_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]public class C { }]@145 -> [[CreateNewOnMetadataUpdate]internal class C { }]@145"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPrivateInInterface_Remove(string keyword) { var src1 = "interface C { private " + keyword + " S { } }"; var src2 = "interface C { " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, keyword + " S", GetResource(keyword))); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPrivateInClass_Add(string keyword) { var src1 = "class C { " + keyword + " S { } }"; var src2 = "class C { private " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPublicInInterface_Add(string keyword) { var src1 = "interface C { " + keyword + " S { } }"; var src2 = "interface C { public " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Add() { var src1 = "public class C { }"; var src2 = "public unsafe class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public class C { }]@0 -> [public unsafe class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Remove() { var src1 = @" using System; unsafe delegate void D(); class C { unsafe class N { } public unsafe event Action<int> A { add { } remove { } } unsafe int F() => 0; unsafe int X; unsafe int Y { get; } unsafe C() {} unsafe ~C() {} } "; var src2 = @" using System; delegate void D(); class C { class N { } public event Action<int> A { add { } remove { } } int F() => 0; int X; int Y { get; } C() {} ~C() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [unsafe delegate void D();]@17 -> [delegate void D();]@17", "Update [unsafe class N { }]@60 -> [class N { }]@53", "Update [public unsafe event Action<int> A { add { } remove { } }]@84 -> [public event Action<int> A { add { } remove { } }]@70", "Update [unsafe int F() => 0;]@146 -> [int F() => 0;]@125", "Update [unsafe int X;]@172 -> [int X;]@144", "Update [unsafe int Y { get; }]@191 -> [int Y { get; }]@156", "Update [unsafe C() {}]@218 -> [C() {}]@176", "Update [unsafe ~C() {}]@237 -> [~C() {}]@188"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_DeleteInsert() { var srcA1 = "partial class C { unsafe void F() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }), }); } [Fact] public void Type_Modifiers_Ref_Add() { var src1 = "public struct C { }"; var src2 = "public ref struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public struct C { }]@0 -> [public ref struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public ref struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_Ref_Remove() { var src1 = "public ref struct C { }"; var src2 = "public struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public ref struct C { }]@0 -> [public struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_ReadOnly_Add() { var src1 = "public struct C { }"; var src2 = "public readonly struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public struct C { }]@0 -> [public readonly struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_ReadOnly_Remove() { var src1 = "public readonly struct C { }"; var src2 = "public struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public readonly struct C { }]@0 -> [public struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Attribute_Update_NotSupportedByRuntime1() { var attribute = "public class A1Attribute : System.Attribute { }\n\n" + "public class A2Attribute : System.Attribute { }\n\n"; var src1 = attribute + "[A1]class C { }"; var src2 = attribute + "[A2]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A1]class C { }]@98 -> [[A2]class C { }]@98"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Update_NotSupportedByRuntime2() { var src1 = "[System.Obsolete(\"1\")]class C { }"; var src2 = "[System.Obsolete(\"2\")]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\")]class C { }]@0 -> [[System.Obsolete(\"2\")]class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Delete_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A, B]class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A, B]class C { }]@96 -> [[A]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Delete_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[B, A]class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[B, A]class C { }]@96 -> [[A]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Change_Reloadable() { var attributeSrc = @" public class A1 : System.Attribute { } public class A2 : System.Attribute { } public class A3 : System.Attribute { } "; var src1 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A1, A2]class C { }"; var src2 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A2, A3]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate, A1, A2]class C { }]@267 -> [[CreateNewOnMetadataUpdate, A2, A3]class C { }]@267"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_ReloadableRemove() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_ReloadableAdd() { var src1 = ReloadableAttributeSrc + "class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Attribute_ReloadableBase() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { void F() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_Add() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A]class C { }"; var src2 = attribute + "[A, B]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]class C { }]@96 -> [[A, B]class C { }]@96"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Attribute_Add_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A]class C { }"; var src2 = attribute + "[A, B]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]class C { }]@96 -> [[A, B]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Add_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@48 -> [[A]class C { }]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Reorder1() { var src1 = "[A(1), B(2), C(3)]class C { }"; var src2 = "[C(3), A(1), B(2)]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(1), B(2), C(3)]class C { }]@0 -> [[C(3), A(1), B(2)]class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Attribute_Reorder2() { var src1 = "[A, B, C]class C { }"; var src2 = "[B, C, A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A, B, C]class C { }]@0 -> [[B, C, A]class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Attribute_ReorderAndUpdate_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[System.Obsolete(\"1\"), A, B]class C { }"; var src2 = attribute + "[A, B, System.Obsolete(\"2\")]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), A, B]class C { }]@96 -> [[A, B, System.Obsolete(\"2\")]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Rename(string keyword) { var src1 = keyword + " C { }"; var src2 = keyword + " D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + keyword + " C { }]@0 -> [" + keyword + " D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, keyword + " D", GetResource(keyword))); } [Fact] public void Type_Rename_AddAndDeleteMember() { var src1 = "class C { int x = 1; }"; var src2 = "class D { void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { int x = 1; }]@0 -> [class D { void F() { } }]@0", "Insert [void F() { }]@10", "Insert [()]@16", "Delete [int x = 1;]@10", "Delete [int x = 1]@10", "Delete [x = 1]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] [WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")] public void Type_Rename_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]class C { }]@145 -> [[CreateNewOnMetadataUpdate]class D { }]@145"); // TODO: expected: Replace edit of D edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] [WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")] public void Type_Rename_Reloadable_AddAndDeleteMember() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { int x = 1; }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]class C { int x = 1; }]@145 -> [[CreateNewOnMetadataUpdate]class D { void F() { } }]@145", "Insert [void F() { }]@182", "Insert [()]@188", "Delete [int x = 1;]@182", "Delete [int x = 1]@182", "Delete [x = 1]@186"); // TODO: expected: Replace edit of D edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] public void Interface_NoModifiers_Insert() { var src1 = ""; var src2 = "interface C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Interface_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { } "; var src2 = "namespace N { interface C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Interface_NoModifiers_IntoType_Insert() { var src1 = "interface N { }"; var src2 = "interface N { interface C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_Insert() { var src1 = ""; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { class C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { class C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_Insert() { var src1 = ""; var src2 = "struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { struct C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { struct C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_BaseType_Add_Unchanged() { var src1 = "class C { }"; var src2 = "class C : object { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : object { }]@0"); edits.VerifySemantics(); } [Fact] public void Type_BaseType_Add_Changed() { var src1 = "class C { }"; var src2 = "class C : D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Theory] [InlineData("string", "string?")] [InlineData("string[]", "string[]?")] [InlineData("object", "dynamic")] [InlineData("dynamic?", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Type_BaseType_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Type_BaseType_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_BaseType_Update_CompileTimeTypeUnchanged() { var src1 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<A> {}"; var src2 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_BaseInterface_Add() { var src1 = "class C { }"; var src2 = "class C : IDisposable { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : IDisposable { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_BaseInterface_Delete_Inherited() { var src1 = @" interface B {} interface A : B {} class C : A, B {} "; var src2 = @" interface B {} interface A : B {} class C : A {} "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_BaseInterface_Reorder() { var src1 = "class C : IGoo, IBar { }"; var src2 = "class C : IBar, IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C : IGoo, IBar { }]@0 -> [class C : IBar, IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Type_BaseInterface_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Type_BaseInterface_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_Base_Partial() { var srcA1 = "partial class C : B, I { }"; var srcB1 = "partial class C : J { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C : B, I, J { }"; var srcC = @" class B {} interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) }, new[] { DocumentResults(), DocumentResults(), DocumentResults() }); } [Fact] public void Type_Base_Partial_InsertDeleteAndUpdate() { var srcA1 = "partial class C { }"; var srcB1 = ""; var srcC1 = "partial class C { }"; var srcA2 = ""; var srcB2 = "partial class C : D { }"; var srcC2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "partial class C", FeaturesResources.class_) }), DocumentResults(), }); } [Fact] public void Type_Base_InsertDelete() { var srcA1 = ""; var srcB1 = "class C : B, I { }"; var srcA2 = "class C : B, I { }"; var srcB2 = ""; var srcC = @" class B {} interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) }, new[] { DocumentResults(), DocumentResults(), DocumentResults() }); } [Fact] public void Type_Reloadable_NotSupportedByRuntime() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] public class C { void F() { System.Console.WriteLine(1); } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] public class C { void F() { System.Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, "void F()", "CreateNewOnMetadataUpdateAttribute")); } [Fact] public void Type_Insert_AbstractVirtualOverride() { var src1 = ""; var src2 = @" public abstract class C<T> { public abstract void F(); public virtual void G() {} public override string ToString() => null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Insert_NotSupportedByRuntime() { var src1 = @" public class C { void F() { } }"; var src2 = @" public class C { void F() { } } public class D { void M() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "public class D", FeaturesResources.class_)); } [Fact] public void Type_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + ""; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"))); } [Fact] public void InterfaceInsert() { var src1 = ""; var src2 = @" public interface I { void F(); static void G() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void RefStructInsert() { var src1 = ""; var src2 = "ref struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref struct X { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_ReadOnly_Insert() { var src1 = ""; var src2 = "readonly struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [readonly struct X { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_RefModifier_Add() { var src1 = "struct X { }"; var src2 = "ref struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [struct X { }]@0 -> [ref struct X { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "ref struct X", CSharpFeaturesResources.struct_)); } [Fact] public void Struct_ReadonlyModifier_Add() { var src1 = "struct X { }"; var src2 = "readonly struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [struct X { }]@0 -> [readonly struct X { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly struct X", SyntaxFacts.GetText(SyntaxKind.StructKeyword))); } [Theory] [InlineData("ref")] [InlineData("readonly")] public void Struct_Modifiers_Partial_InsertDelete(string modifier) { var srcA1 = modifier + " partial struct S { }"; var srcB1 = "partial struct S { }"; var srcA2 = "partial struct S { }"; var srcB2 = modifier + " partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults() }); } [Fact] public void Class_ImplementingInterface_Add() { var src1 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } "; var src2 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; }]@219", "Insert [public override string Get() => string.Empty;]@272", "Insert [string IConflict.Get() => String.Empty;]@325", "Insert [()]@298", "Insert [()]@345"); // Here we add a class implementing an interface and a method inside it with explicit interface specifier. // We want to be sure that adding the method will not tirgger a rude edit as it happens if adding a single method with explicit interface specifier. edits.VerifyRudeDiagnostics(); } [WorkItem(37128, "https://github.com/dotnet/roslyn/issues/37128")] [Fact] public void Interface_InsertMembers() { var src1 = @" using System; interface I { } "; var src2 = @" using System; interface I { static int StaticField = 10; static void StaticMethod() { } void VirtualMethod1() { } virtual void VirtualMethod2() { } abstract void AbstractMethod(); sealed void NonVirtualMethod() { } public static int operator +(I a, I b) => 1; static int StaticProperty1 { get => 1; set { } } static int StaticProperty2 => 1; virtual int VirtualProperty1 { get => 1; set { } } virtual int VirtualProperty2 { get => 1; } int VirtualProperty3 { get => 1; set { } } int VirtualProperty4 { get => 1; } abstract int AbstractProperty1 { get; set; } abstract int AbstractProperty2 { get; } sealed int NonVirtualProperty => 1; int this[byte virtualIndexer] => 1; int this[sbyte virtualIndexer] { get => 1; } virtual int this[ushort virtualIndexer] { get => 1; set {} } virtual int this[short virtualIndexer] { get => 1; set {} } abstract int this[uint abstractIndexer] { get; set; } abstract int this[int abstractIndexer] { get; } sealed int this[ulong nonVirtualIndexer] { get => 1; set {} } sealed int this[long nonVirtualIndexer] { get => 1; set {} } static event Action StaticEvent; static event Action StaticEvent2 { add { } remove { } } event Action VirtualEvent { add { } remove { } } abstract event Action AbstractEvent; sealed event Action NonVirtualEvent { add { } remove { } } abstract class C { } interface J { } enum E { } delegate void D(); } "; var edits = GetTopEdits(src1, src2); // TODO: InsertIntoInterface errors are reported due to https://github.com/dotnet/roslyn/issues/37128. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoInterface, "static void StaticMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "void VirtualMethod1()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "virtual void VirtualMethod2()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "abstract void AbstractMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed void NonVirtualMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertOperator, "public static int operator +(I a, I b)", FeaturesResources.operator_), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty2", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty3", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty4", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty1", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.InsertVirtual, "int this[sbyte virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[ushort virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[short virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[uint abstractIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[int abstractIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[ulong nonVirtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[long nonVirtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "static event Action StaticEvent2", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertVirtual, "event Action VirtualEvent", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed event Action NonVirtualEvent", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoInterface, "StaticField = 10", FeaturesResources.field), Diagnostic(RudeEditKind.InsertIntoInterface, "StaticEvent", CSharpFeaturesResources.event_field), Diagnostic(RudeEditKind.InsertVirtual, "AbstractEvent", CSharpFeaturesResources.event_field)); } [Fact] public void Interface_InsertDelete() { var srcA1 = @" interface I { static void M() { } } "; var srcB1 = @" "; var srcA2 = @" "; var srcB2 = @" interface I { static void M() { } } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("M")) }), }); } [Fact] public void Type_Generic_InsertMembers() { var src1 = @" using System; class C<T> { } "; var src2 = @" using System; class C<T> { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1, F2; enum E {} interface I {} class D {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "void M()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertIntoGenericType, "int P1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoGenericType, "int P2", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoGenericType, "int this[int i]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoGenericType, "event Action E", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoGenericType, "EF", CSharpFeaturesResources.event_field), Diagnostic(RudeEditKind.InsertIntoGenericType, "F1", FeaturesResources.field), Diagnostic(RudeEditKind.InsertIntoGenericType, "F2", FeaturesResources.field)); } [Fact] public void Type_Generic_InsertMembers_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { } "; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } event System.Action E { add {} remove {} } event System.Action EF; int F1, F2; enum E {} interface I {} class D {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Generic_DeleteInsert() { var srcA1 = @" class C<T> { void F() {} } struct S<T> { void F() {} } interface I<T> { void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "struct S<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "interface I<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }) }); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")] [WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")] public void Type_TypeParameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C<T> { void F() { } }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C<T, S> { int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Delete() { var src1 = @" class C { void F() {} } struct S { void F() {} } interface I { void F() {} } "; var src2 = ""; GetTopEdits(src1, src2).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(CSharpFeaturesResources.struct_, "S")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.interface_, "I"))); } [Fact] public void Type_Delete_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var src2 = ReloadableAttributeSrc; GetTopEdits(src1, src2).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C"))); } [Fact] public void Type_Partial_DeleteDeclaration() { var srcA1 = "partial class C { void F() {} void M() { } }"; var srcB1 = "partial class C { void G() {} }"; var srcA2 = ""; var srcB2 = "partial class C { void G() {} void M() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.method, "C.F()")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("M")), }) }); } [Fact] public void Type_Partial_InsertFirstDeclaration() { var src1 = ""; var src2 = "partial class C { void F() {} }"; GetTopEdits(src1, src2).VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C"), preserveLocalVariables: false) }); } [Fact] public void Type_Partial_InsertSecondDeclaration() { var srcA1 = "partial class C { void F() {} }"; var srcB1 = ""; var srcA2 = "partial class C { void F() {} }"; var srcB2 = "partial class C { void G() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G"), preserveLocalVariables: false) }), }); } [Fact] public void Type_Partial_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; var srcB1 = ""; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; var srcB2 = "partial class C { void G() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } [Fact] public void Type_DeleteInsert() { var srcA1 = @" class C { void F() {} } struct S { void F() {} } interface I { void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }); } [Fact] public void Type_DeleteInsert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var srcB1 = ""; var srcA2 = ReloadableAttributeSrc; var srcB2 = "[CreateNewOnMetadataUpdate]class C { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")), }) }); } [Fact] public void Type_NonInsertableMembers_DeleteInsert() { var srcA1 = @" abstract class C { public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { void G(); void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; // TODO: The methods without bodies do not need to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }); } [Fact] public void Type_Attribute_NonInsertableMembers_DeleteInsert() { var srcA1 = @" abstract class C { public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { void G(); void F() {} } "; var srcB1 = ""; var srcA2 = ""; var srcB2 = @" abstract class C { [System.Obsolete]public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { [System.Obsolete]void G(); void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_DeleteInsert_DataMembers() { var srcA1 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; public event System.Action E = new System.Action(null); } "; var srcB1 = ""; var srcA2 = ""; var srcB2 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; public event System.Action E = new System.Action(null); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true), }) }); } [Fact] public void Type_DeleteInsert_DataMembers_PartialSplit() { var srcA1 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; } "; var srcB1 = ""; var srcA2 = @" partial class C { public int x = 1; public int y = 2; } "; var srcB2 = @" partial class C { public int P { get; set; } = 3; } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true), }) }); } [Fact] public void Type_DeleteInsert_DataMembers_PartialMerge() { var srcA1 = @" partial class C { public int x = 1; public int y = 2; } "; var srcB1 = @" partial class C { public int P { get; set; } = 3; }"; var srcA2 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; } "; var srcB2 = @" "; // note that accessors are not updated since they do not have bodies EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true), }), DocumentResults() }); } #endregion #region Records [Fact] public void Record_Partial_MovePrimaryConstructor() { var src1 = @" partial record C { } partial record C(int X);"; var src2 = @" partial record C(int X); partial record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_Name_Update() { var src1 = "record C { }"; var src2 = "record D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "record D", CSharpFeaturesResources.record_)); } [Fact] public void RecordStruct_NoModifiers_Insert() { var src1 = ""; var src2 = "record struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_AddField() { var src1 = @" record struct C(int X) { }"; var src2 = @" record struct C(int X) { private int _y = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "_y = 0", FeaturesResources.field, CSharpFeaturesResources.record_struct)); } [Fact] public void RecordStruct_AddProperty() { var src1 = @" record struct C(int X) { }"; var src2 = @" record struct C(int X) { public int Y { get; set; } = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "public int Y { get; set; } = 0;", FeaturesResources.auto_property, CSharpFeaturesResources.record_struct)); } [Fact] public void Record_NoModifiers_Insert() { var src1 = ""; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { record C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { record C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_BaseTypeUpdate1() { var src1 = "record C { }"; var src2 = "record C : D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record C : D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseTypeUpdate2() { var src1 = "record C : D1 { }"; var src2 = "record C : D2 { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : D1 { }]@0 -> [record C : D2 { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate1() { var src1 = "record C { }"; var src2 = "record C : IDisposable { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record C : IDisposable { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate2() { var src1 = "record C : IGoo, IBar { }"; var src2 = "record C : IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : IGoo, IBar { }]@0 -> [record C : IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate3() { var src1 = "record C : IGoo, IBar { }"; var src2 = "record C : IBar, IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : IGoo, IBar { }]@0 -> [record C : IBar, IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void RecordInsert_AbstractVirtualOverride() { var src1 = ""; var src2 = @" public abstract record C<T> { public abstract void F(); public virtual void G() {} public override void H() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_ParameterlessConstructor() { var src1 = "record C { }"; var src2 = @" record C { public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_ImplementSynthesized_ParameterlessConstructor() { var src1 = "record struct C { }"; var src2 = @" record struct C { public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_PrintMembers() { var src1 = "record C { }"; var src2 = @" record C { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers"))); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_ImplementSynthesized_PrintMembers() { var src1 = "record struct C { }"; var src2 = @" record struct C { private readonly bool PrintMembers(System.Text.StringBuilder builder) { return true; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_WrongParameterName() { // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 var src1 = "record C { }"; var src2 = @" record C { protected virtual bool PrintMembers(System.Text.StringBuilder sb) { return false; } public virtual bool Equals(C rhs) { return false; } protected C(C other) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected virtual bool PrintMembers(System.Text.StringBuilder sb)", "PrintMembers(System.Text.StringBuilder builder)"), Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "public virtual bool Equals(C rhs)", "Equals(C other)"), Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected C(C other)", "C(C original)")); } [Fact] public void Record_ImplementSynthesized_ToString() { var src1 = "record C { }"; var src2 = @" record C { public override string ToString() { return ""R""; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_ToString() { var src1 = @" record C { public override string ToString() { return ""R""; } }"; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_Primary() { var src1 = "record C(int X);"; var src2 = "record C(int X, int Y);"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int Y", FeaturesResources.parameter)); } [Fact] public void Record_UnimplementSynthesized_ParameterlessConstructor() { var src1 = @" record C { public C() { } }"; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_UnimplementSynthesized_ParameterlessConstructor() { var src1 = @" record struct C { public C() { } }"; var src2 = "record struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int Y { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithConstructor() { var src1 = @" record C(int X) { public C(string fromAString) { } }"; var src2 = @" record C(int X) { public int Y { get; set; } public C(string fromAString) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithExplicitMembers() { var src1 = @" record C(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return false; } public override int GetHashCode() { return 0; } public virtual bool Equals(C other) { return false; } public C(C original) { } }"; var src2 = @" record C(int X) { public int Y { get; set; } protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return false; } public override int GetHashCode() { return 0; } public virtual bool Equals(C other) { return false; } public C(C original) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithInitializer() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int Y { get; set; } = 1; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField() { var src1 = "record C(int X) { }"; var src2 = "record C(int X) { private int _y; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithExplicitMembers() { var src1 = @" record C(int X) { public C(C other) { } }"; var src2 = @" record C(int X) { private int _y; public C(C other) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithInitializer() { var src1 = "record C(int X) { }"; var src2 = "record C(int X) { private int _y = 1; }"; var syntaxMap = GetSyntaxMap(src1, src2); var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithExistingInitializer() { var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }"; var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithInitializerAndExistingInitializer() { var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }"; var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z = 1; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_DeleteField() { var src1 = "record C(int X) { private int _y; }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.field, "_y"))); } [Fact] public void Record_DeleteProperty_Primary() { var src1 = "record C(int X, int Y) { }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.parameter, "int Y"))); } [Fact] public void Record_DeleteProperty_NotPrimary() { var src1 = "record C(int X) { public int P { get; set; } }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "P"))); } [Fact] public void Record_ImplementSynthesized_Property() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; init; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_WithBody() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get { return 4; } init { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_WithExpressionBody() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get => 4; init => throw null; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_InitToSet() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ImplementRecordParameterWithSet, "public int X", "X")); } [Fact] public void Record_ImplementSynthesized_Property_MakeReadOnly() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ImplementRecordParameterAsReadOnly, "public int X", "X")); } [Fact] public void Record_UnImplementSynthesized_Property() { var src1 = @" record C(int X) { public int X { get; init; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithExpressionBody() { var src1 = @" record C(int X) { public int X { get => 4; init => throw null; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithBody() { var src1 = @" record C(int X) { public int X { get { return 4; } init { } } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_Partial() { var srcA1 = @"partial record C(int X);"; var srcB1 = @"partial record C;"; var srcA2 = @"partial record C(int X);"; var srcB2 = @" partial record C { public int X { get; init; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void Record_UnImplementSynthesized_Property_Partial() { var srcA1 = @"partial record C(int X);"; var srcB1 = @" partial record C { public int X { get; init; } }"; var srcA2 = @"partial record C(int X);"; var srcB2 = @"partial record C;"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void Record_ImplementSynthesized_Property_Partial_WithBody() { var srcA1 = @"partial record C(int X);"; var srcB1 = @"partial record C;"; var srcA2 = @"partial record C(int X);"; var srcB2 = @" partial record C { public int X { get { return 4; } init { throw null; } } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")) }) }); } [Fact] public void Record_UnImplementSynthesized_Property_Partial_WithBody() { var srcA1 = @"partial record C(int X);"; var srcB1 = @" partial record C { public int X { get { return 4; } init { throw null; } } }"; var srcA2 = @"partial record C(int X);"; var srcB2 = @"partial record C;"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")) }) }); } [Fact] public void Record_MoveProperty_Partial() { var srcA1 = @" partial record C(int X) { public int Y { get; init; } }"; var srcB1 = @" partial record C; "; var srcA2 = @" partial record C(int X); "; var srcB2 = @" partial record C { public int Y { get; init; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").SetMethod) }), }); } [Fact] public void Record_UnImplementSynthesized_Property_WithInitializer() { var src1 = @" record C(int X) { public int X { get; init; } = 1; }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithInitializerMatchingCompilerGenerated() { var src1 = @" record C(int X) { public int X { get; init; } = X; }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_Property_Delete_NotPrimary() { var src1 = @" record C(int X) { public int Y { get; init; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "Y"))); } [Fact] public void Record_PropertyInitializer_Update_NotPrimary() { var src1 = "record C { int X { get; } = 0; }"; var src2 = "record C { int X { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Length == 0), preserveLocalVariables: true)); } [Fact] public void Record_PropertyInitializer_Update_Primary() { var src1 = "record C(int X) { int X { get; } = 0; }"; var src2 = "record C(int X) { int X { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); } #endregion #region Enums [Fact] public void Enum_NoModifiers_Insert() { var src1 = ""; var src2 = "enum C { A }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { enum C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { enum C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_Attribute_Insert() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { }"; var src2 = attribute + "[A]enum E { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum E { }]@48 -> [[A]enum E { }]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "enum E", FeaturesResources.enum_)); } [Fact] public void Enum_Member_Attribute_Delete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { [A]X }"; var src2 = attribute + "enum E { X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]X]@57 -> [X]@57"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_Insert() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { X }"; var src2 = attribute + "enum E { [A]X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [X]@57 -> [[A]X]@57"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A]X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_Update() { var attribute = "public class A1Attribute : System.Attribute { }\n\n" + "public class A2Attribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { [A1]X }"; var src2 = attribute + "enum E { [A2]X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A1]X]@107 -> [[A2]X]@107"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A2]X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_InsertDeleteAndUpdate() { var srcA1 = ""; var srcB1 = "enum N { A = 1 }"; var srcA2 = "enum N { [System.Obsolete]A = 1 }"; var srcB2 = ""; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.A")) }), DocumentResults() }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Enum_Rename() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Colors { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Colors { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "enum Colors", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Add() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color : ushort { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : ushort { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Add_Unchanged() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color : int { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : int { Red = 1, Blue = 2, }]@0"); edits.VerifySemantics(); } [Fact] public void Enum_BaseType_Update() { var src1 = "enum Color : ushort { Red = 1, Blue = 2, }"; var src2 = "enum Color : long { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color : long { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Delete_Unchanged() { var src1 = "enum Color : int { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : int { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifySemantics(); } [Fact] public void Enum_BaseType_Delete_Changed() { var src1 = "enum Color : ushort { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void EnumAccessibilityChange() { var src1 = "public enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "enum Color", FeaturesResources.enum_)); } [Fact] public void EnumAccessibilityNoChange() { var src1 = "internal enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void EnumInitializerUpdate() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 3, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Blue = 2]@22 -> [Blue = 3]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 3", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate2() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1 << 0, Blue = 2 << 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = 1]@13 -> [Red = 1 << 0]@13", "Update [Blue = 2]@22 -> [Blue = 2 << 1]@27"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 2 << 1", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate3() { var src1 = "enum Color { Red = int.MinValue }"; var src2 = "enum Color { Red = int.MaxValue }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = int.MinValue]@13 -> [Red = int.MaxValue]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red = int.MaxValue", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 1 }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 2 }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = 1]@185 -> [Red = 2]@185"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("Color"))); } [Fact] public void EnumInitializerAdd() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red = 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red]@13 -> [Red = 1]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red = 1", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerDelete() { var src1 = "enum Color { Red = 1, }"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red = 1]@13 -> [Red]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberAdd() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Red, Blue}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red }]@0 -> [enum Color { Red, Blue}]@0", "Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [Fact] public void EnumMemberAdd2() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red, Blue}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberAdd3() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red, Blue,}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red, Blue,}]@0", "Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [Fact] public void EnumMemberUpdate() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Orange }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red]@13 -> [Orange]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "Orange", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberDelete() { var src1 = "enum Color { Red, Blue}"; var src2 = "enum Color { Red }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red, Blue}]@0 -> [enum Color { Red }]@0", "Delete [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue"))); } [Fact] public void EnumMemberDelete2() { var src1 = "enum Color { Red, Blue}"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue"))); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaAdd() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red }]@0 -> [enum Color { Red, }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaAdd_WithInitializer() { var src1 = "enum Color { Red = 1 }"; var src2 = "enum Color { Red = 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red = 1 }]@0 -> [enum Color { Red = 1, }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaDelete() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaDelete_WithInitializer() { var src1 = "enum Color { Red = 1, }"; var src2 = "enum Color { Red = 1 }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, }]@0 -> [enum Color { Red = 1 }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } #endregion #region Delegates [Fact] public void Delegates_NoModifiers_Insert() { var src1 = ""; var src2 = "delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_NoModifiers_IntoType_Insert() { var src1 = "class C { }"; var src2 = "class C { delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Public_IntoType_Insert() { var src1 = "class C { }"; var src2 = "class C { public delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate void D();]@10", "Insert [()]@32"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Generic_Insert() { var src1 = "class C { }"; var src2 = "class C { private delegate void D<T>(T a); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private delegate void D<T>(T a);]@10", "Insert [<T>]@33", "Insert [(T a)]@36", "Insert [T]@34", "Insert [T a]@37"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Delete() { var src1 = "class C { private delegate void D(); }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [private delegate void D();]@10", "Delete [()]@33"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.delegate_, "D"))); } [Fact] public void Delegates_Rename() { var src1 = "public delegate void D();"; var src2 = "public delegate void Z();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void D();]@0 -> [public delegate void Z();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "public delegate void Z()", FeaturesResources.delegate_)); } [Fact] public void Delegates_Accessibility_Update() { var src1 = "public delegate void D();"; var src2 = "private delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void D();]@0 -> [private delegate void D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "private delegate void D()", FeaturesResources.delegate_)); } [Fact] public void Delegates_ReturnType_Update() { var src1 = "public delegate int D();"; var src2 = "public delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D();]@0 -> [public delegate void D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "public delegate void D()", FeaturesResources.delegate_)); } [Fact] public void Delegates_ReturnType_AddAttribute() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[return: A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@39 -> [[return: A]public delegate int D(int a);]@39"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Parameter_Insert() { var src1 = "public delegate int D();"; var src2 = "public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D();"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D"))); } [Fact] public void Delegates_Parameter_Delete() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.parameter, "int a"))); } [Fact] public void Delegates_Parameter_Rename() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D(int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@22 -> [int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "int b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Parameter_Update() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D(byte a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@22 -> [byte a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "byte a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_AddAttribute_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "public delegate int D([A]int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@70 -> [[A]int a]@70"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_AddAttribute() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "public delegate int D([A]int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@61 -> [[A]int a]@61"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_TypeParameter_Insert() { var src1 = "public delegate int D();"; var src2 = "public delegate int D<T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<T>]@21", "Insert [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "T", FeaturesResources.type_parameter)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")] [WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")] public void Delegates_TypeParameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D<out T>();"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D<in T, out S>(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D"))); } [Fact] public void Delegates_TypeParameter_Delete() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<T>]@21", "Delete [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T"))); } [Fact] public void Delegates_TypeParameter_Rename() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D<S>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@22 -> [S]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "S", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "S")); } [Fact] public void Delegates_TypeParameter_Variance1() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D<in T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@22 -> [in T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_Variance2() { var src1 = "public delegate int D<out T>();"; var src2 = "public delegate int D<T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [out T]@22 -> [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_Variance3() { var src1 = "public delegate int D<out T>();"; var src2 = "public delegate int D<in T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [out T]@22 -> [in T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_AddAttribute() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D<T>();"; var src2 = attribute + "public delegate int D<[A]T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@70 -> [[A]T]@70"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_Attribute_Add_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public delegate int D(int a)", FeaturesResources.delegate_)); } [Fact] public void Delegates_Attribute_Add() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Attribute_Add_WithReturnTypeAttribute() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[return: A][A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[return: A][A]public delegate int D(int a);]@48"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_ReadOnlyRef_Parameter_InsertWhole() { var src1 = ""; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate int D(in int b);]@0", "Insert [(in int b)]@21", "Insert [in int b]@22"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "public delegate int D();"; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Delegates_ReadOnlyRef_Parameter_Update() { var src1 = "public delegate int D(int b);"; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@22 -> [in int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } [Fact] public void Delegates_ReadOnlyRef_ReturnType_Insert() { var src1 = ""; var src2 = "public delegate ref readonly int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate ref readonly int D();]@0", "Insert [()]@34"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_ReadOnlyRef_ReturnType_Update() { var src1 = "public delegate int D();"; var src2 = "public delegate ref readonly int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D();]@0 -> [public delegate ref readonly int D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "public delegate ref readonly int D()", FeaturesResources.delegate_)); } #endregion #region Nested Types [Fact] public void NestedClass_ClassMove1() { var src1 = @"class C { class D { } }"; var src2 = @"class C { } class D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [class D { }]@10 -> @12"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_)); } [Fact] public void NestedClass_ClassMove2() { var src1 = @"class C { class D { } class E { } class F { } }"; var src2 = @"class C { class D { } class F { } } class E { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [class E { }]@23 -> @37"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class E", FeaturesResources.class_)); } [Fact] public void NestedClass_ClassInsertMove1() { var src1 = @"class C { class D { } }"; var src2 = @"class C { class E { class D { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [class E { class D { } }]@10", "Move [class D { }]@10 -> @20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_)); } [Fact] public void NestedClass_Insert1() { var src1 = @"class C { }"; var src2 = @"class C { class D { class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [class D { class E { } }]@10", "Insert [class E { }]@20"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert2() { var src1 = @"class C { }"; var src2 = @"class C { protected class D { public class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [protected class D { public class E { } }]@10", "Insert [public class E { }]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert3() { var src1 = @"class C { }"; var src2 = @"class C { private class D { public class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public class E { } }]@10", "Insert [public class E { }]@28"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert4() { var src1 = @"class C { }"; var src2 = @"class C { private class D { public D(int a, int b) { } public int P { get; set; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public D(int a, int b) { } public int P { get; set; } }]@10", "Insert [public D(int a, int b) { }]@28", "Insert [public int P { get; set; }]@55", "Insert [(int a, int b)]@36", "Insert [{ get; set; }]@68", "Insert [int a]@37", "Insert [int b]@44", "Insert [get;]@70", "Insert [set;]@75"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable1() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable2() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable3() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable4() { var src1 = ReloadableAttributeSrc + "class C { }"; var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"))); } [Fact] public void NestedClass_Insert_Member_Reloadable() { var src1 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { } }"; var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { int x; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C.D"))); } [Fact] public void NestedClass_InsertMemberWithInitializer1() { var src1 = @" class C { }"; var src2 = @" class C { private class D { public int P = 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"), preserveLocalVariables: false) }); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void NestedClass_Insert_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { abstract class D { public extern D(); public static extern int P { [DllImport(""msvcrt.dll"")]get; [DllImport(""msvcrt.dll"")]set; } [DllImport(""msvcrt.dll"")] public static extern int puts(string c); [DllImport(""msvcrt.dll"")] public static extern int operator +(D d, D g); [DllImport(""msvcrt.dll"")] public static extern explicit operator int (D d); } } "; var edits = GetTopEdits(src1, src2); // Adding P/Invoke is not supported by the CLR. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "public extern D()", FeaturesResources.constructor), Diagnostic(RudeEditKind.InsertExtern, "public static extern int P", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "public static extern int puts(string c)", FeaturesResources.method), Diagnostic(RudeEditKind.InsertExtern, "public static extern int operator +(D d, D g)", FeaturesResources.operator_), Diagnostic(RudeEditKind.InsertExtern, "public static extern explicit operator int (D d)", CSharpFeaturesResources.conversion_operator)); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void NestedClass_Insert_VirtualAbstract() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { abstract class D { public abstract int P { get; } public abstract int this[int i] { get; } public abstract int puts(string c); public virtual event Action E { add { } remove { } } public virtual int Q { get { return 1; } } public virtual int this[string i] { get { return 1; } } public virtual int M(string c) { return 1; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_TypeReorder1() { var src1 = @"class C { struct E { } class F { } delegate void D(); interface I {} }"; var src2 = @"class C { class F { } interface I {} delegate void D(); struct E { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [struct E { }]@10 -> @56", "Reorder [interface I {}]@54 -> @22"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_MethodDeleteInsert() { var src1 = @"public class C { public void goo() {} }"; var src2 = @"public class C { private class D { public void goo() {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public void goo() {} }]@17", "Insert [public void goo() {}]@35", "Insert [()]@50", "Delete [public void goo() {}]@17", "Delete [()]@32"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "public class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [Fact] public void NestedClass_ClassDeleteInsert() { var src1 = @"public class C { public class X {} }"; var src2 = @"public class C { public class D { public class X {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public class D { public class X {} }]@17", "Move [public class X {}]@17 -> @34"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "public class X", FeaturesResources.class_)); } /// <summary> /// A new generic type can be added whether it's nested and inherits generic parameters from the containing type, or top-level. /// </summary> [Fact] public void NestedClassGeneric_Insert() { var src1 = @" using System; class C<T> { } "; var src2 = @" using System; class C<T> { class D {} struct S {} enum N {} interface I {} delegate void D(); } class D<T> { } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedEnum_InsertMember() { var src1 = "struct S { enum N { A = 1 } }"; var src2 = "struct S { enum N { A = 1, B = 2 } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum N { A = 1 }]@11 -> [enum N { A = 1, B = 2 }]@11", "Insert [B = 2]@27"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value)); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDelete() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 1 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateMember() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 2 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "A = 2", FeaturesResources.enum_value), }), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateBase() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N : uint { A = 1 } }"; var srcA2 = "partial struct S { enum N : int { A = 1 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum N", FeaturesResources.enum_), }), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndInsertMember() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 1, B = 2 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDelete() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(); }"; var srcA2 = "partial struct S { delegate void D(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( // delegate does not have any user-defined method body and this does not need a PDB update semanticEdits: NoSemanticEdits), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeParameters() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(); }"; var srcA2 = "partial struct S { delegate void D(int x); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingParameterTypes, "delegate void D(int x)", FeaturesResources.delegate_) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeReturnType() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate ref int D(); }"; var srcA2 = "partial struct S { delegate ref readonly int D(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.TypeUpdate, "delegate ref readonly int D()", FeaturesResources.delegate_) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeOptionalParameterValue() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(int x = 1); }"; var srcA2 = "partial struct S { delegate void D(int x = 2); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults() }); } [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndChange() { var srcA1 = "partial struct S { partial class C { void F1() {} } }"; var srcB1 = "partial struct S { partial class C { void F2(byte x) {} } }"; var srcC1 = "partial struct S { }"; var srcA2 = "partial struct S { partial class C { void F1() {} } }"; var srcB2 = "partial struct S { }"; var srcC2 = "partial struct S { partial class C { void F2(int x) {} } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F2(byte x)")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("S").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }) }); } [Fact] public void Type_Partial_AddMultiple() { var srcA1 = ""; var srcB1 = ""; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteAndChange_Attribute() { var srcA1 = "partial class C { }"; var srcB1 = ""; var srcC1 = "partial class C { }"; var srcA2 = ""; var srcB2 = "[A]partial class C { }"; var srcC2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), DocumentResults(), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteAndChange_TypeParameterAttribute_NotSupportedByRuntime() { var srcA1 = "partial class C<T> { }"; var srcB1 = ""; var srcC1 = "partial class C<T> { }"; var srcA2 = ""; var srcB2 = "partial class C<[A]T> { }"; var srcC2 = "partial class C<T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<[A]T>"), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T") }), DocumentResults(), }); } [Fact] public void Type_Partial_InsertDeleteAndChange_Constraint() { var srcA1 = "partial class C<T> { }"; var srcB1 = ""; var srcC1 = "partial class C<T> { }"; var srcA2 = ""; var srcB2 = "partial class C<T> where T : new() { }"; var srcC2 = "partial class C<T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<T>"), Diagnostic(RudeEditKind.ChangingConstraints, "where T : new()", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : new()") }), DocumentResults(), }); } [Fact] public void Type_Partial_InsertDeleteRefactor() { var srcA1 = "partial class C : I { void F() { } }"; var srcB1 = "[A][B]partial class C : J { void G() { } }"; var srcC1 = ""; var srcD1 = ""; var srcA2 = ""; var srcB2 = ""; var srcC2 = "[A]partial class C : I, J { void F() { } }"; var srcD2 = "[B]partial class C { void G() { } }"; var srcE = "interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE, srcE) }, new[] { DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G")) }), DocumentResults(), }); } [Fact] public void Type_Partial_Attribute_AddMultiple() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = "partial class C { }" + attributes; var srcB1 = "partial class C { }"; var srcA2 = "[A]partial class C { }" + attributes; var srcB2 = "[B]partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteRefactor_AttributeListSplitting() { var srcA1 = "partial class C { void F() { } }"; var srcB1 = "[A,B]partial class C { void G() { } }"; var srcC1 = ""; var srcD1 = ""; var srcA2 = ""; var srcB2 = ""; var srcC2 = "[A]partial class C { void F() { } }"; var srcD2 = "[B]partial class C { void G() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G")) }), }); } [Fact] public void Type_Partial_InsertDeleteChangeMember() { var srcA1 = "partial class C { void F(int y = 1) { } }"; var srcB1 = "partial class C { void G(int x = 1) { } }"; var srcC1 = ""; var srcA2 = ""; var srcB2 = "partial class C { void G(int x = 2) { } }"; var srcC2 = "partial class C { void F(int y = 2) { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int y = 2", FeaturesResources.parameter) }), }); } [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndInsertVirtual() { var srcA1 = "partial interface I { partial class C { virtual void F1() {} } }"; var srcB1 = "partial interface I { partial class C { virtual void F2() {} } }"; var srcC1 = "partial interface I { partial class C { } }"; var srcD1 = "partial interface I { partial class C { } }"; var srcE1 = "partial interface I { }"; var srcF1 = "partial interface I { }"; var srcA2 = "partial interface I { partial class C { } }"; var srcB2 = ""; var srcC2 = "partial interface I { partial class C { virtual void F1() {} } }"; // move existing virtual into existing partial decl var srcD2 = "partial interface I { partial class C { virtual void N1() {} } }"; // insert new virtual into existing partial decl var srcE2 = "partial interface I { partial class C { virtual void F2() {} } }"; // move existing virtual into a new partial decl var srcF2 = "partial interface I { partial class C { virtual void N2() {} } }"; // insert new virtual into new partial decl EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE1, srcE2), GetTopEdits(srcF1, srcF2) }, new[] { // A DocumentResults(), // B DocumentResults(), // C DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F1")) }), // D DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N1()", FeaturesResources.method) }), // E DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }), // F DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N2()", FeaturesResources.method) }), }); } #endregion #region Namespaces [Fact] public void Namespace_Insert() { var src1 = @""; var src2 = @"namespace C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_InsertNested() { var src1 = @"namespace C { }"; var src2 = @"namespace C { namespace D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace D { }]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace D", FeaturesResources.namespace_)); } [Fact] public void Namespace_DeleteNested() { var src1 = @"namespace C { namespace D { } }"; var src2 = @"namespace C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [namespace D { }]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_Move() { var src1 = @"namespace C { namespace D { } }"; var src2 = @"namespace C { } namespace D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [namespace D { }]@14 -> @16"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "namespace D", FeaturesResources.namespace_)); } [Fact] public void Namespace_Reorder1() { var src1 = @"namespace C { namespace D { } class T { } namespace E { } }"; var src2 = @"namespace C { namespace E { } class T { } namespace D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [class T { }]@30 -> @30", "Reorder [namespace E { }]@42 -> @14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Namespace_Reorder2() { var src1 = @"namespace C { namespace D1 { } namespace D2 { } namespace D3 { } class T { } namespace E { } }"; var src2 = @"namespace C { namespace E { } class T { } namespace D1 { } namespace D2 { } namespace D3 { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [class T { }]@65 -> @65", "Reorder [namespace E { }]@77 -> @14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Namespace_FileScoped_Insert() { var src1 = @""; var src2 = @"namespace C;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace C;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_FileScoped_Delete() { var src1 = @"namespace C;"; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [namespace C;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, FeaturesResources.namespace_)); } #endregion #region Members [Fact] public void PartialMember_DeleteInsert_SingleDocument() { var src1 = @" using System; partial class C { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } int this[byte i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1; int F2; } partial class C { } "; var src2 = @" using System; partial class C { } partial class C { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } int this[byte i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1, F2; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void M() {}]@68", "Insert [int P1 { get; set; }]@85", "Insert [int P2 { get => 1; set {} }]@111", "Insert [int this[int i] { get => 1; set {} }]@144", "Insert [int this[byte i] { get => 1; set {} }]@186", "Insert [event Action E { add {} remove {} }]@229", "Insert [event Action EF;]@270", "Insert [int F1, F2;]@292", "Insert [()]@74", "Insert [{ get; set; }]@92", "Insert [{ get => 1; set {} }]@118", "Insert [[int i]]@152", "Insert [{ get => 1; set {} }]@160", "Insert [[byte i]]@194", "Insert [{ get => 1; set {} }]@203", "Insert [{ add {} remove {} }]@244", "Insert [Action EF]@276", "Insert [int F1, F2]@292", "Insert [get;]@94", "Insert [set;]@99", "Insert [get => 1;]@120", "Insert [set {}]@130", "Insert [int i]@153", "Insert [get => 1;]@162", "Insert [set {}]@172", "Insert [byte i]@195", "Insert [get => 1;]@205", "Insert [set {}]@215", "Insert [add {}]@246", "Insert [remove {}]@253", "Insert [EF]@283", "Insert [F1]@296", "Insert [F2]@300", "Delete [void M() {}]@43", "Delete [()]@49", "Delete [int P1 { get; set; }]@60", "Delete [{ get; set; }]@67", "Delete [get;]@69", "Delete [set;]@74", "Delete [int P2 { get => 1; set {} }]@86", "Delete [{ get => 1; set {} }]@93", "Delete [get => 1;]@95", "Delete [set {}]@105", "Delete [int this[int i] { get => 1; set {} }]@119", "Delete [[int i]]@127", "Delete [int i]@128", "Delete [{ get => 1; set {} }]@135", "Delete [get => 1;]@137", "Delete [set {}]@147", "Delete [int this[byte i] { get => 1; set {} }]@161", "Delete [[byte i]]@169", "Delete [byte i]@170", "Delete [{ get => 1; set {} }]@178", "Delete [get => 1;]@180", "Delete [set {}]@190", "Delete [event Action E { add {} remove {} }]@204", "Delete [{ add {} remove {} }]@219", "Delete [add {}]@221", "Delete [remove {}]@228", "Delete [event Action EF;]@245", "Delete [Action EF]@251", "Delete [EF]@258", "Delete [int F1;]@267", "Delete [int F1]@267", "Delete [F1]@271", "Delete [int F2;]@280", "Delete [int F2]@280", "Delete [F2]@284"); EditAndContinueValidation.VerifySemantics( new[] { edits }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod, preserveLocalVariables: false), }) }); } [Fact] public void PartialMember_InsertDelete_MultipleDocuments() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { void F() {} }"; var srcA2 = "partial class C { void F() {} }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F"), preserveLocalVariables: false) }), DocumentResults() }); } [Fact] public void PartialMember_DeleteInsert_MultipleDocuments() { var srcA1 = "partial class C { void F() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"), preserveLocalVariables: false) }) }); } [Fact] public void PartialMember_DeleteInsert_GenericMethod() { var srcA1 = "partial class C { void F<T>() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F<T>() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<T>()"), Diagnostic(RudeEditKind.GenericMethodUpdate, "T") }) }); } [Fact] public void PartialMember_DeleteInsert_GenericType() { var srcA1 = "partial class C<T> { void F() {} }"; var srcB1 = "partial class C<T> { }"; var srcA2 = "partial class C<T> { }"; var srcB2 = "partial class C<T> { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()") }) }); } [Fact] public void PartialMember_DeleteInsert_Destructor() { var srcA1 = "partial class C { ~C() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { ~C() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("Finalize"), preserveLocalVariables: false), }) }); } [Fact] public void PartialNestedType_InsertDeleteAndChange() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { class D { void M() {} } interface I { } }"; var srcA2 = "partial class C { class D : I { void M() {} } interface I { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class D", FeaturesResources.class_), }), DocumentResults() }); } [Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")] public void PartialMember_RenameInsertDelete() { // The syntactic analysis for A and B produce rename edits since it doesn't see that the member was in fact moved. // TODO: Currently, we don't even pass rename edits to semantic analysis where we could handle them as updates. var srcA1 = "partial class C { void F1() {} }"; var srcB1 = "partial class C { void F2() {} }"; var srcA2 = "partial class C { void F2() {} }"; var srcB2 = "partial class C { void F1() {} }"; // current outcome: GetTopEdits(srcA1, srcA2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F2()", FeaturesResources.method)); GetTopEdits(srcB1, srcB2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F1()", FeaturesResources.method)); // correct outcome: //EditAndContinueValidation.VerifySemantics( // new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, // new[] // { // DocumentResults(semanticEdits: new[] // { // SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F2")), // }), // DocumentResults( // semanticEdits: new[] // { // SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F1")), // }) // }); } [Fact] public void PartialMember_DeleteInsert_UpdateMethodBodyError() { var srcA1 = @" using System.Collections.Generic; partial class C { IEnumerable<int> F() { yield return 1; } } "; var srcB1 = @" using System.Collections.Generic; partial class C { } "; var srcA2 = @" using System.Collections.Generic; partial class C { } "; var srcB2 = @" using System.Collections.Generic; partial class C { IEnumerable<int> F() { yield return 1; yield return 2; } } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "yield return 2;", CSharpFeaturesResources.yield_return_statement) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdatePropertyAccessors() { var srcA1 = "partial class C { int P { get => 1; set { Console.WriteLine(1); } } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int P { get => 2; set { Console.WriteLine(2); } } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdateAutoProperty() { var srcA1 = "partial class C { int P => 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int P => 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }) }); } [Fact] public void PartialMember_DeleteInsert_AddFieldInitializer() { var srcA1 = "partial class C { int f; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int f = 1; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_RemoveFieldInitializer() { var srcA1 = "partial class C { int f = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int f; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_ConstructorWithInitializers() { var srcA1 = "partial class C { int f = 1; C(int x) { f = x; } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { int f = 1; }"; var srcB2 = "partial class C { C(int x) { f = x + 1; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_MethodAddParameter() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F() {} }"; var srcA2 = "partial struct S { void F(int x) {} }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F")) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdateMethodParameterType() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F(int x); }"; var srcA2 = "partial struct S { void F(byte x); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F")) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F(int x)")) }) }); } [Fact] public void PartialMember_DeleteInsert_MethodAddTypeParameter() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F(); }"; var srcA2 = "partial struct S { void F<T>(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertGenericMethod, "void F<T>()", FeaturesResources.method) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } #endregion #region Methods [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Method_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F() => 0; }"; var src2 = "class C { " + newModifiers + "int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F() => 0;]@10 -> [" + newModifiers + "int F() => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F()", FeaturesResources.method)); } [Fact] public void Method_NewModifier_Add() { var src1 = "class C { int F() => 0; }"; var src2 = "class C { new int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int F() => 0;]@10 -> [new int F() => 0;]@10"); // Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"))); } [Fact] public void Method_NewModifier_Remove() { var src1 = "class C { new int F() => 0; }"; var src2 = "class C { int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [new int F() => 0;]@10 -> [int F() => 0;]@10"); // Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"))); } [Fact] public void Method_ReadOnlyModifier_Add_InMutableStruct() { var src1 = @" struct S { public int M() => 1; }"; var src2 = @" struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly int M()", FeaturesResources.method)); } [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct1() { var src1 = @" readonly struct S { public int M() => 1; }"; var src2 = @" readonly struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); // Currently, an edit is produced eventhough the body nor IsReadOnly attribute have changed. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IMethodSymbol>("M"))); } [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct2() { var src1 = @" readonly struct S { public int M() => 1; }"; var src2 = @" struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "struct S", "struct")); } [Fact] public void Method_AsyncModifier_Remove() { var src1 = @" class Test { public async Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public Task<int> WaitAsync() { return Task.FromResult(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "public Task<int> WaitAsync()", FeaturesResources.method)); } [Fact] public void Method_AsyncModifier_Add() { var src1 = @" class Test { public Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: false); } [Fact] public void Method_AsyncModifier_Add_NotSupported() { var src1 = @" class Test { public Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.MakeMethodAsync, "public async Task<int> WaitAsync()")); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Method_ReturnType_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { " + oldType + " M() => default; }"; var src2 = "class C { " + newType + " M() => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Method_ReturnType_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { " + oldType + " M() => default; }"; var src2 = "class C { " + newType + " M() => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " M()", FeaturesResources.method)); } [Fact] public void Method_Update() { var src1 = @" class C { static void Main(string[] args) { int a = 1; int b = 2; System.Console.WriteLine(a + b); } } "; var src2 = @" class C { static void Main(string[] args) { int b = 2; int a = 1; System.Console.WriteLine(a + b); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static void Main(string[] args) { int a = 1; int b = 2; System.Console.WriteLine(a + b); }]@18 -> [static void Main(string[] args) { int b = 2; int a = 1; System.Console.WriteLine(a + b); }]@18"); edits.VerifyRudeDiagnostics(); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) }); } [Fact] public void MethodWithExpressionBody_Update() { var src1 = @" class C { static int Main(string[] args) => F(1); static int F(int a) => 1; } "; var src2 = @" class C { static int Main(string[] args) => F(2); static int F(int a) => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static int Main(string[] args) => F(1);]@18 -> [static int Main(string[] args) => F(2);]@18"); edits.VerifyRudeDiagnostics(); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void MethodWithExpressionBody_Update_LiftedParameter() { var src1 = @" using System; class C { int M(int a) => new Func<int>(() => a + 1)(); } "; var src2 = @" using System; class C { int M(int a) => new Func<int>(() => 2)(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int M(int a) => new Func<int>(() => a + 1)();]@35 -> [int M(int a) => new Func<int>(() => 2)();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact] public void MethodWithExpressionBody_ToBlockBody() { var src1 = "class C { static int F(int a) => 1; }"; var src2 = "class C { static int F(int a) { return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => 1;]@10 -> [static int F(int a) { return 2; }]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false) }); } [Fact] public void MethodWithBlockBody_ToExpressionBody() { var src1 = "class C { static int F(int a) { return 2; } }"; var src2 = "class C { static int F(int a) => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) { return 2; }]@10 -> [static int F(int a) => 1;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false) }); } [Fact] public void MethodWithLambda_Update() { var src1 = @" using System; class C { static void F() { Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; } } "; var src2 = @" using System; class C { static void F() { Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); } }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), syntaxMap[0]) }); } [Fact] public void MethodUpdate_LocalVariableDeclaration() { var src1 = @" class C { static void Main(string[] args) { int x = 1; Console.WriteLine(x); } } "; var src2 = @" class C { static void Main(string[] args) { int x = 2; Console.WriteLine(x); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static void Main(string[] args) { int x = 1; Console.WriteLine(x); }]@18 -> [static void Main(string[] args) { int x = 2; Console.WriteLine(x); }]@18"); } [Fact] public void Method_Delete() { var src1 = @" class C { void goo() { } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [void goo() { }]@18", "Delete [()]@26"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [Fact] public void MethodWithExpressionBody_Delete() { var src1 = @" class C { int goo() => 1; } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int goo() => 1;]@18", "Delete [()]@25"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodDelete_WithParameterAndAttribute() { var src1 = @" class C { [Obsolete] void goo(int a) { } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Delete [[Obsolete] void goo(int a) { }]@18", "Delete [(int a)]@42", "Delete [int a]@43"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo(int a)"))); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodDelete_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int puts(string c); } "; var src2 = @" using System; using System.Runtime.InteropServices; class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Delete [[DllImport(""msvcrt.dll"")] public static extern int puts(string c);]@74", "Delete [(string c)]@134", "Delete [string c]@135"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "puts(string c)"))); } [Fact] public void MethodInsert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { void goo() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "void goo()", FeaturesResources.method)); } [Fact] public void PrivateMethodInsert() { var src1 = @" class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" class C { void goo() { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void goo() { }]@18", "Insert [()]@26"); edits.VerifyRudeDiagnostics(); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] [Fact] public void PrivateMethodInsert_WithParameters() { var src1 = @" using System; class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" using System; class C { void goo(int a) { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void goo(int a) { }]@35", "Insert [(int a)]@43", "Insert [int a]@44"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.goo")) }); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] [Fact] public void PrivateMethodInsert_WithAttribute() { var src1 = @" class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" class C { [System.Obsolete] void goo(int a) { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [[System.Obsolete] void goo(int a) { }]@18", "Insert [(int a)]@49", "Insert [int a]@50"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodInsert_Virtual() { var src1 = @" class C { }"; var src2 = @" class C { public virtual void F() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public virtual void F()", FeaturesResources.method)); } [Fact] public void MethodInsert_Abstract() { var src1 = @" abstract class C { }"; var src2 = @" abstract class C { public abstract void F(); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public abstract void F()", FeaturesResources.method)); } [Fact] public void MethodInsert_Override() { var src1 = @" class C { }"; var src2 = @" class C { public override void F() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public override void F()", FeaturesResources.method)); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void ExternMethodInsert() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [[DllImport(""msvcrt.dll"")] private static extern int puts(string c);]@74", "Insert [(string c)]@135", "Insert [string c]@136"); // CLR doesn't support methods without a body edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "private static extern int puts(string c)", FeaturesResources.method)); } [Fact] [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethodDeleteInsert() { var srcA1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); }"; var srcA2 = @" using System; using System.Runtime.InteropServices; "; var srcB1 = @" using System; using System.Runtime.InteropServices; "; var srcB2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); } "; // TODO: The method does not need to be updated since there are no sequence points generated for it. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")), }) }); } [Fact] [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethod_Attribute_DeleteInsert() { var srcA1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); }"; var srcA2 = @" using System; using System.Runtime.InteropServices; "; var srcB1 = @" using System; using System.Runtime.InteropServices; "; var srcB2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] [Obsolete] private static extern int puts(string c); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")), }) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodReorder1() { var src1 = "class C { void f(int a, int b) { a = b; } void g() { } }"; var src2 = "class C { void g() { } void f(int a, int b) { a = b; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Reorder [void g() { }]@42 -> @10"); } [Fact] public void MethodInsertDelete1() { var src1 = "class C { class D { } void f(int a, int b) { a = b; } }"; var src2 = "class C { class D { void f(int a, int b) { a = b; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void f(int a, int b) { a = b; }]@20", "Insert [(int a, int b)]@26", "Insert [int a]@27", "Insert [int b]@34", "Delete [void f(int a, int b) { a = b; }]@22", "Delete [(int a, int b)]@28", "Delete [int a]@29", "Delete [int b]@36"); } [Fact] public void MethodUpdate_AddParameter() { var src1 = @" class C { static void Main() { } }"; var src2 = @" class C { static void Main(string[] args) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [string[] args]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "string[] args", FeaturesResources.parameter)); } [Fact] public void MethodUpdate_UpdateParameter() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] b) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [string[] args]@35 -> [string[] b]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "string[] b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_UpdateParameterAndBody() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] b) { System.Console.Write(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "string[] b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Method_Name_Update() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void EntryPoint(string[] args) { } }"; var edits = GetTopEdits(src1, src2); var expectedEdit = @"Update [static void Main(string[] args) { }]@18 -> [static void EntryPoint(string[] args) { }]@18"; edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "static void EntryPoint(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AsyncMethod0() { var src1 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(500); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [Fact] public void MethodUpdate_AsyncMethod1() { var src1 = @" class Test { static void Main(string[] args) { Test f = new Test(); string result = f.WaitAsync().Result; } public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Done""; } }"; var src2 = @" class Test { static void Main(string[] args) { Test f = new Test(); string result = f.WaitAsync().Result; } public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Not Done""; } }"; var edits = GetTopEdits(src1, src2); var expectedEdit = @"Update [public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Done""; }]@151 -> [public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Not Done""; }]@151"; edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AddReturnTypeAttribute() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [return: Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[return: Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute_SupportedByRuntime() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Test.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_Attribute_ArrayParameter() { var src1 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { } }"; var src2 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 4, 5, 6})] void M() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_Attribute_ArrayParameter_NoChange() { var src1 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { var x = 1; } }"; var src2 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { var x = 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AddAttribute2() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute3() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] [Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute4() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_UpdateAttribute() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete("""")] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodUpdate_DeleteAttribute() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_DeleteAttribute2() { var src1 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_DeleteAttribute3() { var src1 = @" using System; class Test { [Obsolete] [Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_ExplicitlyImplemented1() { var src1 = @" class C : I, J { void I.Goo() { Console.WriteLine(2); } void J.Goo() { Console.WriteLine(1); } }"; var src2 = @" class C : I, J { void I.Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void I.Goo() { Console.WriteLine(2); }]@25 -> [void I.Goo() { Console.WriteLine(1); }]@25", "Update [void J.Goo() { Console.WriteLine(1); }]@69 -> [void J.Goo() { Console.WriteLine(2); }]@69"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_ExplicitlyImplemented2() { var src1 = @" class C : I, J { void I.Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var src2 = @" class C : I, J { void Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void I.Goo() { Console.WriteLine(1); }]@25 -> [void Goo() { Console.WriteLine(1); }]@25"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "void Goo()", FeaturesResources.method)); } [WorkItem(754255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754255")] [Fact] public void MethodUpdate_UpdateStackAlloc() { var src1 = @" class C { static void Main(string[] args) { int i = 10; unsafe { int* px2 = &i; } } }"; var src2 = @" class C { static void Main(string[] args) { int i = 10; unsafe { char* buffer = stackalloc char[16]; int* px2 = &i; } } }"; var expectedEdit = @"Update [static void Main(string[] args) { int i = 10; unsafe { int* px2 = &i; } }]@18 -> [static void Main(string[] args) { int i = 10; unsafe { char* buffer = stackalloc char[16]; int* px2 = &i; } }]@18"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method)); } [Theory] [InlineData("stackalloc int[3]")] [InlineData("stackalloc int[3] { 1, 2, 3 }")] [InlineData("stackalloc int[] { 1, 2, 3 }")] [InlineData("stackalloc[] { 1, 2, 3 }")] public void MethodUpdate_UpdateStackAlloc2(string stackallocDecl) { var src1 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 1; } }"; var src2 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method)); } [Fact] public void MethodUpdate_UpdateStackAllocInLambda1() { var src1 = "unsafe class C { void M() { F(1, () => { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, () => { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInLambda2() { var src1 = "unsafe class C { void M() { F(1, x => { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, x => { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInAnonymousMethod() { var src1 = "unsafe class C { void M() { F(1, delegate(int x) { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, delegate(int x) { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInLocalFunction() { var src1 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(1); } }"; var src2 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLambda1() { var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }"; var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLambda2() { var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }"; var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInAnonymousMethod() { var src1 = "class C { void M() { F(1, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }"; var src2 = "class C { void M() { F(2, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLocalFunction() { var src1 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(1); } }"; var src2 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInQuery() { var src1 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 1; } }"; var src2 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateAnonymousMethod() { var src1 = "class C { void M() { F(1, delegate(int a) { return a; }); } }"; var src2 = "class C { void M() { F(2, delegate(int a) { return a; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_UpdateAnonymousMethod() { var src1 = "class C { void M() => F(1, delegate(int a) { return a; }); }"; var src2 = "class C { void M() => F(2, delegate(int a) { return a; }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_Query() { var src1 = "class C { void M() { F(1, from goo in bar select baz); } }"; var src2 = "class C { void M() { F(2, from goo in bar select baz); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_Query() { var src1 = "class C { void M() => F(1, from goo in bar select baz); }"; var src2 = "class C { void M() => F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AnonymousType() { var src1 = "class C { void M() { F(1, new { A = 1, B = 2 }); } }"; var src2 = "class C { void M() { F(2, new { A = 1, B = 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_AnonymousType() { var src1 = "class C { void M() => F(new { A = 1, B = 2 }); }"; var src2 = "class C { void M() => F(new { A = 10, B = 20 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_Iterator_YieldReturn() { var src1 = "class C { IEnumerable<int> M() { yield return 1; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [Fact] public void MethodUpdate_AddYieldReturn() { var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: false); } [Fact] public void MethodUpdate_AddYieldReturn_NotSupported() { var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.MakeMethodIterator, "IEnumerable<int> M()")); } [Fact] public void MethodUpdate_Iterator_YieldBreak() { var src1 = "class C { IEnumerable<int> M() { F(); yield break; } }"; var src2 = "class C { IEnumerable<int> M() { G(); yield break; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [WorkItem(1087305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087305")] [Fact] public void MethodUpdate_LabeledStatement() { var src1 = @" class C { static void Main(string[] args) { goto Label1; Label1: { Console.WriteLine(1); } } }"; var src2 = @" class C { static void Main(string[] args) { goto Label1; Label1: { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_LocalFunctionsParameterRefnessInBody() { var src1 = @"class C { public void M(int a) { void f(ref int b) => b = 1; } }"; var src2 = @"class C { public void M(int a) { void f(out int b) => b = 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public void M(int a) { void f(ref int b) => b = 1; }]@10 -> [public void M(int a) { void f(out int b) => b = 1; }]@10"); } [Fact] public void MethodUpdate_LambdaParameterRefnessInBody() { var src1 = @"class C { public void M(int a) { f((ref int b) => b = 1); } }"; var src2 = @"class C { public void M(int a) { f((out int b) => b = 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public void M(int a) { f((ref int b) => b = 1); }]@10 -> [public void M(int a) { f((out int b) => b = 1); }]@10"); } [Fact] public void Method_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int M(in int b) => throw null;]@13", "Insert [(in int b)]@18", "Insert [in int b]@19"); edits.VerifyRudeDiagnostics(); } [Fact] public void Method_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "class Test { int M() => throw null; }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@19"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Method_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { int M(int b) => throw null; }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@19 -> [in int b]@19"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } [Fact] public void Method_ReadOnlyRef_ReturnType_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int M() => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int M() => throw null;]@13", "Insert [()]@31"); edits.VerifyRudeDiagnostics(); } [Fact] public void Method_ReadOnlyRef_ReturnType_Update() { var src1 = "class Test { int M() => throw null; }"; var src2 = "class Test { ref readonly int M() => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int M() => throw null;]@13 -> [ref readonly int M() => throw null;]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int M()", FeaturesResources.method)); } [Fact] public void Method_ImplementingInterface_Add() { var src1 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; } "; var src2 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [string IConflict.Get() => String.Empty;]@325", "Insert [()]@345"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, "string IConflict.Get()", FeaturesResources.method)); } [Fact] public void Method_Partial_DeleteInsert_DefinitionPart() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { partial void F() { } }"; var srcC2 = "partial class C { partial void F(); }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(), }); } [Fact] public void Method_Partial_DeleteInsert_ImplementationPart() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { }"; var srcC2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), }); } [Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")] public void Method_Partial_Swap_ImplementationAndDefinitionParts() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { partial void F() { } }"; var srcB2 = "partial class C { partial void F(); }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), DocumentResults(), }); } [Fact] public void Method_Partial_DeleteImplementation() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void Method_Partial_DeleteBoth() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void Method_Partial_DeleteInsertBoth() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcD1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; var srcC2 = "partial class C { partial void F(); }"; var srcD2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }) }); } [Fact] public void Method_Partial_Insert() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), }); } [Fact] public void Method_Partial_Insert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { partial void F(); }"; var srcB2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } #endregion #region Operators [Theory] [InlineData("implicit", "explicit")] [InlineData("explicit", "implicit")] public void Operator_Modifiers_Update(string oldModifiers, string newModifiers) { var src1 = "class C { public static " + oldModifiers + " operator int (C c) => 0; }"; var src2 = "class C { public static " + newModifiers + " operator int (C c) => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static " + oldModifiers + " operator int (C c) => 0;]@10 -> [public static " + newModifiers + " operator int (C c) => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public static " + newModifiers + " operator int (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void Operator_Modifiers_Update_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static implicit operator int (C c) => 0; }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static explicit operator int (C c) => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Operator_Conversion_ExternModifiers_Add() { var src1 = "class C { public static implicit operator bool (C c) => default; }"; var src2 = "class C { extern public static implicit operator bool (C c); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "extern public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void Operator_Conversion_ExternModifiers_Remove() { var src1 = "class C { extern public static implicit operator bool (C c); }"; var src2 = "class C { public static implicit operator bool (C c) => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void OperatorInsert() { var src1 = @" class C { } "; var src2 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertOperator, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator), Diagnostic(RudeEditKind.InsertOperator, "public static C operator +(C c, C d)", FeaturesResources.operator_)); } [Fact] public void OperatorDelete() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(CSharpFeaturesResources.conversion_operator, "implicit operator bool(C c)")), Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.operator_, "operator +(C c, C d)"))); } [Fact] public void OperatorInsertDelete() { var srcA1 = @" partial class C { public static implicit operator bool (C c) => false; } "; var srcB1 = @" partial class C { public static C operator +(C c, C d) => c; } "; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Addition")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Implicit")) }), }); } [Fact] public void OperatorUpdate() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } } "; var src2 = @" class C { public static implicit operator bool (C c) { return true; } public static C operator +(C c, C d) { return d; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")), }); } [Fact] public void OperatorWithExpressionBody_Update() { var src1 = @" class C { public static implicit operator bool (C c) => false; public static C operator +(C c, C d) => c; } "; var src2 = @" class C { public static implicit operator bool (C c) => true; public static C operator +(C c, C d) => d; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")), }); } [Fact] public void OperatorWithExpressionBody_ToBlockBody() { var src1 = "class C { public static C operator +(C c, C d) => d; }"; var src2 = "class C { public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static C operator +(C c, C d) => d;]@10 -> [public static C operator +(C c, C d) { return c; }]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")) }); } [Fact] public void OperatorWithBlockBody_ToExpressionBody() { var src1 = "class C { public static C operator +(C c, C d) { return c; } }"; var src2 = "class C { public static C operator +(C c, C d) => d; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static C operator +(C c, C d) { return c; }]@10 -> [public static C operator +(C c, C d) => d;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")) }); } [Fact] public void OperatorReorder1() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static implicit operator int (C c) { return 1; } } "; var src2 = @" class C { public static implicit operator int (C c) { return 1; } public static implicit operator bool (C c) { return false; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [public static implicit operator int (C c) { return 1; }]@84 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void OperatorReorder2() { var src1 = @" class C { public static C operator +(C c, C d) { return c; } public static C operator -(C c, C d) { return d; } } "; var src2 = @" class C { public static C operator -(C c, C d) { return d; } public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [public static C operator -(C c, C d) { return d; }]@74 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void Operator_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { public static bool operator !(in Test b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public static bool operator !(in Test b) => throw null;]@13", "Insert [(in Test b)]@42", "Insert [in Test b]@43"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertOperator, "public static bool operator !(in Test b)", FeaturesResources.operator_)); } [Fact] public void Operator_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { public static bool operator !(Test b) => throw null; }"; var src2 = "class Test { public static bool operator !(in Test b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Test b]@43 -> [in Test b]@43"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in Test b", FeaturesResources.parameter)); } #endregion #region Constructor, Destructor [Fact] public void Constructor_Parameter_AddAttribute() { var src1 = @" class C { private int x = 1; public C(int a) { } }"; var src2 = @" class C { private int x = 2; public C([System.Obsolete]int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [x = 1]@30 -> [x = 2]@30", "Update [int a]@53 -> [[System.Obsolete]int a]@53"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C..ctor")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] [WorkItem(2068, "https://github.com/dotnet/roslyn/issues/2068")] public void Constructor_ExternModifier_Add() { var src1 = "class C { }"; var src2 = "class C { public extern C(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public extern C();]@10", "Insert [()]@25"); // This can be allowed as the compiler generates an empty constructor, but it's not worth the complexity. edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public extern C()", FeaturesResources.constructor)); } [Fact] public void ConstructorInitializer_Update1() { var src1 = @" class C { public C(int a) : base(a) { } }"; var src2 = @" class C { public C(int a) : base(a + 1) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@18 -> [public C(int a) : base(a + 1) { }]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void ConstructorInitializer_Update2() { var src1 = @" class C<T> { public C(int a) : base(a) { } }"; var src2 = @" class C<T> { public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@21 -> [public C(int a) { }]@21"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)")); } [Fact] public void ConstructorInitializer_Update3() { var src1 = @" class C { public C(int a) { } }"; var src2 = @" class C { public C(int a) : base(a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) { }]@18 -> [public C(int a) : base(a) { }]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void ConstructorInitializer_Update4() { var src1 = @" class C<T> { public C(int a) : base(a) { } }"; var src2 = @" class C<T> { public C(int a) : base(a + 1) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@21 -> [public C(int a) : base(a + 1) { }]@21"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)")); } [WorkItem(743552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743552")] [Fact] public void ConstructorUpdate_AddParameter() { var src1 = @" class C { public C(int a) { } }"; var src2 = @" class C { public C(int a, int b) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a)]@26 -> [(int a, int b)]@26", "Insert [int b]@34"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int b", FeaturesResources.parameter)); } [Fact] public void DestructorDelete() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { }"; var expectedEdit1 = @"Delete [~B() { }]@10"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(expectedEdit1); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); } [Fact] public void DestructorDelete_InsertConstructor() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { B() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [B() { }]@10", "Insert [()]@11", "Delete [~B() { }]@10"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "B()", FeaturesResources.constructor), Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); } [Fact] [WorkItem(789577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/789577")] public void ConstructorUpdate_AnonymousTypeInFieldInitializer() { var src1 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 1; } }"; var src2 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Constructor_Static_Delete() { var src1 = "class C { static C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.static_constructor, "C()"))); } [Fact] public void Constructor_Static_Delete_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { static C() { } }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Constructor_Static_Insert() { var src1 = "class C { }"; var src2 = "class C { static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void InstanceCtorDelete_Public() { var src1 = "class C { public C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("protected")] [InlineData("internal")] [InlineData("private protected")] [InlineData("protected internal")] public void InstanceCtorDelete_NonPublic(string accessibility) { var src1 = "class C { [System.Obsolete] " + accessibility + " C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")), Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void InstanceCtorDelete_Public_PartialWithInitializerUpdate() { var srcA1 = "partial class C { public C() { } }"; var srcB1 = "partial class C { int x = 1; }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void InstanceCtorInsert_Public_Implicit() { var src1 = "class C { }"; var src2 = "class C { public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void InstanceCtorInsert_Partial_Public_Implicit() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // no change in document A DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtorInsert_Public_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty)) }); } [Fact] public void InstanceCtorInsert_Partial_Public_NoImplicit() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { public C(int a) { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { public C(int a) { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty)) }), // no change in document B DocumentResults(), }); } [Fact] public void InstanceCtorInsert_Private_Implicit1() { var src1 = "class C { }"; var src2 = "class C { private C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "private C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Private_Implicit2() { var src1 = "class C { }"; var src2 = "class C { C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Protected_PublicImplicit() { var src1 = "class C { }"; var src2 = "class C { protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "protected C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Internal_PublicImplicit() { var src1 = "class C { }"; var src2 = "class C { internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Internal_ProtectedImplicit() { var src1 = "abstract class C { }"; var src2 = "abstract class C { internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorUpdate_ProtectedImplicit() { var src1 = "abstract class C { }"; var src2 = "abstract class C { protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void InstanceCtorInsert_Private_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } private C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C") .InstanceConstructors.Single(ctor => ctor.DeclaredAccessibility == Accessibility.Private)) }); } [Fact] public void InstanceCtorInsert_Internal_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void InstanceCtorInsert_Protected_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void InstanceCtorInsert_InternalProtected_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } internal protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void StaticCtor_Partial_DeleteInsert() { var srcA1 = "partial class C { static C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { static C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePrivateInsertPrivate() { var srcA1 = "partial class C { C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePublicInsertPublic() { var srcA1 = "partial class C { public C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePrivateInsertPublic() { var srcA1 = "partial class C { C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be reported as rude edit in the other document where it was inserted back with changed accessibility DocumentResults( semanticEdits: NoSemanticEdits), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }), }); } [Fact] public void StaticCtor_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { static C() { } }"; var srcA2 = "partial class C { static C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPublicDeletePublic() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { public C() { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPrivateDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { private C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_DeleteInternalInsertInternal() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { internal C() { } }"; var srcA2 = "partial class C { internal C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertInternalDeleteInternal_WithBody() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { internal C() { } }"; var srcA2 = "partial class C { internal C() { Console.WriteLine(1); } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPublicDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }), // delete of the constructor in partial part will be reported as rude in the the other document where it was inserted with changed accessibility DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertInternalDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { internal C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor) }), DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 2</N:0.2>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer_Trivia1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); /*new trivia*/public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer_ExplicitInterfaceImpl1() { var src1 = @" using System; public interface I { int B { get; } } public interface J { int B { get; } } partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C : I, J { int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>); int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>); public C() { F(<N:0.3>c => c + 1</N:0.3>); } } "; var src2 = @" using System; public interface I { int B { get; } } public interface J { int B { get; } } partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C : I, J { int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>); int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>); public C() { F(<N:0.3>c => c + 2</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void InstanceCtor_Partial_Insert_Parameterless_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()")); // TODO: //var syntaxMap = GetSyntaxMap(src1, src2); //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void InstanceCtor_Partial_Insert_WithParameters_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)")); // TODO: bug https://github.com/dotnet/roslyn/issues/2504 //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Explicit_Update() { var srcA1 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(bool arg) => Console.WriteLine(1); } "; var srcB1 = @" using System; partial class C { int a <N:0.0>= 1</N:0.0>; C(uint arg) => Console.WriteLine(2); } "; var srcA2 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(bool arg) => Console.WriteLine(1); } "; var srcB2 = @" using System; partial class C { int a <N:0.0>= 2</N:0.0>; // updated field initializer C(uint arg) => Console.WriteLine(2); C(byte arg) => Console.WriteLine(3); // new ctor } "; var syntaxMapB = GetSyntaxMap(srcB1, srcB2)[0]; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // No changes in document A DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Int32"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Boolean"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "UInt32"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Byte"), syntaxMap: null), }) }); } [Fact] public void InstanceCtor_Partial_Explicit_Update_SemanticError() { var srcA1 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(int arg) => Console.WriteLine(1); } "; var srcB1 = @" using System; partial class C { int a = 1; } "; var srcA2 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(int arg) => Console.WriteLine(1); } "; var srcB2 = @" using System; partial class C { int a = 2; C(int arg) => Console.WriteLine(2); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // No changes in document A DocumentResults(), // The actual edits do not matter since there are semantic errors in the compilation. // We just should not crash. DocumentResults(diagnostics: Array.Empty<RudeEditDiagnosticDescription>()) }); } [Fact] public void InstanceCtor_Partial_Implicit_Update() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { int G = 1; }"; var srcA2 = "partial class C { int F = 2; }"; var srcB2 = "partial class C { int G = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void ParameterlessConstructor_SemanticError_Delete1() { var src1 = @" class C { D() {} } "; var src2 = @" class C { } "; var edits = GetTopEdits(src1, src2); // The compiler interprets D() as a constructor declaration. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void Constructor_SemanticError_Partial() { var src1 = @" partial class C { partial void C(int x); } partial class C { partial void C(int x) { System.Console.WriteLine(1); } } "; var src2 = @" partial class C { partial void C(int x); } partial class C { partial void C(int x) { System.Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("C").PartialImplementationPart) }); } [Fact] public void PartialDeclaration_Delete() { var srcA1 = "partial class C { public C() { } void F() { } }"; var srcB1 = "partial class C { int x = 1; }"; var srcA2 = ""; var srcB2 = "partial class C { int x = 2; void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void PartialDeclaration_Insert() { var srcA1 = ""; var srcB1 = "partial class C { int x = 1; void F() { } }"; var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = "partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void PartialDeclaration_Insert_Reloadable() { var srcA1 = ""; var srcB1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 1; void F() { } }"; var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void Constructor_DeleteParameterless(string typeKind) { var src1 = @" " + typeKind + @" C { private int a = 10; private int b; public C() { b = 3; } } "; var src2 = @" " + typeKind + @" C { private int a = 10; private int b; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [public C() { b = 3; }]@66", "Delete [()]@74"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void Constructor_InsertParameterless(string typeKind) { var src1 = @" " + typeKind + @" C { private int a = 10; private int b; } "; var src2 = @" " + typeKind + @" C { private int a = 10; private int b; public C() { b = 3; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [public C() { b = 3; }]@66", "Insert [()]@74"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_BlockBodyToExpressionBody() { var src1 = @" public class C { private int _value; public C(int value) { _value = value; } } "; var src2 = @" public class C { private int _value; public C(int value) => _value = value; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) { _value = value; }]@52 -> [public C(int value) => _value = value;]@52"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void ConstructorWithInitializer_BlockBodyToExpressionBody() { var src1 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) { _value = value; } } "; var src2 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) => _value = value; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) : base(value) { _value = value; }]@90 -> [public C(int value) : base(value) => _value = value;]@90"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_ExpressionBodyToBlockBody() { var src1 = @" public class C { private int _value; public C(int value) => _value = value; } "; var src2 = @" public class C { private int _value; public C(int value) { _value = value; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) => _value = value;]@52 -> [public C(int value) { _value = value; }]@52"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void ConstructorWithInitializer_ExpressionBodyToBlockBody() { var src1 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) => _value = value; } "; var src2 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) { _value = value; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) : base(value) => _value = value;]@90 -> [public C(int value) : base(value) { _value = value; }]@90"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_BlockBodyToExpressionBody() { var src1 = @" public class C { ~C() { Console.WriteLine(0); } } "; var src2 = @" public class C { ~C() => Console.WriteLine(0); } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() { Console.WriteLine(0); }]@25 -> [~C() => Console.WriteLine(0);]@25"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_ExpressionBodyToBlockBody() { var src1 = @" public class C { ~C() => Console.WriteLine(0); } "; var src2 = @" public class C { ~C() { Console.WriteLine(0); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() => Console.WriteLine(0);]@25 -> [~C() { Console.WriteLine(0); }]@25"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false) }); } [Fact] public void Constructor_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [Test(in int b) => throw null;]@13", "Insert [(in int b)]@17", "Insert [in int b]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void Constructor_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "class Test { Test() => throw null; }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Constructor_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { Test(int b) => throw null; }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@18 -> [in int b]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } #endregion #region Fields and Properties with Initializers [Theory] [InlineData("class ")] [InlineData("struct")] public void FieldInitializer_Update1(string typeKind) { var src1 = typeKind + " C { int a = 0; }"; var src2 = typeKind + " C { int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@15 -> [a = 1]@15"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void PropertyInitializer_Update1(string typeKind) { var src1 = typeKind + " C { int a { get; } = 0; }"; var src2 = typeKind + " C { int a { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get; } = 0;]@11 -> [int a { get; } = 1;]@11"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializer_Update2() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a]@14"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializer_Update2() { var src1 = "class C { int a { get; } = 0; }"; var src2 = "class C { int a { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get; } = 0;]@10 -> [int a { get { return 1; } }]@10", "Update [get;]@18 -> [get { return 1; }]@18"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true)); } [Fact] public void PropertyInitializer_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int a { get; } = 0; }"; var srcA2 = "partial class C { int a { get { return 1; } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults() }); } [Fact] public void FieldInitializer_Update3() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializer_Update3() { var src1 = "class C { int a { get { return 1; } } }"; var src2 = "class C { int a { get; } = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get { return 1; } }]@10 -> [int a { get; } = 0;]@10", "Update [get { return 1; }]@18 -> [get;]@18"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorUpdate1() { var src1 = "class C { static int a; static C() { } }"; var src2 = "class C { static int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21", "Delete [static C() { }]@24", "Delete [()]@32"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_StaticCtorUpdate1() { var src1 = "class C { static int a { get; } = 1; static C() { } }"; var src2 = "class C { static int a { get; } = 2;}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void FieldInitializerUpdate_InstanceCtorUpdate_Private(string typeKind) { var src1 = typeKind + " C { int a; [System.Obsolete]C() { } }"; var src2 = typeKind + " C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, $"{typeKind} C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")), Diagnostic(RudeEditKind.ChangingAccessibility, $"{typeKind} C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Theory] [InlineData("class ")] [InlineData("struct")] public void PropertyInitializerUpdate_InstanceCtorUpdate_Private(string typeKind) { var src1 = typeKind + " C { int a { get; } = 1; C() { } }"; var src2 = typeKind + " C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, $"{typeKind} C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Theory] [InlineData("class ")] [InlineData("struct")] public void FieldInitializerUpdate_InstanceCtorUpdate_Public(string typeKind) { var src1 = typeKind + " C { int a; public C() { } }"; var src2 = typeKind + " C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void PropertyInitializerUpdate_InstanceCtorUpdate_Public(string typeKind) { var src1 = typeKind + " C { int a { get; } = 1; public C() { } }"; var src2 = typeKind + " C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorUpdate2() { var src1 = "class C { static int a; static C() { } }"; var src2 = "class C { static int a = 0; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_StaticCtorUpdate2() { var src1 = "class C { static int a { get; } = 1; static C() { } }"; var src2 = "class C { static int a { get; } = 2; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void FieldInitializerUpdate_InstanceCtorUpdate2(string typeKind) { var src1 = typeKind + " C { int a; public C() { } }"; var src2 = typeKind + " C { int a = 0; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@15 -> [a = 0]@15"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void PropertyInitializerUpdate_InstanceCtorUpdate2(string typeKind) { var src1 = typeKind + " C { int a { get; } = 1; public C() { } }"; var src2 = typeKind + " C { int a { get; } = 2; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate3() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate3() { var src1 = "class C { int a { get; } = 1; }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate4() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate5() { var src1 = "class C { int a; private C(int a) { } private C(bool a) { } }"; var src2 = "class C { int a = 0; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), }); } [Fact] public void FieldInitializerUpdate_Struct_InstanceCtorUpdate5() { var src1 = "struct C { int a; private C(int a) { } private C(bool a) { } }"; var src2 = "struct C { int a = 0; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@15 -> [a = 0]@15"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C()"), preserveLocalVariables: true), }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate5() { var src1 = "class C { int a { get; } = 1; private C(int a) { } private C(bool a) { } }"; var src2 = "class C { int a { get; } = 10000; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), }); } [Fact] public void PropertyInitializerUpdate_Struct_InstanceCtorUpdate5() { var src1 = "struct C { int a { get; } = 1; private C(int a) { } private C(bool a) { } }"; var src2 = "struct C { int a { get; } = 10000; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C()"), preserveLocalVariables: true), }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate6() { var src1 = "class C { int a; private C(int a) : this(true) { } private C(bool a) { } }"; var src2 = "class C { int a = 0; private C(int a) : this(true) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorInsertImplicit() { var src1 = "class C { static int a; }"; var src2 = "class C { static int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void FieldInitializerUpdate_StaticCtorInsertExplicit() { var src1 = "class C { static int a; }"; var src2 = "class C { static int a = 0; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [static C() { }]@28", "Insert [()]@36", "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void FieldInitializerUpdate_InstanceCtorInsertExplicit(string typeKind) { var src1 = typeKind + " C { int a; }"; var src2 = typeKind + " C { int a = 0; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void PropertyInitializerUpdate_InstanceCtorInsertExplicit(string typeKind) { var src1 = typeKind + " C { int a { get; } = 1; }"; var src2 = typeKind + " C { int a { get; } = 2; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_GenericType() { var src1 = "class C<T> { int a = 1; }"; var src2 = "class C<T> { int a = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@17 -> [a = 2]@17"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "a = 2"), Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>")); } [Fact] public void PropertyInitializerUpdate_GenericType() { var src1 = "class C<T> { int a { get; } = 1; }"; var src2 = "class C<T> { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "int a"), Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>")); } [Fact] public void FieldInitializerUpdate_StackAllocInConstructor() { var src1 = "unsafe class C { int a = 1; public C() { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a = 2; public C() { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@21 -> [a = 2]@21"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void FieldInitializerUpdate_SwitchExpressionInConstructor() { var src1 = "class C { int a = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor1() { var src1 = "unsafe class C { int a { get; } = 1; public C() { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); // TODO (tomat): diagnostic should point to the property initializer edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor2() { var src1 = "unsafe class C { int a { get; } = 1; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor3() { var src1 = "unsafe class C { int a { get; } = 1; public C() { } public C(int b) { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() { } public C(int b) { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); // TODO (tomat): diagnostic should point to the property initializer edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor1() { var src1 = "class C { int a { get; } = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a { get; } = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor2() { var src1 = "class C { int a { get; } = 1; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }"; var src2 = "class C { int a { get; } = 2; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor3() { var src1 = "class C { int a { get; } = 1; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a { get; } = 2; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_LambdaInConstructor() { var src1 = "class C { int a = 1; public C() { F(() => {}); } static void F(System.Action a) {} }"; var src2 = "class C { int a = 2; public C() { F(() => {}); } static void F(System.Action a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@14 -> [a = 2]@14"); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_LambdaInConstructor() { var src1 = "class C { int a { get; } = 1; public C() { F(() => {}); } static void F(System.Action a) {} }"; var src2 = "class C { int a { get; } = 2; public C() { F(() => {}); } static void F(System.Action a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_QueryInConstructor() { var src1 = "using System.Linq; class C { int a = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var src2 = "using System.Linq; class C { int a = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@33 -> [a = 2]@33"); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_QueryInConstructor() { var src1 = "using System.Linq; class C { int a { get; } = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var src2 = "using System.Linq; class C { int a { get; } = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_AnonymousTypeInConstructor() { var src1 = "class C { int a = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var src2 = "class C { int a = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_AnonymousTypeInConstructor() { var src1 = "class C { int a { get; } = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var src2 = "class C { int a { get; } = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_PartialTypeWithSingleDeclaration() { var src1 = "partial class C { int a = 1; }"; var src2 = "partial class C { int a = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@22 -> [a = 2]@22"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_PartialTypeWithSingleDeclaration() { var src1 = "partial class C { int a { get; } = 1; }"; var src2 = "partial class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_PartialTypeWithMultipleDeclarations() { var src1 = "partial class C { int a = 1; } partial class C { }"; var src2 = "partial class C { int a = 2; } partial class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@22 -> [a = 2]@22"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_PartialTypeWithMultipleDeclarations() { var src1 = "partial class C { int a { get; } = 1; } partial class C { }"; var src2 = "partial class C { int a { get; } = 2; } partial class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_ParenthesizedLambda() { var src1 = "class C { int a = F(1, (x, y) => x + y); }"; var src2 = "class C { int a = F(2, (x, y) => x + y); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_ParenthesizedLambda() { var src1 = "class C { int a { get; } = F(1, (x, y) => x + y); }"; var src2 = "class C { int a { get; } = F(2, (x, y) => x + y); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_SimpleLambda() { var src1 = "class C { int a = F(1, x => x); }"; var src2 = "class C { int a = F(2, x => x); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_SimpleLambda() { var src1 = "class C { int a { get; } = F(1, x => x); }"; var src2 = "class C { int a { get; } = F(2, x => x); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_Query() { var src1 = "class C { int a = F(1, from goo in bar select baz); }"; var src2 = "class C { int a = F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_Query() { var src1 = "class C { int a { get; } = F(1, from goo in bar select baz); }"; var src2 = "class C { int a { get; } = F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_AnonymousType() { var src1 = "class C { int a = F(1, new { A = 1, B = 2 }); }"; var src2 = "class C { int a = F(2, new { A = 1, B = 2 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_AnonymousType() { var src1 = "class C { int a { get; } = F(1, new { A = 1, B = 2 }); }"; var src2 = "class C { int a { get; } = F(2, new { A = 1, B = 2 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 1; int B = F(<N:0.0>b => b + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 2; int B = F(<N:0.0>b => b + 1</N:0.0>); } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C() {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C() {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 1; int B = F(<N:0.0>b => b + 1</N:0.0>); public C() {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 2; int B = F(<N:0.0>b => b + 1</N:0.0>); public C() {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializers_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) {} public C(bool b) {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C(int a) {} public C(bool b) {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda_Trivia1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 2</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda_Trivia1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_EditConstructorNotIncludingInitializers() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)")) }); } [Fact] public void FieldInitializerUpdate_Lambdas_RemoveCtorInitializer1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_AddCtorInitializer1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)")) }); } [Fact] public void FieldInitializerUpdate_Lambdas_UpdateBaseCtorInitializerWithLambdas1() { var src1 = @" using System; class B { public B(int a) { } } class C : B { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(bool b) : base(F(<N:0.2>c => c + 1</N:0.2>)) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class B { public B(int a) { } } class C : B { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(bool b) : base(F(<N:0.2>c => c + 2</N:0.2>)) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_PartialDeclarationDelete_SingleDocument() { var src1 = @" partial class C { int x = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int y = F(<N:0.1>a => a + 10</N:0.1>); } partial class C { public C() { } static int F(Func<int, int> x) => 1; } "; var src2 = @" partial class C { int x = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int y = F(<N:0.1>a => a + 10</N:0.1>); static int F(Func<int, int> x) => 1; } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), syntaxMap[0]), }); } [Fact] public void FieldInitializerUpdate_ActiveStatements1() { var src1 = @" using System; class C { <AS:0>int A = <N:0.0>1</N:0.0>;</AS:0> int B = 1; public C(int a) { Console.WriteLine(1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { <AS:0>int A = <N:0.0>1</N:0.0>;</AS:0> int B = 2; public C(int a) { Console.WriteLine(1); } public C(bool b) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); var activeStatements = GetActiveStatements(src1, src2); edits.VerifySemantics( activeStatements, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]), }); } [Fact] public void PropertyWithInitializer_SemanticError_Partial() { var src1 = @" partial class C { partial int P => 1; } partial class C { partial int P => 1; } "; var src2 = @" partial class C { partial int P => 1; } partial class C { partial int P => 2; public C() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => ((IPropertySymbol)c.GetMember<INamedTypeSymbol>("C").GetMembers("P").First()).GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Partial_DeleteInsert_InitializerRemoval() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int F; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void Field_Partial_DeleteInsert_InitializerUpdate() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int F = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } #endregion #region Fields [Fact] public void Field_Rename() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int b = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [b = 0]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "b = 0", FeaturesResources.field)); } [Fact] public void Field_Kind_Update() { var src1 = "class C { Action a; }"; var src2 = "class C { event Action a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Action a;]@10 -> [event Action a;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.FieldKindUpdate, "event Action a", FeaturesResources.event_)); } [Theory] [InlineData("static")] [InlineData("volatile")] [InlineData("const")] public void Field_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F = 0; }"; var src2 = "class C { " + newModifiers + "int F = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F = 0;]@10 -> [" + newModifiers + "int F = 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F = 0", FeaturesResources.field)); } [Fact] public void Field_Modifier_Add_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int F; }"; var srcA2 = "partial class C { static int F; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ModifiersUpdate, "F", FeaturesResources.field) }), DocumentResults(), }); } [Fact] public void Field_Attribute_Add_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int F; }"; var srcA2 = "partial class C { [System.Obsolete]int F; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }), DocumentResults(), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_FixedSize_Update() { var src1 = "struct S { public unsafe fixed byte a[1], b[2]; }"; var src2 = "struct S { public unsafe fixed byte a[2], b[3]; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a[1]]@36 -> [a[2]]@36", "Update [b[2]]@42 -> [b[3]]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "a[2]", FeaturesResources.field), Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "b[3]", FeaturesResources.field)); } [WorkItem(1120407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1120407")] [Fact] public void Field_Const_Update() { var src1 = "class C { const int x = 0; }"; var src2 = "class C { const int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [x = 0]@20 -> [x = 1]@20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "x = 1", FeaturesResources.const_field)); } [Fact] public void Field_Event_VariableDeclarator_Update() { var src1 = "class C { event Action a; }"; var src2 = "class C { event Action a = () => { }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@23 -> [a = () => { }]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void Field_Reorder() { var src1 = "class C { int a = 0; int b = 1; int c = 2; }"; var src2 = "class C { int c = 2; int a = 0; int b = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int c = 2;]@32 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int c = 2", FeaturesResources.field)); } [Fact] public void Field_Insert() { var src1 = "class C { }"; var src2 = "class C { int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a = 1;]@10", "Insert [int a = 1]@10", "Insert [a = 1]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Insert_IntoStruct() { var src1 = @" struct S { public int a; public S(int z) { this = default(S); a = z; } } "; var src2 = @" struct S { public int a; private int b; private static int c; private static int f = 1; private event System.Action d; public S(int z) { this = default(S); a = z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "b", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "c", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "f = 1", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "d", CSharpFeaturesResources.event_field, CSharpFeaturesResources.struct_)); } [Fact] public void Field_Insert_IntoLayoutClass_Auto() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Auto)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Auto)] class C { private int a; private int b; private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.b")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.c")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.d")), }); } [Fact] public void Field_Insert_IntoLayoutClass_Explicit() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Explicit)] class C { [FieldOffset(0)] private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Explicit)] class C { [FieldOffset(0)] private int a; [FieldOffset(0)] private int b; [FieldOffset(4)] private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_)); } [Fact] public void Field_Insert_IntoLayoutClass_Sequential() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; private int b; private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_)); } [Fact] public void Field_Insert_WithInitializersAndLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C() { F(<N:0.1>c => c + 1</N:0.1>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C() { F(<N:0.1>c => c + 1</N:0.1>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void Field_Insert_ConstructorReplacingImplicitConstructor_WithInitializersAndLambdas() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C() // new ctor replacing existing implicit constructor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ParameterlessConstructorInsert_WithInitializersAndLambdas() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C(int x) {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C(int x) {} public C() // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()")); // TODO (bug https://github.com/dotnet/roslyn/issues/2504): //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] // { // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) // }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersAndLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)")); // TODO (bug https://github.com/dotnet/roslyn/issues/2504): //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] // { // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) // }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersButNoExistingLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(null); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(null); int B = F(b => b + 1); // new field public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single()) }); } [Fact] public void Field_Insert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { public int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddStaticFieldToExistingType, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field)); } [Fact] public void Field_Insert_Static_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { public static int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddInstanceFieldToExistingType, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field)); } [Fact] public void Field_Attribute_Add_NotSupportedByRuntime() { var src1 = @" class C { public int a = 1, x = 1; }"; var src2 = @" class C { [System.Obsolete]public int a = 1, x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public int a = 1, x = 1;]@18 -> [[System.Obsolete]public int a = 1, x = 1;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field)); } [Fact] public void Field_Attribute_Add() { var src1 = @" class C { public int a, b; }"; var src2 = @" class C { [System.Obsolete]public int a, b; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.b")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Attribute_Add_WithInitializer() { var src1 = @" class C { int a; }"; var src2 = @" class C { [System.Obsolete]int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Attribute_DeleteInsertUpdate_WithInitializer() { var srcA1 = "partial class C { int a = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { [System.Obsolete]int a = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Delete1() { var src1 = "class C { int a = 1; }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a = 1;]@10", "Delete [int a = 1]@10", "Delete [a = 1]@14"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void Field_UnsafeModifier_Update() { var src1 = "struct Node { unsafe Node* left; }"; var src2 = "struct Node { Node* left; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [unsafe Node* left;]@14 -> [Node* left;]@14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Field_ModifierAndType_Update() { var src1 = "struct Node { unsafe Node* left; }"; var src2 = "struct Node { Node left; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [unsafe Node* left;]@14 -> [Node left;]@14", "Update [Node* left]@21 -> [Node left]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "Node left", FeaturesResources.field)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Field_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { " + oldType + " F, G; }"; var src2 = "class C { " + newType + " F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Field_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { " + oldType + " F, G; }"; var src2 = "class C { " + newType + " F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Field_Event_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { event System.Action<" + oldType + "> F, G; }"; var src2 = "class C { event System.Action<" + newType + "> F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Field_Event_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { event System.Action<" + oldType + "> F, G; }"; var src2 = "class C { event System.Action<" + newType + "> F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_), Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_)); } [Fact] public void Field_Type_Update_ReorderRemoveAdd() { var src1 = "class C { int F, G, H; bool U; }"; var src2 = "class C { string G, F; double V, U; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int F, G, H]@10 -> [string G, F]@10", "Reorder [G]@17 -> @17", "Update [bool U]@23 -> [double V, U]@23", "Insert [V]@30", "Delete [H]@20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "G", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "double V, U", FeaturesResources.field), Diagnostic(RudeEditKind.Delete, "string G, F", DeletedSymbolDisplay(FeaturesResources.field, "H"))); } [Fact] public void Field_Event_Reorder() { var src1 = "class C { int a = 0; int b = 1; event int c = 2; }"; var src2 = "class C { event int c = 2; int a = 0; int b = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [event int c = 2;]@32 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "event int c = 2", CSharpFeaturesResources.event_field)); } [Fact] public void Field_Event_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { event int E = 2; }"; var srcA2 = "partial class C { event int E = 2; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults(), }); } #endregion #region Properties [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Property_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F => 0; }"; var src2 = "class C { " + newModifiers + "int F => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F => 0;]@10 -> [" + newModifiers + "int F => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F", FeaturesResources.property_)); } [Fact] public void Property_ExpressionBody_Rename() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int Q => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void Property_ExpressionBody_Update() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P => 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int P => 1;]@10 -> [int P => 2;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Property_ExpressionBody_ModifierUpdate() { var src1 = "class C { int P => 1; }"; var src2 = "class C { unsafe int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int P => 1;]@10 -> [unsafe int P => 1;]@10"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ExpressionBodyToBlockBody1() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get { return 2; } }]@10", "Insert [{ get { return 2; } }]@16", "Insert [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact] public void Property_ExpressionBodyToBlockBody2() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get { return 2; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get { return 2; } set { } }]@10", "Insert [{ get { return 2; } set { } }]@16", "Insert [get { return 2; }]@18", "Insert [set { }]@36"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_P"), preserveLocalVariables: false) }); } [Fact] public void Property_BlockBodyToExpressionBody1() { var src1 = "class C { int P { get { return 2; } } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get { return 2; } }]@10 -> [int P => 1;]@10", "Delete [{ get { return 2; } }]@16", "Delete [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact] public void Property_BlockBodyToExpressionBody2() { var src1 = "class C { int P { get { return 2; } set { } } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get { return 2; } set { } }]@10 -> [int P => 1;]@10", "Delete [{ get { return 2; } set { } }]@16", "Delete [get { return 2; }]@18", "Delete [set { }]@36"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_ExpressionBodyToGetterExpressionBody() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get => 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get => 2; }]@10", "Insert [{ get => 2; }]@16", "Insert [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyToExpressionBody() { var src1 = "class C { int P { get => 2; } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get => 2; }]@10 -> [int P => 1;]@10", "Delete [{ get => 2; }]@16", "Delete [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterBlockBodyToGetterExpressionBody() { var src1 = "class C { int P { get { return 2; } } }"; var src2 = "class C { int P { get => 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_SetterBlockBodyToSetterExpressionBody() { var src1 = "class C { int P { set { } } }"; var src2 = "class C { int P { set => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [set { }]@18 -> [set => F();]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_InitBlockBodyToInitExpressionBody() { var src1 = "class C { int P { init { } } }"; var src2 = "class C { int P { init => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [init { }]@18 -> [init => F();]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod, preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyToGetterBlockBody() { var src1 = "class C { int P { get => 2; } }"; var src2 = "class C { int P { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterBlockBodyWithSetterToGetterExpressionBodyWithSetter() { var src1 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }"; var src2 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyWithSetterToGetterBlockBodyWithSetter() { var src1 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_P"), preserveLocalVariables: false) }); } [Fact] public void Property_Rename1() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { int Q { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void Property_Rename2() { var src1 = "class C { int I.P { get { return 1; } } }"; var src2 = "class C { int J.P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int J.P", FeaturesResources.property_)); } [Fact] public void Property_RenameAndUpdate() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { int Q { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void PropertyDelete() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.property_, "P"))); } [Fact] public void PropertyReorder1() { var src1 = "class C { int P { get { return 1; } } int Q { get { return 1; } } }"; var src2 = "class C { int Q { get { return 1; } } int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int Q { get { return 1; } }]@38 -> @10"); // TODO: we can allow the move since the property doesn't have a backing field edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.property_)); } [Fact] public void PropertyReorder2() { var src1 = "class C { int P { get; set; } int Q { get; set; } }"; var src2 = "class C { int Q { get; set; } int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int Q { get; set; }]@30 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.auto_property)); } [Fact] public void PropertyAccessorReorder_GetSet() { var src1 = "class C { int P { get { return 1; } set { } } }"; var src2 = "class C { int P { set { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [set { }]@36 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyAccessorReorder_GetInit() { var src1 = "class C { int P { get { return 1; } init { } } }"; var src2 = "class C { int P { init { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [init { }]@36 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyTypeUpdate() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { char P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get; set; }]@10 -> [char P { get; set; }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "char P", FeaturesResources.property_)); } [Fact] public void PropertyUpdate_AddAttribute() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { [System.Obsolete]int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int P", FeaturesResources.property_)); } [Fact] public void PropertyUpdate_AddAttribute_SupportedByRuntime() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { [System.Obsolete]int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.P")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyAccessorUpdate_AddAttribute() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { [System.Obsolete]get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "get", CSharpFeaturesResources.property_getter)); } [Fact] public void PropertyAccessorUpdate_AddAttribute2() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; [System.Obsolete]set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "set", CSharpFeaturesResources.property_setter)); } [Fact] public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { [System.Obsolete]get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime2() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; [System.Obsolete]set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyInsert() { var src1 = "class C { }"; var src2 = "class C { int P { get => 1; set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("P"))); } [Fact] public void PropertyInsert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { int P { get => 1; set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "int P", FeaturesResources.auto_property)); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void PropertyInsert_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { private static extern int P1 { [DllImport(""x.dll"")]get; } private static extern int P2 { [DllImport(""x.dll"")]set; } private static extern int P3 { [DllImport(""x.dll"")]get; [DllImport(""x.dll"")]set; } } "; var edits = GetTopEdits(src1, src2); // CLR doesn't support methods without a body edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "private static extern int P1", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "private static extern int P2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "private static extern int P3", FeaturesResources.property_)); } [Fact] public void PropertyInsert_IntoStruct() { var src1 = @" struct S { public int a; public S(int z) { a = z; } } "; var src2 = @" struct S { public int a; private static int c { get; set; } private static int e { get { return 0; } set { } } private static int g { get; } = 1; private static int i { get; set; } = 1; private static int k => 1; public S(int z) { a = z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "private static int c { get; set; }", FeaturesResources.auto_property, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "private static int g { get; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_)); } [Fact] public void PropertyInsert_IntoLayoutClass_Sequential() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; private int b { get; set; } private static int c { get; set; } private int d { get { return 0; } set { } } private static int e { get { return 0; } set { } } private int f { get; } = 1; private static int g { get; } = 1; private int h { get; set; } = 1; private static int i { get; set; } = 1; private int j => 1; private static int k => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int b { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int c { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int f { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int g { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int h { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_)); } // Design: Adding private accessors should also be allowed since we now allow adding private methods // and adding public properties and/or public accessors are not allowed. [Fact] public void PrivateProperty_AccessorAdd() { var src1 = "class C { int _p; int P { get { return 1; } } }"; var src2 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { _p = value; }]@44"); edits.VerifyRudeDiagnostics(); } [WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")] [Fact] public void PrivatePropertyAccessorDelete() { var src1 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }"; var src2 = "class C { int _p; int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set { _p = value; }]@44"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void PrivateAutoPropertyAccessorAdd1() { var src1 = "class C { int P { get; } }"; var src2 = "class C { int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd2() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; private set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [private set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd4() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd5() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; internal set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [internal set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd6() { var src1 = "class C { int P { get; } = 1; }"; var src2 = "class C { int P { get; set; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd_Init() { var src1 = "class C { int P { get; } = 1; }"; var src2 = "class C { int P { get; init; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [init;]@23"); edits.VerifyRudeDiagnostics(); } [WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")] [Fact] public void PrivateAutoPropertyAccessorDelete_Get() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [get;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_getter, "P.get"))); } [Fact] public void AutoPropertyAccessor_SetToInit() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; init; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [set;]@23 -> [init;]@23"); // not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq) edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "init", CSharpFeaturesResources.property_setter)); } [Fact] public void AutoPropertyAccessor_InitToSet() { var src1 = "class C { int P { get; init; } }"; var src2 = "class C { int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [init;]@23 -> [set;]@23"); // not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq) edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter)); } [Fact] public void PrivateAutoPropertyAccessorDelete_Set() { var src1 = "class C { int P { get; set; } = 1; }"; var src2 = "class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set;]@23"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void PrivateAutoPropertyAccessorDelete_Init() { var src1 = "class C { int P { get; init; } = 1; }"; var src2 = "class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [init;]@23"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.init"))); } [Fact] public void AutoPropertyAccessorUpdate() { var src1 = "class C { int P { get; } }"; var src2 = "class C { int P { set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get;]@18 -> [set;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter)); } [WorkItem(992578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/992578")] [Fact] public void InsertIncompleteProperty() { var src1 = "class C { }"; var src2 = "class C { public int P { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [public int P { }]@10", "Insert [{ }]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ReadOnlyRef_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int P { get; }]@13", "Insert [{ get; }]@32", "Insert [get;]@34"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ReadOnlyRef_Update() { var src1 = "class Test { int P { get; } }"; var src2 = "class Test { ref readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get; }]@13 -> [ref readonly int P { get; }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int P", FeaturesResources.property_)); } [Fact] public void Property_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get => 1; set { } } }"; var srcA2 = "partial class C { int P { get => 1; set { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }), DocumentResults(), }); } [Fact] public void PropertyInit_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int Q { get => 1; init { } }}"; var srcA2 = "partial class C { int Q { get => 1; init { } }}"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod) }), DocumentResults(), }); } [Fact] public void AutoProperty_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get; set; } int Q { get; init; } }"; var srcA2 = "partial class C { int P { get; set; } int Q { get; init; } }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod), }), DocumentResults(), }); } [Fact] public void AutoPropertyWithInitializer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get; set; } = 1; }"; var srcA2 = "partial class C { int P { get; set; } = 1; }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults(), }); } [Fact] public void PropertyWithExpressionBody_Partial_InsertDeleteUpdate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P => 1; }"; var srcA2 = "partial class C { int P => 2; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }), DocumentResults(), }); } [Fact] public void AutoProperty_ReadOnly_Add() { var src1 = @" struct S { int P { get; } }"; var src2 = @" struct S { readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Property_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { int P1 { get => 1; } int P2 { get => 1; set {}} int P3 { get => 1; set {}} int P4 { get => 1; set {}} }"; var src2 = @" struct S { readonly int P1 { get => 1; } int P2 { readonly get => 1; set {}} int P3 { get => 1; readonly set {}} readonly int P4 { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P1", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_setter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.property_setter)); } [Fact] public void Property_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes var src1 = @" readonly struct S { int P1 { get => 1; } int P2 { get => 1; set {}} int P3 { get => 1; set {}} int P4 { get => 1; set {}} }"; var src2 = @" readonly struct S { readonly int P1 { get => 1; } int P2 { readonly get => 1; set {}} int P3 { get => 1; readonly set {}} readonly int P4 { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated edits.VerifySemantics(new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P3").SetMethod, preserveLocalVariables: false) }); } #endregion #region Indexers [Theory] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Indexer_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int this[int a] => 0; }"; var src2 = "class C { " + newModifiers + "int this[int a] => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int this[int a] => 0;]@10 -> [" + newModifiers + "int this[int a] => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int this[int a]", FeaturesResources.indexer_)); } [Fact] public void Indexer_GetterUpdate() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [get { return 1; }]@28 -> [get { return 2; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_SetterUpdate() { var src1 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value); } } }"; var src2 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value + 1); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [set { System.Console.WriteLine(value); }]@46 -> [set { System.Console.WriteLine(value + 1); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_InitUpdate() { var src1 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value); } } }"; var src2 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value + 1); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [init { System.Console.WriteLine(value); }]@46 -> [init { System.Console.WriteLine(value + 1); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void IndexerWithExpressionBody_Update() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] => 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] => 2;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => a + 1)() + 10; } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => 2)() + 11; // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => a + 1)() + 10;]@35 -> [int this[int a] => new Func<int>(() => 2)() + 11;]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_2() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => a + 1)(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => 2)(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => a + 1)();]@35 -> [int this[int a] => new Func<int>(() => 2)();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_3() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => { return a + 1; })(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => { return 2; })(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(() => { return 2; })();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_4() { var src1 = @" using System; class C { int this[int a] => new Func<int>(delegate { return a + 1; })(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(delegate { return 2; })(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(delegate { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(delegate { return 2; })();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToBlockBody() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } }]@10", "Insert [{ get { return 1; } }]@26", "Insert [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_BlockBodyToExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get { return 1; } }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get { return 1; } }]@26", "Delete [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToBlockBody() { var src1 = "class C { int this[int a] { get => 1; } }"; var src2 = "class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_BlockBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToExpressionBody() { var src1 = "class C { int this[int a] { get => 1; } }"; var src2 = "class C { int this[int a] => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get => 1; }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get => 1; }]@26", "Delete [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get => 1; }]@10", "Insert [{ get => 1; }]@26", "Insert [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterBlockBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_SetterBlockBodyToSetterExpressionBody() { var src1 = "class C { int this[int a] { set { } } void F() { } }"; var src2 = "class C { int this[int a] { set => F(); } void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [set { }]@28 -> [set => F();]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_InitBlockBodyToInitExpressionBody() { var src1 = "class C { int this[int a] { init { } } void F() { } }"; var src2 = "class C { int this[int a] { init => F(); } void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [init { }]@28 -> [init => F();]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToGetterBlockBody() { var src1 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterAndSetterBlockBodiesToExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get { return 1; } set { Console.WriteLine(0); } }]@26", "Delete [get { return 1; }]@28", "Delete [set { Console.WriteLine(0); }]@46"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int this[int a]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int a].set"))); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToGetterAndSetterBlockBodies() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10", "Insert [{ get { return 1; } set { Console.WriteLine(0); } }]@26", "Insert [get { return 1; }]@28", "Insert [set { Console.WriteLine(0); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_Rename() { var src1 = "class C { int I.this[int a] { get { return 1; } } }"; var src2 = "class C { int J.this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int J.this[int a]", CSharpFeaturesResources.indexer)); } [Fact] public void Indexer_Reorder1() { var src1 = "class C { int this[int a] { get { return 1; } } int this[string a] { get { return 1; } } }"; var src2 = "class C { int this[string a] { get { return 1; } } int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int this[string a] { get { return 1; } }]@48 -> @10"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_AccessorReorder() { var src1 = "class C { int this[int a] { get { return 1; } set { } } }"; var src2 = "class C { int this[int a] { set { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [set { }]@46 -> @28"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_TypeUpdate() { var src1 = "class C { int this[int a] { get; set; } }"; var src2 = "class C { string this[int a] { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get; set; }]@10 -> [string this[int a] { get; set; }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "string this[int a]", CSharpFeaturesResources.indexer)); } [Fact] public void Tuple_TypeUpdate() { var src1 = "class C { (int, int) M() { throw new System.Exception(); } }"; var src2 = "class C { (string, int) M() { throw new System.Exception(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) M() { throw new System.Exception(); }]@10 -> [(string, int) M() { throw new System.Exception(); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(string, int) M()", FeaturesResources.method)); } [Fact] public void TupleElementDelete() { var src1 = "class C { (int, int, int a) M() { return (1, 2, 3); } }"; var src2 = "class C { (int, int) M() { return (1, 2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int, int a) M() { return (1, 2, 3); }]@10 -> [(int, int) M() { return (1, 2); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(int, int) M()", FeaturesResources.method)); } [Fact] public void TupleElementAdd() { var src1 = "class C { (int, int) M() { return (1, 2); } }"; var src2 = "class C { (int, int, int a) M() { return (1, 2, 3); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) M() { return (1, 2); }]@10 -> [(int, int, int a) M() { return (1, 2, 3); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(int, int, int a) M()", FeaturesResources.method)); } [Fact] public void Indexer_ParameterUpdate() { var src1 = "class C { int this[int a] { get; set; } }"; var src2 = "class C { int this[string a] { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "string a", FeaturesResources.parameter)); } [Fact] public void Indexer_AddGetAccessor() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { set { arr[i] = value; } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [get { return arr[i]; }]@304"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "get", CSharpFeaturesResources.indexer_getter)); } [Fact] public void Indexer_AddSetAccessor() { var src1 = @" class C { public int this[int i] { get { return default; } } }"; var src2 = @" class C { public int this[int i] { get { return default; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@67"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod)); } [Fact] public void Indexer_AddSetAccessor_GenericType() { var src1 = @" class C<T> { public T this[int i] { get { return default; } } }"; var src2 = @" class C<T> { public T this[int i] { get { return default; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@68"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "set", CSharpFeaturesResources.indexer_setter)); } [WorkItem(750109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750109")] [Fact] public void Indexer_DeleteGetAccessor() { var src1 = @" class C<T> { public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; var src2 = @" class C<T> { public T this[int i] { set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [get { return arr[i]; }]@58"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public T this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_getter, "this[int i].get"))); } [Fact] public void Indexer_DeleteSetAccessor() { var src1 = @" class C { public int this[int i] { get { return 0; } set { } } }"; var src2 = @" class C { public int this[int i] { get { return 0; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set { }]@61"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public int this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int i].set"))); } [Fact, WorkItem(1174850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174850")] public void Indexer_Insert() { var src1 = "struct C { }"; var src2 = "struct C { public int this[int x, int y] { get { return x + y; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { int this[in int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int this[in int i] => throw null;]@13", "Insert [[in int i]]@21", "Insert [in int i]@22"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { int this[int i] => throw null; }"; var src2 = "class Test { int this[in int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int i]@22 -> [in int i]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int i", FeaturesResources.parameter)); } [Fact] public void Indexer_ReadOnlyRef_ReturnType_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int this[int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int this[int i] => throw null;]@13", "Insert [[int i]]@34", "Insert [int i]@35"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_ReturnType_Update() { var src1 = "class Test { int this[int i] => throw null; }"; var src2 = "class Test { ref readonly int this[int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int i] => throw null;]@13 -> [ref readonly int this[int i] => throw null;]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int this[int i]", FeaturesResources.indexer_)); } [Fact] public void Indexer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get => 1; set { } } }"; var srcA2 = "partial class C { int this[int x] { get => 1; set { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod) }), DocumentResults(), }); } [Fact] public void IndexerInit_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get => 1; init { } }}"; var srcA2 = "partial class C { int this[int x] { get => 1; init { } }}"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod) }), DocumentResults(), }); } [Fact] public void AutoIndexer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get; set; } }"; var srcA2 = "partial class C { int this[int x] { get; set; } }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod), }), DocumentResults(), }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Partial_InsertDeleteUpdate_LiftedParameter() { var srcA1 = @" partial class C { }"; var srcB1 = @" partial class C { int this[int a] => new System.Func<int>(() => a + 1); }"; var srcA2 = @" partial class C { int this[int a] => new System.Func<int>(() => 2); // no capture }"; var srcB2 = @" partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a") }), DocumentResults(), }); } [Fact] public void AutoIndexer_ReadOnly_Add() { var src1 = @" struct S { int this[int x] { get; } }"; var src2 = @" struct S { readonly int this[int x] { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter)); } [Fact] public void Indexer_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { int this[int x] { get => 1; } int this[uint x] { get => 1; set {}} int this[byte x] { get => 1; set {}} int this[sbyte x] { get => 1; set {}} }"; var src2 = @" struct S { readonly int this[int x] { get => 1; } int this[uint x] { readonly get => 1; set {}} int this[byte x] { get => 1; readonly set {}} readonly int this[sbyte x] { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_setter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.indexer_setter)); } [Fact] public void Indexer_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes var src1 = @" readonly struct S { int this[int x] { get => 1; } int this[uint x] { get => 1; set {}} int this[byte x] { get => 1; set {}} int this[sbyte x] { get => 1; set {}} }"; var src2 = @" readonly struct S { readonly int this[int x] { get => 1; } int this[uint x] { readonly get => 1; set {}} int this[byte x] { get => 1; readonly set {}} readonly int this[sbyte x] { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated edits.VerifySemantics(new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "UInt32").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false) }); } #endregion #region Events [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Event_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "event Action F { add {} remove {} } }"; var src2 = "class C { " + newModifiers + "event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "event Action F { add {} remove {} }]@10 -> [" + newModifiers + "event Action F { add {} remove {} }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "event Action F", FeaturesResources.event_)); } [Fact] public void Event_Accessor_Reorder1() { var src1 = "class C { event int E { add { } remove { } } }"; var src2 = "class C { event int E { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [remove { }]@32 -> @24"); edits.VerifyRudeDiagnostics(); } [Fact] public void Event_Accessor_Reorder2() { var src1 = "class C { event int E1 { add { } remove { } } event int E1 { add { } remove { } } }"; var src2 = "class C { event int E2 { remove { } add { } } event int E2 { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event int E1 { add { } remove { } }]@10 -> [event int E2 { remove { } add { } }]@10", "Update [event int E1 { add { } remove { } }]@49 -> [event int E2 { remove { } add { } }]@49", "Reorder [remove { }]@33 -> @25", "Reorder [remove { }]@72 -> @64"); } [Fact] public void Event_Accessor_Reorder3() { var src1 = "class C { event int E1 { add { } remove { } } event int E2 { add { } remove { } } }"; var src2 = "class C { event int E2 { remove { } add { } } event int E1 { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [event int E2 { add { } remove { } }]@49 -> @10", "Reorder [remove { }]@72 -> @25", "Reorder [remove { }]@33 -> @64"); } [Fact] public void Event_Insert() { var src1 = "class C { }"; var src2 = "class C { event int E { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("E"))); } [Fact] public void Event_Delete() { var src1 = "class C { event int E { remove { } add { } } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.event_, "E"))); } [Fact] public void Event_Insert_IntoLayoutClass_Sequential() { var src1 = @" using System; using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { } "; var src2 = @" using System; using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private event Action c { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Event_ExpressionBodyToBlockBody() { var src1 = @" using System; public class C { event Action E { add => F(); remove => F(); } } "; var src2 = @" using System; public class C { event Action E { add { F(); } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [add => F();]@57 -> [add { F(); }]@56", "Update [remove => F();]@69 -> [remove { }]@69" ); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Event_BlockBodyToExpressionBody() { var src1 = @" using System; public class C { event Action E { add { F(); } remove { } } } "; var src2 = @" using System; public class C { event Action E { add => F(); remove => F(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [add { F(); }]@56 -> [add => F();]@57", "Update [remove { }]@69 -> [remove => F();]@69" ); edits.VerifySemanticDiagnostics(); } [Fact] public void Event_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { event int E { add { } remove { } } }"; var srcA2 = "partial class C { event int E { add { } remove { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod) }), DocumentResults(), }); } [Fact] public void Event_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { public event Action E { add {} remove {} } }"; var src2 = @" struct S { public readonly event Action E { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly event Action E", FeaturesResources.event_)); } [Fact] public void Event_InReadOnlyStruct_ReadOnly_Add1() { var src1 = @" readonly struct S { public event Action E { add {} remove {} } }"; var src2 = @" readonly struct S { public readonly event Action E { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); // Currently, an edit is produced eventhough bodies nor IsReadOnly attribute have changed. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").RemoveMethod)); } [Fact] public void Field_Event_Attribute_Add() { var src1 = @" class C { event Action F; }"; var src2 = @" class C { [System.Obsolete]event Action F; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event Action F;]@18 -> [[System.Obsolete]event Action F;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Attribute_Add() { var src1 = @" class C { event Action F { add {} remove {} } }"; var src2 = @" class C { [System.Obsolete]event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event Action F { add {} remove {} }]@18 -> [[System.Obsolete]event Action F { add {} remove {} }]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Accessor_Attribute_Add() { var src1 = @" class C { event Action F { add {} remove {} } }"; var src2 = @" class C { event Action F { add {} [System.Obsolete]remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [remove {}]@42 -> [[System.Obsolete]remove {}]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "remove", FeaturesResources.event_accessor)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Event_Attribute_Delete() { var src1 = @" class C { [System.Obsolete]event Action F; }"; var src2 = @" class C { event Action F; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]event Action F;]@18 -> [event Action F;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Attribute_Delete() { var src1 = @" class C { [System.Obsolete]event Action F { add {} remove {} } }"; var src2 = @" class C { event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]event Action F { add {} remove {} }]@18 -> [event Action F { add {} remove {} }]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Accessor_Attribute_Delete() { var src1 = @" class C { event Action F { add {} [System.Obsolete]remove {} } }"; var src2 = @" class C { event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]remove {}]@42 -> [remove {}]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "remove", FeaturesResources.event_accessor)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Parameter [Fact] public void ParameterRename_Method1() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [int b]@24"); } [Fact] public void ParameterRename_Ctor1() { var src1 = @"class C { public C(int a) {} }"; var src2 = @"class C { public C(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@19 -> [int b]@19"); } [Fact] public void ParameterRename_Operator1() { var src1 = @"class C { public static implicit operator int(C a) {} }"; var src2 = @"class C { public static implicit operator int(C b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [C a]@46 -> [C b]@46"); } [Fact] public void ParameterRename_Operator2() { var src1 = @"class C { public static int operator +(C a, C b) { return 0; } }"; var src2 = @"class C { public static int operator +(C a, C x) { return 0; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [C b]@44 -> [C x]@44"); } [Fact] public void ParameterRename_Indexer2() { var src1 = @"class C { public int this[int a, int b] { get { return 0; } } }"; var src2 = @"class C { public int this[int a, int x] { get { return 0; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@33 -> [int x]@33"); } [Fact] public void ParameterInsert1() { var src1 = @"class C { public void M() {} }"; var src2 = @"class C { public void M(int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a]@24"); } [Fact] public void ParameterInsert2() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int a, ref int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a)]@23 -> [(int a, ref int b)]@23", "Insert [ref int b]@31"); } [Fact] public void ParameterDelete1() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a]@24"); } [Fact] public void ParameterDelete2() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a, int b)]@23 -> [(int b)]@23", "Delete [int a]@24"); } [Fact] public void ParameterUpdate() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [int b]@24"); } [Fact] public void ParameterReorder() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b, int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int b]@31 -> @24"); } [Fact] public void ParameterReorderAndUpdate() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b, int c) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int b]@31 -> @24", "Update [int a]@24 -> [int c]@31"); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Parameter_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { static void M(" + oldType + " a) {} }"; var src2 = "class C { static void M(" + newType + " a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Parameter_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { static void M(" + oldType + " a) {} }"; var src2 = "class C { static void M(" + newType + " a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " a", FeaturesResources.parameter)); } [Fact] public void Parameter_Type_Nullable() { var src1 = @" #nullable enable class C { static void M(string a) { } } "; var src2 = @" #nullable disable class C { static void M(string a) { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Theory] [InlineData("this")] [InlineData("ref")] [InlineData("out")] [InlineData("params")] public void Parameter_Modifier_Remove(string modifier) { var src1 = @"static class C { static void F(" + modifier + " int[] a) { } }"; var src2 = @"static class C { static void F(int[] a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "int[] a", FeaturesResources.parameter)); } [Theory] [InlineData("int a = 1", "int a = 2")] [InlineData("int a = 1", "int a")] [InlineData("int a", "int a = 2")] [InlineData("object a = null", "object a")] [InlineData("object a", "object a = null")] [InlineData("double a = double.NaN", "double a = 1.2")] public void Parameter_Initializer_Update(string oldParameter, string newParameter) { var src1 = @"static class C { static void F(" + oldParameter + ") { } }"; var src2 = @"static class C { static void F(" + newParameter + ") { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, newParameter, FeaturesResources.parameter)); } [Fact] public void Parameter_Initializer_NaN() { var src1 = @"static class C { static void F(double a = System.Double.NaN) { } }"; var src2 = @"static class C { static void F(double a = double.NaN) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Parameter_Initializer_InsertDeleteUpdate() { var srcA1 = @"partial class C { }"; var srcB1 = @"partial class C { public static void F(int x = 1) {} }"; var srcA2 = @"partial class C { public static void F(int x = 2) {} }"; var srcB2 = @"partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults(), }); } [Fact] public void Parameter_Attribute_Insert() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@63 -> [[A]int a]@63"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_NonCustomAttribute() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M([System.Runtime.InteropServices.InAttribute]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [[System.Runtime.InteropServices.InAttribute]int a]@24"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute1() { var attribute = "public class AAttribute : System.Security.Permissions.SecurityAttribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@101 -> [[A]int a]@101"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute2() { var attribute = "public class BAttribute : System.Security.Permissions.SecurityAttribute { }\n\n" + "public class AAttribute : BAttribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@143 -> [[A]int a]@143"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@72 -> [[A]int a]@72"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([A]int a) {} }"; var src2 = attribute + @"class C { public void M([A, B]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]int a]@120 -> [[A, B]int a]@120"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Delete_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([A]int a) {} }"; var src2 = attribute + @"class C { public void M(int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]int a]@72 -> [int a]@72"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Update_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([System.Obsolete(""1""), B]int a) {} }"; var src2 = attribute + @"class C { public void M([System.Obsolete(""2""), A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]int a]@120 -> [[System.Obsolete(\"2\"), A]int a]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Update() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F([A(0)]int a) {} }"; var src2 = attribute + "class C { void F([A(1)]int a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(0)]int a]@67 -> [[A(1)]int a]@67"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Parameter_Attribute_Update_WithBodyUpdate() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F([A(0)]int a) { F(0); } }"; var src2 = attribute + "class C { void F([A(1)]int a) { F(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void F([A(0)]int a) { F(0); }]@60 -> [void F([A(1)]int a) { F(1); }]@60", "Update [[A(0)]int a]@67 -> [[A(1)]int a]@67"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Method Type Parameter [Fact] public void MethodTypeParameterInsert1() { var src1 = @"class C { public void M() {} }"; var src2 = @"class C { public void M<A>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@23", "Insert [A]@24"); } [Fact] public void MethodTypeParameterInsert2() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M<A,B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@23 -> [<A,B>]@23", "Insert [B]@26"); } [Fact] public void MethodTypeParameterDelete1() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@23", "Delete [A]@24"); } [Fact] public void MethodTypeParameterDelete2() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@23 -> [<B>]@23", "Delete [A]@24"); } [Fact] public void MethodTypeParameterUpdate() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M<B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [A]@24 -> [B]@24"); } [Fact] public void MethodTypeParameterReorder() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B,A>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@26 -> @24"); } [Fact] public void MethodTypeParameterReorderAndUpdate() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B,C>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@26 -> @24", "Update [A]@24 -> [C]@26"); } [Fact] public void MethodTypeParameter_Attribute_Insert1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<T>() {} }"; var src2 = attribute + @"class C { public void M<[A]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@72 -> [[A]T]@72"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T"), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method)); } [Fact] public void MethodTypeParameter_Attribute_Insert2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[A]T>() {} }"; var src2 = attribute + @"class C { public void M<[A, B]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@120 -> [[A, B]T]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T"), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method)); } [Fact] public void MethodTypeParameter_Attribute_Delete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[A]T>() {} }"; var src2 = attribute + @"class C { public void M<T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@72 -> [T]@72"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[System.Obsolete(""1""), B]T>() {} }"; var src2 = attribute + @"class C { public void M<[System.Obsolete(""2""), A]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]T]@120 -> [[System.Obsolete(\"2\"), A]T]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F<[A(0)]T>(T a) {} }"; var src2 = attribute + "class C { void F<[A(1)]T>(T a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(0)]T]@67 -> [[A(1)]T]@67"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update_WithBodyUpdate() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F<[A(0)]T>(T a) { F(0); } }"; var src2 = attribute + "class C { void F<[A(1)]T>(T a) { F(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void F<[A(0)]T>(T a) { F(0); }]@60 -> [void F<[A(1)]T>(T a) { F(1); }]@60", "Update [[A(0)]T]@67 -> [[A(1)]T]@67"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<[A(1)]T>(T a)"), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } #endregion #region Type Type Parameter [Fact] public void TypeTypeParameterInsert1() { var src1 = @"class C {}"; var src2 = @"class C<A> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@7", "Insert [A]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "A", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterInsert2() { var src1 = @"class C<A> {}"; var src2 = @"class C<A,B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@7 -> [<A,B>]@7", "Insert [B]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "B", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterDelete1() { var src1 = @"class C<A> { }"; var src2 = @"class C { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@7", "Delete [A]@8"); } [Fact] public void TypeTypeParameterDelete2() { var src1 = @"class C<A,B> {}"; var src2 = @"class C<B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@7 -> [<B>]@7", "Delete [A]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C<B>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "A"))); } [Fact] public void TypeTypeParameterUpdate() { var src1 = @"class C<A> {}"; var src2 = @"class C<B> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [A]@8 -> [B]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "B")); } [Fact] public void TypeTypeParameterReorder() { var src1 = @"class C<A,B> { }"; var src2 = @"class C<B,A> { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@10 -> @8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterReorderAndUpdate() { var src1 = @"class C<A,B> {}"; var src2 = @"class C<B,C> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@10 -> @8", "Update [A]@8 -> [C]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.Renamed, "C", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "C")); } [Fact] public void TypeTypeParameterAttributeInsert1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<T> {}"; var src2 = attribute + @"class C<[A]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@56 -> [[A]T]@56"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeInsert2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[A]T> {}"; var src2 = attribute + @"class C<[A, B]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@104 -> [[A, B]T]@104"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeInsert_SupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<T> {}"; var src2 = attribute + @"class C<[A]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@56 -> [[A]T]@56"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeDelete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[A]T> {}"; var src2 = attribute + @"class C<T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@56 -> [T]@56"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeUpdate() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[System.Obsolete(""1""), B]T> {}"; var src2 = attribute + @"class C<[System.Obsolete(""2""), A]T> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]T]@104 -> [[System.Obsolete(\"2\"), A]T]@104"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = "partial class C<T> { }" + attributes; var srcB1 = "partial class C<T> { }"; var srcA2 = "partial class C<[A]T> { }" + attributes; var srcB2 = "partial class C<[B]T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple_Reloadable() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<T> { }" + attributes; var srcB1 = "partial class C<T> { }"; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<[A]T> { }" + attributes; var srcB2 = "partial class C<[B]T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Type Parameter Constraints [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void TypeConstraint_Insert(string newConstraint) { var src1 = "class C<S,T> { }"; var src2 = "class C<S,T> where T : " + newConstraint + " { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [where T : " + newConstraint + "]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where T : " + newConstraint, FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : " + newConstraint)); } [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void TypeConstraint_Delete(string oldConstraint) { var src1 = "class C<S,T> where T : " + oldConstraint + " { }"; var src2 = "class C<S,T> { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [where T : " + oldConstraint + "]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Theory] [InlineData("string", "string?")] [InlineData("(int a, int b)", "(int a, int c)")] public void TypeConstraint_Update_RuntimeTypeUnchanged(string oldType, string newType) { // note: dynamic is not allowed in constraints var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">")); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void TypeConstraint_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where T : System.Collections.Generic.List<" + newType + ">", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">")); } [Fact] public void TypeConstraint_Delete_WithParameter() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<S> where S : new() { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C<S>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T"))); } [Fact] public void TypeConstraint_MultipleClauses_Insert() { var src1 = "class C<S,T> where T : class { }"; var src2 = "class C<S,T> where S : unmanaged where T : class { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [where S : unmanaged]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where S : unmanaged", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : unmanaged")); } [Fact] public void TypeConstraint_MultipleClauses_Delete() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<S,T> where T : class { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [where S : new()]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "S", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "S")); } [Fact] public void TypeConstraint_MultipleClauses_Reorder() { var src1 = "class C<S,T> where S : struct where T : class { }"; var src2 = "class C<S,T> where T : class where S : struct { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [where T : class]@30 -> @13"); edits.VerifyRudeDiagnostics(); } [Fact] public void TypeConstraint_MultipleClauses_UpdateAndReorder() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<T,S> where T : class, I where S : class, new() { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [where T : class]@29 -> @13", "Reorder [T]@10 -> @8", "Update [where T : class]@29 -> [where T : class, I]@13", "Update [where S : new()]@13 -> [where S : class, new()]@32"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.ChangingConstraints, "where T : class, I", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : class, I"), Diagnostic(RudeEditKind.ChangingConstraints, "where S : class, new()", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : class, new()")); } #endregion #region Top Level Statements [Fact] public void TopLevelStatements_Update() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_InsertAndUpdate() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello World""); Console.WriteLine(""What is your name?""); var name = Console.ReadLine(); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19", "Insert [Console.WriteLine(\"What is your name?\");]@54", "Insert [var name = Console.ReadLine();]@96"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Insert_NoImplicitMain() { var src1 = @" using System; "; var src2 = @" using System; Console.WriteLine(""Hello World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Insert_ImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello""); Console.WriteLine(""World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"World\");]@48"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Delete_NoImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello World""); "; var src2 = @" using System; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"Hello World\");]@19"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.global_statement)); } [Fact] public void TopLevelStatements_Delete_ImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello""); Console.WriteLine(""World""); "; var src2 = @" using System; Console.WriteLine(""Hello""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"World\");]@48"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_StackAlloc() { var src1 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(1); }"; var src2 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(2); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", CSharpFeaturesResources.global_statement)); } [Fact] public void TopLevelStatements_VoidToInt1() { var src1 = @" using System; Console.Write(1); "; var src2 = @" using System; Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToInt2() { var src1 = @" using System; Console.Write(1); return; "; var src2 = @" using System; Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToInt3() { var src1 = @" using System; Console.Write(1); int Goo() { return 1; } "; var src2 = @" using System; Console.Write(1); return 1; int Goo() { return 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_AddAwait() { var src1 = @" using System.Threading.Tasks; await Task.Delay(100); "; var src2 = @" using System.Threading.Tasks; await Task.Delay(100); await Task.Delay(200); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_DeleteAwait() { var src1 = @" using System.Threading.Tasks; await Task.Delay(100); await Task.Delay(200); "; var src2 = @" using System.Threading.Tasks; await Task.Delay(100); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_VoidToTask() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "await Task.Delay(100);")); } [Fact] public void TopLevelStatements_TaskToTaskInt() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToTaskInt() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); return await GetInt(); Task<int> GetInt() { return Task.FromResult(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return await GetInt();")); } [Fact] public void TopLevelStatements_IntToVoid1() { var src1 = @" using System; Console.Write(1); return 1; "; var src2 = @" using System; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_IntToVoid2() { var src1 = @" using System; Console.Write(1); return 1; "; var src2 = @" using System; Console.Write(1); return; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return;")); } [Fact] public void TopLevelStatements_IntToVoid3() { var src1 = @" using System; Console.Write(1); return 1; int Goo() { return 1; } "; var src2 = @" using System; Console.Write(1); int Goo() { return 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "int Goo()\r\n{\r\n return 1;\r\n}")); } [Fact] public void TopLevelStatements_IntToVoid4() { var src1 = @" using System; Console.Write(1); return 1; public class C { public int Goo() { return 1; } } "; var src2 = @" using System; Console.Write(1); public class C { public int Goo() { return 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_TaskToVoid() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"), Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_TaskIntToTask() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); return 1; "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_TaskIntToVoid() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); return await GetInt(); Task<int> GetInt() { return Task.FromResult(1); } "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"), Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_WithLambda_Insert() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_WithLambda_Update() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); public class C { } "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(2); public class C { } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_WithLambda_Delete() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); public class C { } "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; public class C { } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_UpdateMultiple() { var src1 = @" using System; Console.WriteLine(1); Console.WriteLine(2); public class C { } "; var src2 = @" using System; Console.WriteLine(3); Console.WriteLine(4); public class C { } "; var edits = GetTopEdits(src1, src2); // Since each individual statement is a separate update to a separate node, this just validates we correctly // only analyze the things once edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_MoveToOtherFile() { var srcA1 = @" using System; Console.WriteLine(1); public class A { }"; var srcB1 = @" using System; public class B { }"; var srcA2 = @" using System; public class A { }"; var srcB2 = @" using System; Console.WriteLine(2); public class B { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new [] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")) }), }); } #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.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class TopLevelEditingTests : EditingTestBase { #region Usings [Fact] public void Using_Global_Insert() { var src1 = @" using System.Collections.Generic; "; var src2 = @" global using D = System.Diagnostics; global using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [global using D = System.Diagnostics;]@2", "Insert [global using System.Collections;]@40"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Delete1() { var src1 = @" using System.Diagnostics; "; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [using System.Diagnostics;]@2"); Assert.IsType<UsingDirectiveSyntax>(edits.Edits.First().OldNode); Assert.Null(edits.Edits.First().NewNode); } [Fact] public void Using_Delete2() { var src1 = @" using D = System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [using D = System.Diagnostics;]@2", "Delete [using System.Collections;]@33"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Insert() { var src1 = @" using System.Collections.Generic; "; var src2 = @" using D = System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using D = System.Diagnostics;]@2", "Insert [using System.Collections;]@33"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update1() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Diagnostics; using X = System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using System.Collections;]@29 -> [using X = System.Collections;]@29"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update2() { var src1 = @" using System.Diagnostics; using X1 = System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Diagnostics; using X2 = System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using X1 = System.Collections;]@29 -> [using X2 = System.Collections;]@29"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Update3() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System; using System.Collections; using System.Collections.Generic; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [using System.Diagnostics;]@2 -> [using System;]@2"); edits.VerifyRudeDiagnostics(); } [Fact] public void Using_Reorder1() { var src1 = @" using System.Diagnostics; using System.Collections; using System.Collections.Generic; "; var src2 = @" using System.Collections; using System.Collections.Generic; using System.Diagnostics; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [using System.Diagnostics;]@2 -> @64"); } [Fact] public void Using_InsertDelete1() { var src1 = @" namespace N { using System.Collections; } namespace M { } "; var src2 = @" namespace N { } namespace M { using System.Collections; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using System.Collections;]@43", "Delete [using System.Collections;]@22"); } [Fact] public void Using_InsertDelete2() { var src1 = @" namespace N { using System.Collections; } "; var src2 = @" using System.Collections; namespace N { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [using System.Collections;]@2", "Delete [using System.Collections;]@22"); } [Fact] public void Using_Delete_ChangesCodeMeaning() { // This test specifically validates the scenario we _don't_ support, namely when inserting or deleting // a using directive, if existing code changes in meaning as a result, we don't issue edits for that code. // If this ever regresses then please buy a lottery ticket because the feature has magically fixed itself. var src1 = @" using System.IO; using DirectoryInfo = N.C; namespace N { public class C { public C(string a) { } public FileAttributes Attributes { get; set; } } public class D { public void M() { var d = new DirectoryInfo(""aa""); var x = directoryInfo.Attributes; } } }"; var src2 = @" using System.IO; namespace N { public class C { public C(string a) { } public FileAttributes Attributes { get; set; } } public class D { public void M() { var d = new DirectoryInfo(""aa""); var x = directoryInfo.Attributes; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [using DirectoryInfo = N.C;]@20"); edits.VerifySemantics(); } [Fact] public void Using_Insert_ForNewCode() { // As distinct from the above, this test validates a real world scenario of inserting a using directive // and changing code that utilizes the new directive to some effect. var src1 = @" namespace N { class Program { static void Main(string[] args) { } } }"; var src2 = @" using System; namespace N { class Program { static void Main(string[] args) { Console.WriteLine(""Hello World!""); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main"))); } [Fact] public void Using_Delete_ForOldCode() { var src1 = @" using System; namespace N { class Program { static void Main(string[] args) { Console.WriteLine(""Hello World!""); } } }"; var src2 = @" namespace N { class Program { static void Main(string[] args) { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.Program.Main"))); } [Fact] public void Using_Insert_CreatesAmbiguousCode() { // This test validates that we still issue edits for changed valid code, even when unchanged // code has ambiguities after adding a using. var src1 = @" using System.Threading; namespace N { class C { void M() { // Timer exists in System.Threading and System.Timers var t = new Timer(s => System.Console.WriteLine(s)); } } }"; var src2 = @" using System.Threading; using System.Timers; namespace N { class C { void M() { // Timer exists in System.Threading and System.Timers var t = new Timer(s => System.Console.WriteLine(s)); } void M2() { // TimersDescriptionAttribute only exists in System.Timers System.Console.WriteLine(new TimersDescriptionAttribute("""")); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("N.C.M2"))); } #endregion #region Extern Alias [Fact] public void ExternAliasUpdate() { var src1 = "extern alias X;"; var src2 = "extern alias Y;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [extern alias X;]@0 -> [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Update, "extern alias Y;", CSharpFeaturesResources.extern_alias)); } [Fact] public void ExternAliasInsert() { var src1 = ""; var src2 = "extern alias Y;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "extern alias Y;", CSharpFeaturesResources.extern_alias)); } [Fact] public void ExternAliasDelete() { var src1 = "extern alias Y;"; var src2 = ""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [extern alias Y;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.extern_alias)); } #endregion #region Assembly/Module Attributes [Fact] public void Insert_TopLevelAttribute() { var src1 = ""; var src2 = "[assembly: System.Obsolete(\"2\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [[assembly: System.Obsolete(\"2\")]]@0", "Insert [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "[assembly: System.Obsolete(\"2\")]", FeaturesResources.attribute)); } [Fact] public void Delete_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"2\")]"; var src2 = ""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [[assembly: System.Obsolete(\"2\")]]@0", "Delete [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, FeaturesResources.attribute)); } [Fact] public void Update_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"1\")]"; var src2 = "[assembly: System.Obsolete(\"2\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[assembly: System.Obsolete(\"1\")]]@0 -> [[assembly: System.Obsolete(\"2\")]]@0", "Update [System.Obsolete(\"1\")]@11 -> [System.Obsolete(\"2\")]@11"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Update, "System.Obsolete(\"2\")", FeaturesResources.attribute)); } [Fact] public void Reorder_TopLevelAttribute() { var src1 = "[assembly: System.Obsolete(\"1\")][assembly: System.Obsolete(\"2\")]"; var src2 = "[assembly: System.Obsolete(\"2\")][assembly: System.Obsolete(\"1\")]"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [[assembly: System.Obsolete(\"2\")]]@32 -> @0"); edits.VerifyRudeDiagnostics(); } #endregion #region Types [Theory] [InlineData("class", "struct")] [InlineData("class", "record")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874 [InlineData("class", "record struct")] [InlineData("class", "interface")] [InlineData("struct", "record struct")] // TODO: Allow this conversion: https://github.com/dotnet/roslyn/issues/51874 public void Type_Kind_Update(string oldKeyword, string newKeyword) { var src1 = oldKeyword + " C { }"; var src2 = newKeyword + " C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + oldKeyword + " C { }]@0 -> [" + newKeyword + " C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeKindUpdate, newKeyword + " C")); } [Theory] [InlineData("class", "struct")] [InlineData("class", "record")] [InlineData("class", "record struct")] [InlineData("class", "interface")] [InlineData("struct", "record struct")] public void Type_Kind_Update_Reloadable(string oldKeyword, string newKeyword) { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]" + newKeyword + " C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]" + oldKeyword + " C { }]@145 -> [[CreateNewOnMetadataUpdate]" + newKeyword + " C { }]@145"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Modifiers_Static_Remove() { var src1 = "public static class C { }"; var src2 = "public class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public static class C { }]@0 -> [public class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public class C", FeaturesResources.class_)); } [Theory] [InlineData("public")] [InlineData("protected")] [InlineData("private")] [InlineData("private protected")] [InlineData("internal protected")] public void Type_Modifiers_Accessibility_Change(string accessibility) { var src1 = accessibility + " class C { }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + accessibility + " class C { }]@0 -> [class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", FeaturesResources.class_)); } [Theory] [InlineData("public", "public")] [InlineData("internal", "internal")] [InlineData("", "internal")] [InlineData("internal", "")] [InlineData("protected", "protected")] [InlineData("private", "private")] [InlineData("private protected", "private protected")] [InlineData("internal protected", "internal protected")] public void Type_Modifiers_Accessibility_Partial(string accessibilityA, string accessibilityB) { var srcA1 = accessibilityA + " partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = accessibilityB + " partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(), }); } [Fact] public void Type_Modifiers_Internal_Remove() { var src1 = "internal interface C { }"; var src2 = "interface C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_Modifiers_Internal_Add() { var src1 = "struct C { }"; var src2 = "internal struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_Modifiers_Accessibility_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]public class C { }]@145 -> [[CreateNewOnMetadataUpdate]internal class C { }]@145"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPrivateInInterface_Remove(string keyword) { var src1 = "interface C { private " + keyword + " S { } }"; var src2 = "interface C { " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, keyword + " S", GetResource(keyword))); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPrivateInClass_Add(string keyword) { var src1 = "class C { " + keyword + " S { } }"; var src2 = "class C { private " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Modifiers_NestedPublicInInterface_Add(string keyword) { var src1 = "interface C { " + keyword + " S { } }"; var src2 = "interface C { public " + keyword + " S { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Add() { var src1 = "public class C { }"; var src2 = "public unsafe class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public class C { }]@0 -> [public unsafe class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_Remove() { var src1 = @" using System; unsafe delegate void D(); class C { unsafe class N { } public unsafe event Action<int> A { add { } remove { } } unsafe int F() => 0; unsafe int X; unsafe int Y { get; } unsafe C() {} unsafe ~C() {} } "; var src2 = @" using System; delegate void D(); class C { class N { } public event Action<int> A { add { } remove { } } int F() => 0; int X; int Y { get; } C() {} ~C() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [unsafe delegate void D();]@17 -> [delegate void D();]@17", "Update [unsafe class N { }]@60 -> [class N { }]@53", "Update [public unsafe event Action<int> A { add { } remove { } }]@84 -> [public event Action<int> A { add { } remove { } }]@70", "Update [unsafe int F() => 0;]@146 -> [int F() => 0;]@125", "Update [unsafe int X;]@172 -> [int X;]@144", "Update [unsafe int Y { get; }]@191 -> [int Y { get; }]@156", "Update [unsafe C() {}]@218 -> [C() {}]@176", "Update [unsafe ~C() {}]@237 -> [~C() {}]@188"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Type_Modifiers_Unsafe_DeleteInsert() { var srcA1 = "partial class C { unsafe void F() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }), }); } [Fact] public void Type_Modifiers_Ref_Add() { var src1 = "public struct C { }"; var src2 = "public ref struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public struct C { }]@0 -> [public ref struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public ref struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_Ref_Remove() { var src1 = "public ref struct C { }"; var src2 = "public struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public ref struct C { }]@0 -> [public struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_ReadOnly_Add() { var src1 = "public struct C { }"; var src2 = "public readonly struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public struct C { }]@0 -> [public readonly struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Modifiers_ReadOnly_Remove() { var src1 = "public readonly struct C { }"; var src2 = "public struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public readonly struct C { }]@0 -> [public struct C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public struct C", CSharpFeaturesResources.struct_)); } [Fact] public void Type_Attribute_Update_NotSupportedByRuntime1() { var attribute = "public class A1Attribute : System.Attribute { }\n\n" + "public class A2Attribute : System.Attribute { }\n\n"; var src1 = attribute + "[A1]class C { }"; var src2 = attribute + "[A2]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A1]class C { }]@98 -> [[A2]class C { }]@98"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Update_NotSupportedByRuntime2() { var src1 = "[System.Obsolete(\"1\")]class C { }"; var src2 = "[System.Obsolete(\"2\")]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\")]class C { }]@0 -> [[System.Obsolete(\"2\")]class C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Delete_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A, B]class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A, B]class C { }]@96 -> [[A]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Delete_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[B, A]class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[B, A]class C { }]@96 -> [[A]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Change_Reloadable() { var attributeSrc = @" public class A1 : System.Attribute { } public class A2 : System.Attribute { } public class A3 : System.Attribute { } "; var src1 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A1, A2]class C { }"; var src2 = ReloadableAttributeSrc + attributeSrc + "[CreateNewOnMetadataUpdate, A2, A3]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate, A1, A2]class C { }]@267 -> [[CreateNewOnMetadataUpdate, A2, A3]class C { }]@267"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_ReloadableRemove() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_ReloadableAdd() { var src1 = ReloadableAttributeSrc + "class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Attribute_ReloadableBase() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class B { } class C : B { void F() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Attribute_Add() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A]class C { }"; var src2 = attribute + "[A, B]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]class C { }]@96 -> [[A, B]class C { }]@96"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Attribute_Add_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[A]class C { }"; var src2 = attribute + "[A, B]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]class C { }]@96 -> [[A, B]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Add_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "class C { }"; var src2 = attribute + "[A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@48 -> [[A]class C { }]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Fact] public void Type_Attribute_Reorder1() { var src1 = "[A(1), B(2), C(3)]class C { }"; var src2 = "[C(3), A(1), B(2)]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(1), B(2), C(3)]class C { }]@0 -> [[C(3), A(1), B(2)]class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Attribute_Reorder2() { var src1 = "[A, B, C]class C { }"; var src2 = "[B, C, A]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A, B, C]class C { }]@0 -> [[B, C, A]class C { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Attribute_ReorderAndUpdate_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + "[System.Obsolete(\"1\"), A, B]class C { }"; var src2 = attribute + "[A, B, System.Obsolete(\"2\")]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), A, B]class C { }]@96 -> [[A, B, System.Obsolete(\"2\")]class C { }]@96"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", FeaturesResources.class_)); } [Theory] [InlineData("class")] [InlineData("struct")] [InlineData("interface")] [InlineData("record")] [InlineData("record struct")] public void Type_Rename(string keyword) { var src1 = keyword + " C { }"; var src2 = keyword + " D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [" + keyword + " C { }]@0 -> [" + keyword + " D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, keyword + " D", GetResource(keyword))); } [Fact] public void Type_Rename_AddAndDeleteMember() { var src1 = "class C { int x = 1; }"; var src2 = "class D { void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { int x = 1; }]@0 -> [class D { void F() { } }]@0", "Insert [void F() { }]@10", "Insert [()]@16", "Delete [int x = 1;]@10", "Delete [int x = 1]@10", "Delete [x = 1]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] [WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")] public void Type_Rename_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]class C { }]@145 -> [[CreateNewOnMetadataUpdate]class D { }]@145"); // TODO: expected: Replace edit of D edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] [WorkItem(54886, "https://github.com/dotnet/roslyn/issues/54886")] public void Type_Rename_Reloadable_AddAndDeleteMember() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { int x = 1; }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class D { void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[CreateNewOnMetadataUpdate]class C { int x = 1; }]@145 -> [[CreateNewOnMetadataUpdate]class D { void F() { } }]@145", "Insert [void F() { }]@182", "Insert [()]@188", "Delete [int x = 1;]@182", "Delete [int x = 1]@182", "Delete [x = 1]@186"); // TODO: expected: Replace edit of D edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Renamed, "class D", FeaturesResources.class_)); } [Fact] public void Interface_NoModifiers_Insert() { var src1 = ""; var src2 = "interface C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Interface_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { } "; var src2 = "namespace N { interface C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Interface_NoModifiers_IntoType_Insert() { var src1 = "interface N { }"; var src2 = "interface N { interface C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_Insert() { var src1 = ""; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { class C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Class_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { class C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_Insert() { var src1 = ""; var src2 = "struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { struct C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { struct C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_BaseType_Add_Unchanged() { var src1 = "class C { }"; var src2 = "class C : object { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : object { }]@0"); edits.VerifySemantics(); } [Fact] public void Type_BaseType_Add_Changed() { var src1 = "class C { }"; var src2 = "class C : D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Theory] [InlineData("string", "string?")] [InlineData("string[]", "string[]?")] [InlineData("object", "dynamic")] [InlineData("dynamic?", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Type_BaseType_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Type_BaseType_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_BaseType_Update_CompileTimeTypeUnchanged() { var src1 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<A> {}"; var src2 = "using A = System.Int32; using B = System.Int32; class C : System.Collections.Generic.List<B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_BaseInterface_Add() { var src1 = "class C { }"; var src2 = "class C : IDisposable { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C { }]@0 -> [class C : IDisposable { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_BaseInterface_Delete_Inherited() { var src1 = @" interface B {} interface A : B {} class C : A, B {} "; var src2 = @" interface B {} interface A : B {} class C : A {} "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void Type_BaseInterface_Reorder() { var src1 = "class C : IGoo, IBar { }"; var src2 = "class C : IBar, IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [class C : IGoo, IBar { }]@0 -> [class C : IBar, IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Type_BaseInterface_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Type_BaseInterface_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C : System.Collections.Generic.IEnumerable<" + oldType + "> {}"; var src2 = "class C : System.Collections.Generic.IEnumerable<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class C", FeaturesResources.class_)); } [Fact] public void Type_Base_Partial() { var srcA1 = "partial class C : B, I { }"; var srcB1 = "partial class C : J { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C : B, I, J { }"; var srcC = @" class B {} interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) }, new[] { DocumentResults(), DocumentResults(), DocumentResults() }); } [Fact] public void Type_Base_Partial_InsertDeleteAndUpdate() { var srcA1 = "partial class C { }"; var srcB1 = ""; var srcC1 = "partial class C { }"; var srcA2 = ""; var srcB2 = "partial class C : D { }"; var srcC2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "partial class C", FeaturesResources.class_) }), DocumentResults(), }); } [Fact] public void Type_Base_InsertDelete() { var srcA1 = ""; var srcB1 = "class C : B, I { }"; var srcA2 = "class C : B, I { }"; var srcB2 = ""; var srcC = @" class B {} interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC, srcC) }, new[] { DocumentResults(), DocumentResults(), DocumentResults() }); } [Fact] public void Type_Reloadable_NotSupportedByRuntime() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] public class C { void F() { System.Console.WriteLine(1); } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] public class C { void F() { System.Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, "void F()", "CreateNewOnMetadataUpdateAttribute")); } [Fact] public void Type_Insert_AbstractVirtualOverride() { var src1 = ""; var src2 = @" public abstract class C<T> { public abstract void F(); public virtual void G() {} public override string ToString() => null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Type_Insert_NotSupportedByRuntime() { var src1 = @" public class C { void F() { } }"; var src2 = @" public class C { void F() { } } public class D { void M() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "public class D", FeaturesResources.class_)); } [Fact] public void Type_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + ""; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"))); } [Fact] public void InterfaceInsert() { var src1 = ""; var src2 = @" public interface I { void F(); static void G() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void RefStructInsert() { var src1 = ""; var src2 = "ref struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref struct X { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_ReadOnly_Insert() { var src1 = ""; var src2 = "readonly struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [readonly struct X { }]@0"); edits.VerifyRudeDiagnostics(); } [Fact] public void Struct_RefModifier_Add() { var src1 = "struct X { }"; var src2 = "ref struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [struct X { }]@0 -> [ref struct X { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "ref struct X", CSharpFeaturesResources.struct_)); } [Fact] public void Struct_ReadonlyModifier_Add() { var src1 = "struct X { }"; var src2 = "readonly struct X { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [struct X { }]@0 -> [readonly struct X { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly struct X", SyntaxFacts.GetText(SyntaxKind.StructKeyword))); } [Theory] [InlineData("ref")] [InlineData("readonly")] public void Struct_Modifiers_Partial_InsertDelete(string modifier) { var srcA1 = modifier + " partial struct S { }"; var srcB1 = "partial struct S { }"; var srcA2 = "partial struct S { }"; var srcB2 = modifier + " partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults() }); } [Fact] public void Class_ImplementingInterface_Add() { var src1 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } "; var src2 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; }]@219", "Insert [public override string Get() => string.Empty;]@272", "Insert [string IConflict.Get() => String.Empty;]@325", "Insert [()]@298", "Insert [()]@345"); // Here we add a class implementing an interface and a method inside it with explicit interface specifier. // We want to be sure that adding the method will not tirgger a rude edit as it happens if adding a single method with explicit interface specifier. edits.VerifyRudeDiagnostics(); } [WorkItem(37128, "https://github.com/dotnet/roslyn/issues/37128")] [Fact] public void Interface_InsertMembers() { var src1 = @" using System; interface I { } "; var src2 = @" using System; interface I { static int StaticField = 10; static void StaticMethod() { } void VirtualMethod1() { } virtual void VirtualMethod2() { } abstract void AbstractMethod(); sealed void NonVirtualMethod() { } public static int operator +(I a, I b) => 1; static int StaticProperty1 { get => 1; set { } } static int StaticProperty2 => 1; virtual int VirtualProperty1 { get => 1; set { } } virtual int VirtualProperty2 { get => 1; } int VirtualProperty3 { get => 1; set { } } int VirtualProperty4 { get => 1; } abstract int AbstractProperty1 { get; set; } abstract int AbstractProperty2 { get; } sealed int NonVirtualProperty => 1; int this[byte virtualIndexer] => 1; int this[sbyte virtualIndexer] { get => 1; } virtual int this[ushort virtualIndexer] { get => 1; set {} } virtual int this[short virtualIndexer] { get => 1; set {} } abstract int this[uint abstractIndexer] { get; set; } abstract int this[int abstractIndexer] { get; } sealed int this[ulong nonVirtualIndexer] { get => 1; set {} } sealed int this[long nonVirtualIndexer] { get => 1; set {} } static event Action StaticEvent; static event Action StaticEvent2 { add { } remove { } } event Action VirtualEvent { add { } remove { } } abstract event Action AbstractEvent; sealed event Action NonVirtualEvent { add { } remove { } } abstract class C { } interface J { } enum E { } delegate void D(); } "; var edits = GetTopEdits(src1, src2); // TODO: InsertIntoInterface errors are reported due to https://github.com/dotnet/roslyn/issues/37128. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoInterface, "static void StaticMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "void VirtualMethod1()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "virtual void VirtualMethod2()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertVirtual, "abstract void AbstractMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed void NonVirtualMethod()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertOperator, "public static int operator +(I a, I b)", FeaturesResources.operator_), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "static int StaticProperty2", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "virtual int VirtualProperty2", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty3", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "int VirtualProperty4", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty1", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int AbstractProperty2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int NonVirtualProperty", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "int this[byte virtualIndexer]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.InsertVirtual, "int this[sbyte virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[ushort virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "virtual int this[short virtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[uint abstractIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertVirtual, "abstract int this[int abstractIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[ulong nonVirtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed int this[long nonVirtualIndexer]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoInterface, "static event Action StaticEvent2", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertVirtual, "event Action VirtualEvent", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoInterface, "sealed event Action NonVirtualEvent", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoInterface, "StaticField = 10", FeaturesResources.field), Diagnostic(RudeEditKind.InsertIntoInterface, "StaticEvent", CSharpFeaturesResources.event_field), Diagnostic(RudeEditKind.InsertVirtual, "AbstractEvent", CSharpFeaturesResources.event_field)); } [Fact] public void Interface_InsertDelete() { var srcA1 = @" interface I { static void M() { } } "; var srcB1 = @" "; var srcA2 = @" "; var srcB2 = @" interface I { static void M() { } } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("M")) }), }); } [Fact] public void Type_Generic_InsertMembers() { var src1 = @" using System; class C<T> { } "; var src2 = @" using System; class C<T> { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1, F2; enum E {} interface I {} class D {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "void M()", FeaturesResources.method), Diagnostic(RudeEditKind.InsertIntoGenericType, "int P1", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoGenericType, "int P2", FeaturesResources.auto_property), Diagnostic(RudeEditKind.InsertIntoGenericType, "int this[int i]", FeaturesResources.indexer_), Diagnostic(RudeEditKind.InsertIntoGenericType, "event Action E", FeaturesResources.event_), Diagnostic(RudeEditKind.InsertIntoGenericType, "EF", CSharpFeaturesResources.event_field), Diagnostic(RudeEditKind.InsertIntoGenericType, "F1", FeaturesResources.field), Diagnostic(RudeEditKind.InsertIntoGenericType, "F2", FeaturesResources.field)); } [Fact] public void Type_Generic_InsertMembers_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { } "; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C<T> { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } event System.Action E { add {} remove {} } event System.Action EF; int F1, F2; enum E {} interface I {} class D {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Generic_DeleteInsert() { var srcA1 = @" class C<T> { void F() {} } struct S<T> { void F() {} } interface I<T> { void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "struct S<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "interface I<T>"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }) }); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")] [WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")] public void Type_TypeParameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public class C<T> { void F() { } }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal class C<T, S> { int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Type_Delete() { var src1 = @" class C { void F() {} } struct S { void F() {} } interface I { void F() {} } "; var src2 = ""; GetTopEdits(src1, src2).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(CSharpFeaturesResources.struct_, "S")), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.interface_, "I"))); } [Fact] public void Type_Delete_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var src2 = ReloadableAttributeSrc; GetTopEdits(src1, src2).VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C"))); } [Fact] public void Type_Partial_DeleteDeclaration() { var srcA1 = "partial class C { void F() {} void M() { } }"; var srcB1 = "partial class C { void G() {} }"; var srcA2 = ""; var srcB2 = "partial class C { void G() {} void M() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.method, "C.F()")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("M")), }) }); } [Fact] public void Type_Partial_InsertFirstDeclaration() { var src1 = ""; var src2 = "partial class C { void F() {} }"; GetTopEdits(src1, src2).VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C"), preserveLocalVariables: false) }); } [Fact] public void Type_Partial_InsertSecondDeclaration() { var srcA1 = "partial class C { void F() {} }"; var srcB1 = ""; var srcA2 = "partial class C { void F() {} }"; var srcB2 = "partial class C { void G() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G"), preserveLocalVariables: false) }), }); } [Fact] public void Type_Partial_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; var srcB1 = ""; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { void F() {} }"; var srcB2 = "partial class C { void G() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } [Fact] public void Type_DeleteInsert() { var srcA1 = @" class C { void F() {} } struct S { void F() {} } interface I { void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }); } [Fact] public void Type_DeleteInsert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { void F() {} }"; var srcB1 = ""; var srcA2 = ReloadableAttributeSrc; var srcB2 = "[CreateNewOnMetadataUpdate]class C { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C")), }) }); } [Fact] public void Type_NonInsertableMembers_DeleteInsert() { var srcA1 = @" abstract class C { public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { void G(); void F() {} } "; var srcB1 = ""; var srcA2 = srcB1; var srcB2 = srcA1; // TODO: The methods without bodies do not need to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }); } [Fact] public void Type_Attribute_NonInsertableMembers_DeleteInsert() { var srcA1 = @" abstract class C { public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { void G(); void F() {} } "; var srcB1 = ""; var srcA2 = ""; var srcB2 = @" abstract class C { [System.Obsolete]public abstract void AbstractMethod(); public virtual void VirtualMethod() {} public override string ToString() => null; public void I.G() {} } interface I { [System.Obsolete]void G(); void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("AbstractMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("VirtualMethod")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("ToString")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("I.G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("G")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember("F")), }) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_DeleteInsert_DataMembers() { var srcA1 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; public event System.Action E = new System.Action(null); } "; var srcB1 = ""; var srcA2 = ""; var srcB2 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; public event System.Action E = new System.Action(null); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true), }) }); } [Fact] public void Type_DeleteInsert_DataMembers_PartialSplit() { var srcA1 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; } "; var srcB1 = ""; var srcA2 = @" partial class C { public int x = 1; public int y = 2; } "; var srcB2 = @" partial class C { public int P { get; set; } = 3; } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true), }) }); } [Fact] public void Type_DeleteInsert_DataMembers_PartialMerge() { var srcA1 = @" partial class C { public int x = 1; public int y = 2; } "; var srcB1 = @" partial class C { public int P { get; set; } = 3; }"; var srcA2 = @" class C { public int x = 1; public int y = 2; public int P { get; set; } = 3; } "; var srcB2 = @" "; // note that accessors are not updated since they do not have bodies EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true), }), DocumentResults() }); } #endregion #region Records [Fact] public void Record_Partial_MovePrimaryConstructor() { var src1 = @" partial record C { } partial record C(int X);"; var src2 = @" partial record C(int X); partial record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_Name_Update() { var src1 = "record C { }"; var src2 = "record D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "record D", CSharpFeaturesResources.record_)); } [Fact] public void RecordStruct_NoModifiers_Insert() { var src1 = ""; var src2 = "record struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_AddField() { var src1 = @" record struct C(int X) { }"; var src2 = @" record struct C(int X) { private int _y = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "_y = 0", FeaturesResources.field, CSharpFeaturesResources.record_struct)); } [Fact] public void RecordStruct_AddProperty() { var src1 = @" record struct C(int X) { }"; var src2 = @" record struct C(int X) { public int Y { get; set; } = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "public int Y { get; set; } = 0;", FeaturesResources.auto_property, CSharpFeaturesResources.record_struct)); } [Fact] public void Record_NoModifiers_Insert() { var src1 = ""; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { record C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { record C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_BaseTypeUpdate1() { var src1 = "record C { }"; var src2 = "record C : D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record C : D { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseTypeUpdate2() { var src1 = "record C : D1 { }"; var src2 = "record C : D2 { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : D1 { }]@0 -> [record C : D2 { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate1() { var src1 = "record C { }"; var src2 = "record C : IDisposable { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C { }]@0 -> [record C : IDisposable { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate2() { var src1 = "record C : IGoo, IBar { }"; var src2 = "record C : IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : IGoo, IBar { }]@0 -> [record C : IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void Record_BaseInterfaceUpdate3() { var src1 = "record C : IGoo, IBar { }"; var src2 = "record C : IBar, IGoo { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [record C : IGoo, IBar { }]@0 -> [record C : IBar, IGoo { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "record C", CSharpFeaturesResources.record_)); } [Fact] public void RecordInsert_AbstractVirtualOverride() { var src1 = ""; var src2 = @" public abstract record C<T> { public abstract void F(); public virtual void G() {} public override void H() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_ParameterlessConstructor() { var src1 = "record C { }"; var src2 = @" record C { public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_ImplementSynthesized_ParameterlessConstructor() { var src1 = "record struct C { }"; var src2 = @" record struct C { public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_PrintMembers() { var src1 = "record C { }"; var src2 = @" record C { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return true; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers"))); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_ImplementSynthesized_PrintMembers() { var src1 = "record struct C { }"; var src2 = @" record struct C { private readonly bool PrintMembers(System.Text.StringBuilder builder) { return true; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_WrongParameterName() { var src1 = "record C { }"; var src2 = @" record C { protected virtual bool PrintMembers(System.Text.StringBuilder sb) { return false; } public virtual bool Equals(C rhs) { return false; } protected C(C other) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected virtual bool PrintMembers(System.Text.StringBuilder sb)", "PrintMembers(System.Text.StringBuilder builder)"), Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "public virtual bool Equals(C rhs)", "Equals(C other)"), Diagnostic(RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, "protected C(C other)", "C(C original)")); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.FirstOrDefault()?.Type.ToDisplayString() == "C"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Length == 0), preserveLocalVariables: true), }, EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Record_ImplementSynthesized_ToString() { var src1 = "record C { }"; var src2 = @" record C { public override string ToString() { return ""R""; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_ToString() { var src1 = @" record C { public override string ToString() { return ""R""; } }"; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.ToString"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_Primary() { var src1 = "record C(int X);"; var src2 = "record C(int X, int Y);"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int Y", FeaturesResources.parameter)); } [Fact] public void Record_UnimplementSynthesized_ParameterlessConstructor() { var src1 = @" record C { public C() { } }"; var src2 = "record C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void RecordStruct_UnimplementSynthesized_ParameterlessConstructor() { var src1 = @" record struct C { public C() { } }"; var src2 = "record struct C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.First(c => c.ToString() == "C.C()"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int Y { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithConstructor() { var src1 = @" record C(int X) { public C(string fromAString) { } }"; var src2 = @" record C(int X) { public int Y { get; set; } public C(string fromAString) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithExplicitMembers() { var src1 = @" record C(int X) { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return false; } public override int GetHashCode() { return 0; } public virtual bool Equals(C other) { return false; } public C(C original) { } }"; var src2 = @" record C(int X) { public int Y { get; set; } protected virtual bool PrintMembers(System.Text.StringBuilder builder) { return false; } public override int GetHashCode() { return 0; } public virtual bool Equals(C other) { return false; } public C(C original) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddProperty_NotPrimary_WithInitializer() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int Y { get; set; } = 1; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.Y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField() { var src1 = "record C(int X) { }"; var src2 = "record C(int X) { private int _y; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithExplicitMembers() { var src1 = @" record C(int X) { public C(C other) { } }"; var src2 = @" record C(int X) { private int _y; public C(C other) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithInitializer() { var src1 = "record C(int X) { }"; var src2 = "record C(int X) { private int _y = 1; }"; var syntaxMap = GetSyntaxMap(src1, src2); var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._y")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithExistingInitializer() { var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }"; var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_AddField_WithInitializerAndExistingInitializer() { var src1 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; }"; var src2 = "record C(int X) { private int _y = <N:0.0>1</N:0.0>; private int _z = 1; }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C._z")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_DeleteField() { var src1 = "record C(int X) { private int _y; }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.field, "_y"))); } [Fact] public void Record_DeleteProperty_Primary() { var src1 = "record C(int X, int Y) { }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.parameter, "int Y"))); } [Fact] public void Record_DeleteProperty_NotPrimary() { var src1 = "record C(int X) { public int P { get; set; } }"; var src2 = "record C(int X) { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "P"))); } [Fact] public void Record_ImplementSynthesized_Property() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; init; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_WithBody() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get { return 4; } init { throw null; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_WithExpressionBody() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get => 4; init => throw null; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_InitToSet() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ImplementRecordParameterWithSet, "public int X", "X")); } [Fact] public void Record_ImplementSynthesized_Property_MakeReadOnly() { var src1 = "record C(int X);"; var src2 = @" record C(int X) { public int X { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ImplementRecordParameterAsReadOnly, "public int X", "X")); } [Fact] public void Record_UnImplementSynthesized_Property() { var src1 = @" record C(int X) { public int X { get; init; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithExpressionBody() { var src1 = @" record C(int X) { public int X { get => 4; init => throw null; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithBody() { var src1 = @" record C(int X) { public int X { get { return 4; } init { } } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C"))); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_ImplementSynthesized_Property_Partial() { var srcA1 = @"partial record C(int X);"; var srcB1 = @"partial record C;"; var srcA2 = @"partial record C(int X);"; var srcB2 = @" partial record C { public int X { get; init; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void Record_UnImplementSynthesized_Property_Partial() { var srcA1 = @"partial record C(int X);"; var srcB1 = @" partial record C { public int X { get; init; } }"; var srcA2 = @"partial record C(int X);"; var srcB2 = @"partial record C;"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void Record_ImplementSynthesized_Property_Partial_WithBody() { var srcA1 = @"partial record C(int X);"; var srcB1 = @"partial record C;"; var srcA2 = @"partial record C(int X);"; var srcB2 = @" partial record C { public int X { get { return 4; } init { throw null; } } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")) }) }); } [Fact] public void Record_UnImplementSynthesized_Property_Partial_WithBody() { var srcA1 = @"partial record C(int X);"; var srcB1 = @" partial record C { public int X { get { return 4; } init { throw null; } } }"; var srcA2 = @"partial record C(int X);"; var srcB2 = @"partial record C;"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.PrintMembers")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("Equals").OfType<IMethodSymbol>().First(m => SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType))), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.GetHashCode")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.X").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), partialType : "C", preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "C")) }) }); } [Fact] public void Record_MoveProperty_Partial() { var srcA1 = @" partial record C(int X) { public int Y { get; init; } }"; var srcB1 = @" partial record C; "; var srcA2 = @" partial record C(int X); "; var srcB2 = @" partial record C { public int Y { get; init; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.Y").SetMethod) }), }); } [Fact] public void Record_UnImplementSynthesized_Property_WithInitializer() { var src1 = @" record C(int X) { public int X { get; init; } = 1; }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_UnImplementSynthesized_Property_WithInitializerMatchingCompilerGenerated() { var src1 = @" record C(int X) { public int X { get; init; } = X; }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); edits.VerifyRudeDiagnostics(); } [Fact] public void Record_Property_Delete_NotPrimary() { var src1 = @" record C(int X) { public int Y { get; init; } }"; var src2 = "record C(int X);"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "record C", DeletedSymbolDisplay(FeaturesResources.auto_property, "Y"))); } [Fact] public void Record_PropertyInitializer_Update_NotPrimary() { var src1 = "record C { int X { get; } = 0; }"; var src2 = "record C { int X { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Length == 0), preserveLocalVariables: true)); } [Fact] public void Record_PropertyInitializer_Update_Primary() { var src1 = "record C(int X) { int X { get; } = 0; }"; var src2 = "record C(int X) { int X { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters[0].Type.ToDisplayString() == "int"), preserveLocalVariables: true)); } #endregion #region Enums [Fact] public void Enum_NoModifiers_Insert() { var src1 = ""; var src2 = "enum C { A }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { enum C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_NoModifiers_IntoType_Insert() { var src1 = "struct N { }"; var src2 = "struct N { enum C { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Enum_Attribute_Insert() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { }"; var src2 = attribute + "[A]enum E { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum E { }]@48 -> [[A]enum E { }]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "enum E", FeaturesResources.enum_)); } [Fact] public void Enum_Member_Attribute_Delete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { [A]X }"; var src2 = attribute + "enum E { X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]X]@57 -> [X]@57"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_Insert() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { X }"; var src2 = attribute + "enum E { [A]X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [X]@57 -> [[A]X]@57"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A]X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_Update() { var attribute = "public class A1Attribute : System.Attribute { }\n\n" + "public class A2Attribute : System.Attribute { }\n\n"; var src1 = attribute + "enum E { [A1]X }"; var src2 = attribute + "enum E { [A2]X }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A1]X]@107 -> [[A2]X]@107"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "[A2]X", FeaturesResources.enum_value)); } [Fact] public void Enum_Member_Attribute_InsertDeleteAndUpdate() { var srcA1 = ""; var srcB1 = "enum N { A = 1 }"; var srcA2 = "enum N { [System.Obsolete]A = 1 }"; var srcB2 = ""; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("N.A")) }), DocumentResults() }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Enum_Rename() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Colors { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Colors { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "enum Colors", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Add() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color : ushort { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : ushort { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Add_Unchanged() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color : int { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color : int { Red = 1, Blue = 2, }]@0"); edits.VerifySemantics(); } [Fact] public void Enum_BaseType_Update() { var src1 = "enum Color : ushort { Red = 1, Blue = 2, }"; var src2 = "enum Color : long { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color : long { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void Enum_BaseType_Delete_Unchanged() { var src1 = "enum Color : int { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : int { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifySemantics(); } [Fact] public void Enum_BaseType_Delete_Changed() { var src1 = "enum Color : ushort { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color : ushort { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum Color", FeaturesResources.enum_)); } [Fact] public void EnumAccessibilityChange() { var src1 = "public enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public enum Color { Red = 1, Blue = 2, }]@0 -> [enum Color { Red = 1, Blue = 2, }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "enum Color", FeaturesResources.enum_)); } [Fact] public void EnumAccessibilityNoChange() { var src1 = "internal enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 2, }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Fact] public void EnumInitializerUpdate() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1, Blue = 3, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Blue = 2]@22 -> [Blue = 3]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 3", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate2() { var src1 = "enum Color { Red = 1, Blue = 2, }"; var src2 = "enum Color { Red = 1 << 0, Blue = 2 << 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = 1]@13 -> [Red = 1 << 0]@13", "Update [Blue = 2]@22 -> [Blue = 2 << 1]@27"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Blue = 2 << 1", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate3() { var src1 = "enum Color { Red = int.MinValue }"; var src2 = "enum Color { Red = int.MaxValue }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = int.MinValue]@13 -> [Red = int.MaxValue]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red = int.MaxValue", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerUpdate_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 1 }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]enum Color { Red = 2 }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Red = 1]@185 -> [Red = 2]@185"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("Color"))); } [Fact] public void EnumInitializerAdd() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red = 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red]@13 -> [Red = 1]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red = 1", FeaturesResources.enum_value)); } [Fact] public void EnumInitializerDelete() { var src1 = "enum Color { Red = 1, }"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red = 1]@13 -> [Red]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "Red", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberAdd() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Red, Blue}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red }]@0 -> [enum Color { Red, Blue}]@0", "Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [Fact] public void EnumMemberAdd2() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red, Blue}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberAdd3() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red, Blue,}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red, Blue,}]@0", "Insert [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "Blue", FeaturesResources.enum_value)); } [Fact] public void EnumMemberUpdate() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Orange }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Red]@13 -> [Orange]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "Orange", FeaturesResources.enum_value)); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916")] [Fact] public void EnumMemberDelete() { var src1 = "enum Color { Red, Blue}"; var src2 = "enum Color { Red }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red, Blue}]@0 -> [enum Color { Red }]@0", "Delete [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue"))); } [Fact] public void EnumMemberDelete2() { var src1 = "enum Color { Red, Blue}"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Blue]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "enum Color", DeletedSymbolDisplay(FeaturesResources.enum_value, "Blue"))); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaAdd() { var src1 = "enum Color { Red }"; var src2 = "enum Color { Red, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red }]@0 -> [enum Color { Red, }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaAdd_WithInitializer() { var src1 = "enum Color { Red = 1 }"; var src2 = "enum Color { Red = 1, }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum Color { Red = 1 }]@0 -> [enum Color { Red = 1, }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaDelete() { var src1 = "enum Color { Red, }"; var src2 = "enum Color { Red }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red, }]@0 -> [enum Color { Red }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } [WorkItem(754916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754916"), WorkItem(793197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/793197")] [Fact] public void EnumTrailingCommaDelete_WithInitializer() { var src1 = "enum Color { Red = 1, }"; var src2 = "enum Color { Red = 1 }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [enum Color { Red = 1, }]@0 -> [enum Color { Red = 1 }]@0"); edits.VerifySemantics(ActiveStatementsDescription.Empty, NoSemanticEdits); } #endregion #region Delegates [Fact] public void Delegates_NoModifiers_Insert() { var src1 = ""; var src2 = "delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_NoModifiers_IntoNamespace_Insert() { var src1 = "namespace N { }"; var src2 = "namespace N { delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_NoModifiers_IntoType_Insert() { var src1 = "class C { }"; var src2 = "class C { delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Public_IntoType_Insert() { var src1 = "class C { }"; var src2 = "class C { public delegate void D(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate void D();]@10", "Insert [()]@32"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Generic_Insert() { var src1 = "class C { }"; var src2 = "class C { private delegate void D<T>(T a); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private delegate void D<T>(T a);]@10", "Insert [<T>]@33", "Insert [(T a)]@36", "Insert [T]@34", "Insert [T a]@37"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_Delete() { var src1 = "class C { private delegate void D(); }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [private delegate void D();]@10", "Delete [()]@33"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.delegate_, "D"))); } [Fact] public void Delegates_Rename() { var src1 = "public delegate void D();"; var src2 = "public delegate void Z();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void D();]@0 -> [public delegate void Z();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "public delegate void Z()", FeaturesResources.delegate_)); } [Fact] public void Delegates_Accessibility_Update() { var src1 = "public delegate void D();"; var src2 = "private delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate void D();]@0 -> [private delegate void D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "private delegate void D()", FeaturesResources.delegate_)); } [Fact] public void Delegates_ReturnType_Update() { var src1 = "public delegate int D();"; var src2 = "public delegate void D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D();]@0 -> [public delegate void D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "public delegate void D()", FeaturesResources.delegate_)); } [Fact] public void Delegates_ReturnType_AddAttribute() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[return: A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@39 -> [[return: A]public delegate int D(int a);]@39"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Parameter_Insert() { var src1 = "public delegate int D();"; var src2 = "public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D();"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D"))); } [Fact] public void Delegates_Parameter_Delete() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.parameter, "int a"))); } [Fact] public void Delegates_Parameter_Rename() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D(int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@22 -> [int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "int b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Parameter_Update() { var src1 = "public delegate int D(int a);"; var src2 = "public delegate int D(byte a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@22 -> [byte a]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "byte a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_AddAttribute_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "public delegate int D([A]int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@70 -> [[A]int a]@70"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Delegates_Parameter_AddAttribute() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "public delegate int D([A]int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@61 -> [[A]int a]@61"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_TypeParameter_Insert() { var src1 = "public delegate int D();"; var src2 = "public delegate int D<T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<T>]@21", "Insert [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "T", FeaturesResources.type_parameter)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/54881")] [WorkItem(54881, "https://github.com/dotnet/roslyn/issues/54881")] public void Delegates_TypeParameter_Insert_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]public delegate int D<out T>();"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]internal delegate bool D<in T, out S>(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("D"))); } [Fact] public void Delegates_TypeParameter_Delete() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<T>]@21", "Delete [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public delegate int D()", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T"))); } [Fact] public void Delegates_TypeParameter_Rename() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D<S>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@22 -> [S]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "S", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "S")); } [Fact] public void Delegates_TypeParameter_Variance1() { var src1 = "public delegate int D<T>();"; var src2 = "public delegate int D<in T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@22 -> [in T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_Variance2() { var src1 = "public delegate int D<out T>();"; var src2 = "public delegate int D<T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [out T]@22 -> [T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_Variance3() { var src1 = "public delegate int D<out T>();"; var src2 = "public delegate int D<in T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [out T]@22 -> [in T]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.VarianceUpdate, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_TypeParameter_AddAttribute() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D<T>();"; var src2 = attribute + "public delegate int D<[A]T>();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@70 -> [[A]T]@70"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void Delegates_Attribute_Add_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public delegate int D(int a)", FeaturesResources.delegate_)); } [Fact] public void Delegates_Attribute_Add() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[A]public delegate int D(int a);]@48"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_Attribute_Add_WithReturnTypeAttribute() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + "public delegate int D(int a);"; var src2 = attribute + "[return: A][A]public delegate int D(int a);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D(int a);]@48 -> [[return: A][A]public delegate int D(int a);]@48"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.Invoke")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("D.BeginInvoke")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Delegates_ReadOnlyRef_Parameter_InsertWhole() { var src1 = ""; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate int D(in int b);]@0", "Insert [(in int b)]@21", "Insert [in int b]@22"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "public delegate int D();"; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Delegates_ReadOnlyRef_Parameter_Update() { var src1 = "public delegate int D(int b);"; var src2 = "public delegate int D(in int b);"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@22 -> [in int b]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } [Fact] public void Delegates_ReadOnlyRef_ReturnType_Insert() { var src1 = ""; var src2 = "public delegate ref readonly int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public delegate ref readonly int D();]@0", "Insert [()]@34"); edits.VerifyRudeDiagnostics(); } [Fact] public void Delegates_ReadOnlyRef_ReturnType_Update() { var src1 = "public delegate int D();"; var src2 = "public delegate ref readonly int D();"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public delegate int D();]@0 -> [public delegate ref readonly int D();]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "public delegate ref readonly int D()", FeaturesResources.delegate_)); } #endregion #region Nested Types [Fact] public void NestedClass_ClassMove1() { var src1 = @"class C { class D { } }"; var src2 = @"class C { } class D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [class D { }]@10 -> @12"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_)); } [Fact] public void NestedClass_ClassMove2() { var src1 = @"class C { class D { } class E { } class F { } }"; var src2 = @"class C { class D { } class F { } } class E { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [class E { }]@23 -> @37"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class E", FeaturesResources.class_)); } [Fact] public void NestedClass_ClassInsertMove1() { var src1 = @"class C { class D { } }"; var src2 = @"class C { class E { class D { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [class E { class D { } }]@10", "Move [class D { }]@10 -> @20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "class D", FeaturesResources.class_)); } [Fact] public void NestedClass_Insert1() { var src1 = @"class C { }"; var src2 = @"class C { class D { class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [class D { class E { } }]@10", "Insert [class E { }]@20"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert2() { var src1 = @"class C { }"; var src2 = @"class C { protected class D { public class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [protected class D { public class E { } }]@10", "Insert [public class E { }]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert3() { var src1 = @"class C { }"; var src2 = @"class C { private class D { public class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public class E { } }]@10", "Insert [public class E { }]@28"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert4() { var src1 = @"class C { }"; var src2 = @"class C { private class D { public D(int a, int b) { } public int P { get; set; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public D(int a, int b) { } public int P { get; set; } }]@10", "Insert [public D(int a, int b) { }]@28", "Insert [public int P { get; set; }]@55", "Insert [(int a, int b)]@36", "Insert [{ get; set; }]@68", "Insert [int a]@37", "Insert [int b]@44", "Insert [get;]@70", "Insert [set;]@75"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable1() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable2() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable3() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void NestedClass_Insert_ReloadableIntoReloadable4() { var src1 = ReloadableAttributeSrc + "class C { }"; var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { [CreateNewOnMetadataUpdate]class E { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"))); } [Fact] public void NestedClass_Insert_Member_Reloadable() { var src1 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { } }"; var src2 = ReloadableAttributeSrc + "class C { [CreateNewOnMetadataUpdate]class D { int x; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C.D"))); } [Fact] public void NestedClass_InsertMemberWithInitializer1() { var src1 = @" class C { }"; var src2 = @" class C { private class D { public int P = 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.D"), preserveLocalVariables: false) }); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void NestedClass_Insert_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { abstract class D { public extern D(); public static extern int P { [DllImport(""msvcrt.dll"")]get; [DllImport(""msvcrt.dll"")]set; } [DllImport(""msvcrt.dll"")] public static extern int puts(string c); [DllImport(""msvcrt.dll"")] public static extern int operator +(D d, D g); [DllImport(""msvcrt.dll"")] public static extern explicit operator int (D d); } } "; var edits = GetTopEdits(src1, src2); // Adding P/Invoke is not supported by the CLR. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "public extern D()", FeaturesResources.constructor), Diagnostic(RudeEditKind.InsertExtern, "public static extern int P", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "public static extern int puts(string c)", FeaturesResources.method), Diagnostic(RudeEditKind.InsertExtern, "public static extern int operator +(D d, D g)", FeaturesResources.operator_), Diagnostic(RudeEditKind.InsertExtern, "public static extern explicit operator int (D d)", CSharpFeaturesResources.conversion_operator)); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void NestedClass_Insert_VirtualAbstract() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { abstract class D { public abstract int P { get; } public abstract int this[int i] { get; } public abstract int puts(string c); public virtual event Action E { add { } remove { } } public virtual int Q { get { return 1; } } public virtual int this[string i] { get { return 1; } } public virtual int M(string c) { return 1; } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_TypeReorder1() { var src1 = @"class C { struct E { } class F { } delegate void D(); interface I {} }"; var src2 = @"class C { class F { } interface I {} delegate void D(); struct E { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [struct E { }]@10 -> @56", "Reorder [interface I {}]@54 -> @22"); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedClass_MethodDeleteInsert() { var src1 = @"public class C { public void goo() {} }"; var src2 = @"public class C { private class D { public void goo() {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [private class D { public void goo() {} }]@17", "Insert [public void goo() {}]@35", "Insert [()]@50", "Delete [public void goo() {}]@17", "Delete [()]@32"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "public class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [Fact] public void NestedClass_ClassDeleteInsert() { var src1 = @"public class C { public class X {} }"; var src2 = @"public class C { public class D { public class X {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public class D { public class X {} }]@17", "Move [public class X {}]@17 -> @34"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "public class X", FeaturesResources.class_)); } /// <summary> /// A new generic type can be added whether it's nested and inherits generic parameters from the containing type, or top-level. /// </summary> [Fact] public void NestedClassGeneric_Insert() { var src1 = @" using System; class C<T> { } "; var src2 = @" using System; class C<T> { class D {} struct S {} enum N {} interface I {} delegate void D(); } class D<T> { } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void NestedEnum_InsertMember() { var src1 = "struct S { enum N { A = 1 } }"; var src2 = "struct S { enum N { A = 1, B = 2 } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [enum N { A = 1 }]@11 -> [enum N { A = 1, B = 2 }]@11", "Insert [B = 2]@27"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value)); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDelete() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 1 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateMember() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 2 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "A = 2", FeaturesResources.enum_value), }), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndUpdateBase() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N : uint { A = 1 } }"; var srcA2 = "partial struct S { enum N : int { A = 1 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.EnumUnderlyingTypeUpdate, "enum N", FeaturesResources.enum_), }), DocumentResults() }); } [Fact, WorkItem(50876, "https://github.com/dotnet/roslyn/issues/50876")] public void NestedEnumInPartialType_InsertDeleteAndInsertMember() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { enum N { A = 1 } }"; var srcA2 = "partial struct S { enum N { A = 1, B = 2 } }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "B = 2", FeaturesResources.enum_value) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDelete() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(); }"; var srcA2 = "partial struct S { delegate void D(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( // delegate does not have any user-defined method body and this does not need a PDB update semanticEdits: NoSemanticEdits), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeParameters() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(); }"; var srcA2 = "partial struct S { delegate void D(int x); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingParameterTypes, "delegate void D(int x)", FeaturesResources.delegate_) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeReturnType() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate ref int D(); }"; var srcA2 = "partial struct S { delegate ref readonly int D(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.TypeUpdate, "delegate ref readonly int D()", FeaturesResources.delegate_) }), DocumentResults() }); } [Fact] public void NestedDelegateInPartialType_InsertDeleteAndChangeOptionalParameterValue() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { delegate void D(int x = 1); }"; var srcA2 = "partial struct S { delegate void D(int x = 2); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults() }); } [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndChange() { var srcA1 = "partial struct S { partial class C { void F1() {} } }"; var srcB1 = "partial struct S { partial class C { void F2(byte x) {} } }"; var srcC1 = "partial struct S { }"; var srcA2 = "partial struct S { partial class C { void F1() {} } }"; var srcB2 = "partial struct S { }"; var srcC2 = "partial struct S { partial class C { void F2(int x) {} } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F2(byte x)")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("S").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }) }); } [Fact] public void Type_Partial_AddMultiple() { var srcA1 = ""; var srcB1 = ""; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteAndChange_Attribute() { var srcA1 = "partial class C { }"; var srcB1 = ""; var srcC1 = "partial class C { }"; var srcA2 = ""; var srcB2 = "[A]partial class C { }"; var srcC2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), DocumentResults(), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteAndChange_TypeParameterAttribute_NotSupportedByRuntime() { var srcA1 = "partial class C<T> { }"; var srcB1 = ""; var srcC1 = "partial class C<T> { }"; var srcA2 = ""; var srcB2 = "partial class C<[A]T> { }"; var srcC2 = "partial class C<T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<[A]T>"), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T") }), DocumentResults(), }); } [Fact] public void Type_Partial_InsertDeleteAndChange_Constraint() { var srcA1 = "partial class C<T> { }"; var srcB1 = ""; var srcC1 = "partial class C<T> { }"; var srcA2 = ""; var srcB2 = "partial class C<T> where T : new() { }"; var srcC2 = "partial class C<T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "partial class C<T>"), Diagnostic(RudeEditKind.ChangingConstraints, "where T : new()", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : new()") }), DocumentResults(), }); } [Fact] public void Type_Partial_InsertDeleteRefactor() { var srcA1 = "partial class C : I { void F() { } }"; var srcB1 = "[A][B]partial class C : J { void G() { } }"; var srcC1 = ""; var srcD1 = ""; var srcA2 = ""; var srcB2 = ""; var srcC2 = "[A]partial class C : I, J { void F() { } }"; var srcD2 = "[B]partial class C { void G() { } }"; var srcE = "interface I {} interface J {}"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE, srcE) }, new[] { DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("G")) }), DocumentResults(), }); } [Fact] public void Type_Partial_Attribute_AddMultiple() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = "partial class C { }" + attributes; var srcB1 = "partial class C { }"; var srcA2 = "[A]partial class C { }" + attributes; var srcB2 = "[B]partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Type_Partial_InsertDeleteRefactor_AttributeListSplitting() { var srcA1 = "partial class C { void F() { } }"; var srcB1 = "[A,B]partial class C { void G() { } }"; var srcC1 = ""; var srcD1 = ""; var srcA2 = ""; var srcB2 = ""; var srcC2 = "[A]partial class C { void F() { } }"; var srcD2 = "[B]partial class C { void G() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G")) }), }); } [Fact] public void Type_Partial_InsertDeleteChangeMember() { var srcA1 = "partial class C { void F(int y = 1) { } }"; var srcB1 = "partial class C { void G(int x = 1) { } }"; var srcC1 = ""; var srcA2 = ""; var srcB2 = "partial class C { void G(int x = 2) { } }"; var srcC2 = "partial class C { void F(int y = 2) { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int y = 2", FeaturesResources.parameter) }), }); } [Fact] public void NestedPartialTypeInPartialType_InsertDeleteAndInsertVirtual() { var srcA1 = "partial interface I { partial class C { virtual void F1() {} } }"; var srcB1 = "partial interface I { partial class C { virtual void F2() {} } }"; var srcC1 = "partial interface I { partial class C { } }"; var srcD1 = "partial interface I { partial class C { } }"; var srcE1 = "partial interface I { }"; var srcF1 = "partial interface I { }"; var srcA2 = "partial interface I { partial class C { } }"; var srcB2 = ""; var srcC2 = "partial interface I { partial class C { virtual void F1() {} } }"; // move existing virtual into existing partial decl var srcD2 = "partial interface I { partial class C { virtual void N1() {} } }"; // insert new virtual into existing partial decl var srcE2 = "partial interface I { partial class C { virtual void F2() {} } }"; // move existing virtual into a new partial decl var srcF2 = "partial interface I { partial class C { virtual void N2() {} } }"; // insert new virtual into new partial decl EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2), GetTopEdits(srcE1, srcE2), GetTopEdits(srcF1, srcF2) }, new[] { // A DocumentResults(), // B DocumentResults(), // C DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F1")) }), // D DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N1()", FeaturesResources.method) }), // E DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("I").GetMember<INamedTypeSymbol>("C").GetMember("F2")) }), // F DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertVirtual, "virtual void N2()", FeaturesResources.method) }), }); } #endregion #region Namespaces [Fact] public void Namespace_Insert() { var src1 = @""; var src2 = @"namespace C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace C { }]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_InsertNested() { var src1 = @"namespace C { }"; var src2 = @"namespace C { namespace D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace D { }]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace D", FeaturesResources.namespace_)); } [Fact] public void Namespace_DeleteNested() { var src1 = @"namespace C { namespace D { } }"; var src2 = @"namespace C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [namespace D { }]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_Move() { var src1 = @"namespace C { namespace D { } }"; var src2 = @"namespace C { } namespace D { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Move [namespace D { }]@14 -> @16"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "namespace D", FeaturesResources.namespace_)); } [Fact] public void Namespace_Reorder1() { var src1 = @"namespace C { namespace D { } class T { } namespace E { } }"; var src2 = @"namespace C { namespace E { } class T { } namespace D { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [class T { }]@30 -> @30", "Reorder [namespace E { }]@42 -> @14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Namespace_Reorder2() { var src1 = @"namespace C { namespace D1 { } namespace D2 { } namespace D3 { } class T { } namespace E { } }"; var src2 = @"namespace C { namespace E { } class T { } namespace D1 { } namespace D2 { } namespace D3 { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [class T { }]@65 -> @65", "Reorder [namespace E { }]@77 -> @14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Namespace_FileScoped_Insert() { var src1 = @""; var src2 = @"namespace C;"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [namespace C;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "namespace C", FeaturesResources.namespace_)); } [Fact] public void Namespace_FileScoped_Delete() { var src1 = @"namespace C;"; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [namespace C;]@0"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, FeaturesResources.namespace_)); } #endregion #region Members [Fact] public void PartialMember_DeleteInsert_SingleDocument() { var src1 = @" using System; partial class C { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } int this[byte i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1; int F2; } partial class C { } "; var src2 = @" using System; partial class C { } partial class C { void M() {} int P1 { get; set; } int P2 { get => 1; set {} } int this[int i] { get => 1; set {} } int this[byte i] { get => 1; set {} } event Action E { add {} remove {} } event Action EF; int F1, F2; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void M() {}]@68", "Insert [int P1 { get; set; }]@85", "Insert [int P2 { get => 1; set {} }]@111", "Insert [int this[int i] { get => 1; set {} }]@144", "Insert [int this[byte i] { get => 1; set {} }]@186", "Insert [event Action E { add {} remove {} }]@229", "Insert [event Action EF;]@270", "Insert [int F1, F2;]@292", "Insert [()]@74", "Insert [{ get; set; }]@92", "Insert [{ get => 1; set {} }]@118", "Insert [[int i]]@152", "Insert [{ get => 1; set {} }]@160", "Insert [[byte i]]@194", "Insert [{ get => 1; set {} }]@203", "Insert [{ add {} remove {} }]@244", "Insert [Action EF]@276", "Insert [int F1, F2]@292", "Insert [get;]@94", "Insert [set;]@99", "Insert [get => 1;]@120", "Insert [set {}]@130", "Insert [int i]@153", "Insert [get => 1;]@162", "Insert [set {}]@172", "Insert [byte i]@195", "Insert [get => 1;]@205", "Insert [set {}]@215", "Insert [add {}]@246", "Insert [remove {}]@253", "Insert [EF]@283", "Insert [F1]@296", "Insert [F2]@300", "Delete [void M() {}]@43", "Delete [()]@49", "Delete [int P1 { get; set; }]@60", "Delete [{ get; set; }]@67", "Delete [get;]@69", "Delete [set;]@74", "Delete [int P2 { get => 1; set {} }]@86", "Delete [{ get => 1; set {} }]@93", "Delete [get => 1;]@95", "Delete [set {}]@105", "Delete [int this[int i] { get => 1; set {} }]@119", "Delete [[int i]]@127", "Delete [int i]@128", "Delete [{ get => 1; set {} }]@135", "Delete [get => 1;]@137", "Delete [set {}]@147", "Delete [int this[byte i] { get => 1; set {} }]@161", "Delete [[byte i]]@169", "Delete [byte i]@170", "Delete [{ get => 1; set {} }]@178", "Delete [get => 1;]@180", "Delete [set {}]@190", "Delete [event Action E { add {} remove {} }]@204", "Delete [{ add {} remove {} }]@219", "Delete [add {}]@221", "Delete [remove {}]@228", "Delete [event Action EF;]@245", "Delete [Action EF]@251", "Delete [EF]@258", "Delete [int F1;]@267", "Delete [int F1]@267", "Delete [F1]@271", "Delete [int F2;]@280", "Delete [int F2]@280", "Delete [F2]@284"); EditAndContinueValidation.VerifySemantics( new[] { edits }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("M"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P1").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P2").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Int32").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.GetParameters().Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod, preserveLocalVariables: false), }) }); } [Fact] public void PartialMember_InsertDelete_MultipleDocuments() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { void F() {} }"; var srcA2 = "partial class C { void F() {} }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F"), preserveLocalVariables: false) }), DocumentResults() }); } [Fact] public void PartialMember_DeleteInsert_MultipleDocuments() { var srcA1 = "partial class C { void F() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"), preserveLocalVariables: false) }) }); } [Fact] public void PartialMember_DeleteInsert_GenericMethod() { var srcA1 = "partial class C { void F<T>() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { void F<T>() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<T>()"), Diagnostic(RudeEditKind.GenericMethodUpdate, "T") }) }); } [Fact] public void PartialMember_DeleteInsert_GenericType() { var srcA1 = "partial class C<T> { void F() {} }"; var srcB1 = "partial class C<T> { }"; var srcA2 = "partial class C<T> { }"; var srcB2 = "partial class C<T> { void F() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "void F()") }) }); } [Fact] public void PartialMember_DeleteInsert_Destructor() { var srcA1 = "partial class C { ~C() {} }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { ~C() {} }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("Finalize"), preserveLocalVariables: false), }) }); } [Fact] public void PartialNestedType_InsertDeleteAndChange() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { class D { void M() {} } interface I { } }"; var srcA2 = "partial class C { class D : I { void M() {} } interface I { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.BaseTypeOrInterfaceUpdate, "class D", FeaturesResources.class_), }), DocumentResults() }); } [Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")] public void PartialMember_RenameInsertDelete() { // The syntactic analysis for A and B produce rename edits since it doesn't see that the member was in fact moved. // TODO: Currently, we don't even pass rename edits to semantic analysis where we could handle them as updates. var srcA1 = "partial class C { void F1() {} }"; var srcB1 = "partial class C { void F2() {} }"; var srcA2 = "partial class C { void F2() {} }"; var srcB2 = "partial class C { void F1() {} }"; // current outcome: GetTopEdits(srcA1, srcA2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F2()", FeaturesResources.method)); GetTopEdits(srcB1, srcB2).VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Renamed, "void F1()", FeaturesResources.method)); // correct outcome: //EditAndContinueValidation.VerifySemantics( // new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, // new[] // { // DocumentResults(semanticEdits: new[] // { // SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F2")), // }), // DocumentResults( // semanticEdits: new[] // { // SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F1")), // }) // }); } [Fact] public void PartialMember_DeleteInsert_UpdateMethodBodyError() { var srcA1 = @" using System.Collections.Generic; partial class C { IEnumerable<int> F() { yield return 1; } } "; var srcB1 = @" using System.Collections.Generic; partial class C { } "; var srcA2 = @" using System.Collections.Generic; partial class C { } "; var srcB2 = @" using System.Collections.Generic; partial class C { IEnumerable<int> F() { yield return 1; yield return 2; } } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.Insert, "yield return 2;", CSharpFeaturesResources.yield_return_statement) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdatePropertyAccessors() { var srcA1 = "partial class C { int P { get => 1; set { Console.WriteLine(1); } } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int P { get => 2; set { Console.WriteLine(2); } } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdateAutoProperty() { var srcA1 = "partial class C { int P => 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int P => 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }) }); } [Fact] public void PartialMember_DeleteInsert_AddFieldInitializer() { var srcA1 = "partial class C { int f; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int f = 1; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_RemoveFieldInitializer() { var srcA1 = "partial class C { int f = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int f; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_ConstructorWithInitializers() { var srcA1 = "partial class C { int f = 1; C(int x) { f = x; } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { int f = 1; }"; var srcB2 = "partial class C { C(int x) { f = x + 1; } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void PartialMember_DeleteInsert_MethodAddParameter() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F() {} }"; var srcA2 = "partial struct S { void F(int x) {} }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F")) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void PartialMember_DeleteInsert_UpdateMethodParameterType() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F(int x); }"; var srcA2 = "partial struct S { void F(byte x); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("S.F")) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F(int x)")) }) }); } [Fact] public void PartialMember_DeleteInsert_MethodAddTypeParameter() { var srcA1 = "partial struct S { }"; var srcB1 = "partial struct S { void F(); }"; var srcA2 = "partial struct S { void F<T>(); }"; var srcB2 = "partial struct S { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InsertGenericMethod, "void F<T>()", FeaturesResources.method) }), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial struct S", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } #endregion #region Methods [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Method_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F() => 0; }"; var src2 = "class C { " + newModifiers + "int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F() => 0;]@10 -> [" + newModifiers + "int F() => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F()", FeaturesResources.method)); } [Fact] public void Method_NewModifier_Add() { var src1 = "class C { int F() => 0; }"; var src2 = "class C { new int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int F() => 0;]@10 -> [new int F() => 0;]@10"); // Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"))); } [Fact] public void Method_NewModifier_Remove() { var src1 = "class C { new int F() => 0; }"; var src2 = "class C { int F() => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [new int F() => 0;]@10 -> [int F() => 0;]@10"); // Currently, an edit is produced eventhough there is no metadata/IL change. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F"))); } [Fact] public void Method_ReadOnlyModifier_Add_InMutableStruct() { var src1 = @" struct S { public int M() => 1; }"; var src2 = @" struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly int M()", FeaturesResources.method)); } [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct1() { var src1 = @" readonly struct S { public int M() => 1; }"; var src2 = @" readonly struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); // Currently, an edit is produced eventhough the body nor IsReadOnly attribute have changed. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IMethodSymbol>("M"))); } [Fact] public void Method_ReadOnlyModifier_Add_InReadOnlyStruct2() { var src1 = @" readonly struct S { public int M() => 1; }"; var src2 = @" struct S { public readonly int M() => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "struct S", "struct")); } [Fact] public void Method_AsyncModifier_Remove() { var src1 = @" class Test { public async Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public Task<int> WaitAsync() { return Task.FromResult(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "public Task<int> WaitAsync()", FeaturesResources.method)); } [Fact] public void Method_AsyncModifier_Add() { var src1 = @" class Test { public Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: false); } [Fact] public void Method_AsyncModifier_Add_NotSupported() { var src1 = @" class Test { public Task<int> WaitAsync() { return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.MakeMethodAsync, "public async Task<int> WaitAsync()")); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Method_ReturnType_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { " + oldType + " M() => default; }"; var src2 = "class C { " + newType + " M() => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Method_ReturnType_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { " + oldType + " M() => default; }"; var src2 = "class C { " + newType + " M() => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " M()", FeaturesResources.method)); } [Fact] public void Method_Update() { var src1 = @" class C { static void Main(string[] args) { int a = 1; int b = 2; System.Console.WriteLine(a + b); } } "; var src2 = @" class C { static void Main(string[] args) { int b = 2; int a = 1; System.Console.WriteLine(a + b); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static void Main(string[] args) { int a = 1; int b = 2; System.Console.WriteLine(a + b); }]@18 -> [static void Main(string[] args) { int b = 2; int a = 1; System.Console.WriteLine(a + b); }]@18"); edits.VerifyRudeDiagnostics(); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) }); } [Fact] public void MethodWithExpressionBody_Update() { var src1 = @" class C { static int Main(string[] args) => F(1); static int F(int a) => 1; } "; var src2 = @" class C { static int Main(string[] args) => F(2); static int F(int a) => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static int Main(string[] args) => F(1);]@18 -> [static int Main(string[] args) => F(2);]@18"); edits.VerifyRudeDiagnostics(); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: false) }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void MethodWithExpressionBody_Update_LiftedParameter() { var src1 = @" using System; class C { int M(int a) => new Func<int>(() => a + 1)(); } "; var src2 = @" using System; class C { int M(int a) => new Func<int>(() => 2)(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int M(int a) => new Func<int>(() => a + 1)();]@35 -> [int M(int a) => new Func<int>(() => 2)();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact] public void MethodWithExpressionBody_ToBlockBody() { var src1 = "class C { static int F(int a) => 1; }"; var src2 = "class C { static int F(int a) { return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) => 1;]@10 -> [static int F(int a) { return 2; }]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false) }); } [Fact] public void MethodWithBlockBody_ToExpressionBody() { var src1 = "class C { static int F(int a) { return 2; } }"; var src2 = "class C { static int F(int a) => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [static int F(int a) { return 2; }]@10 -> [static int F(int a) => 1;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), preserveLocalVariables: false) }); } [Fact] public void MethodWithLambda_Update() { var src1 = @" using System; class C { static void F() { Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; } } "; var src2 = @" using System; class C { static void F() { Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); } }"; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F"), syntaxMap[0]) }); } [Fact] public void MethodUpdate_LocalVariableDeclaration() { var src1 = @" class C { static void Main(string[] args) { int x = 1; Console.WriteLine(x); } } "; var src2 = @" class C { static void Main(string[] args) { int x = 2; Console.WriteLine(x); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Update [static void Main(string[] args) { int x = 1; Console.WriteLine(x); }]@18 -> [static void Main(string[] args) { int x = 2; Console.WriteLine(x); }]@18"); } [Fact] public void Method_Delete() { var src1 = @" class C { void goo() { } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [void goo() { }]@18", "Delete [()]@26"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [Fact] public void MethodWithExpressionBody_Delete() { var src1 = @" class C { int goo() => 1; } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int goo() => 1;]@18", "Delete [()]@25"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo()"))); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodDelete_WithParameterAndAttribute() { var src1 = @" class C { [Obsolete] void goo(int a) { } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Delete [[Obsolete] void goo(int a) { }]@18", "Delete [(int a)]@42", "Delete [int a]@43"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "goo(int a)"))); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodDelete_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] public static extern int puts(string c); } "; var src2 = @" using System; using System.Runtime.InteropServices; class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Delete [[DllImport(""msvcrt.dll"")] public static extern int puts(string c);]@74", "Delete [(string c)]@134", "Delete [string c]@135"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.method, "puts(string c)"))); } [Fact] public void MethodInsert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { void goo() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "void goo()", FeaturesResources.method)); } [Fact] public void PrivateMethodInsert() { var src1 = @" class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" class C { void goo() { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void goo() { }]@18", "Insert [()]@26"); edits.VerifyRudeDiagnostics(); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] [Fact] public void PrivateMethodInsert_WithParameters() { var src1 = @" using System; class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" using System; class C { void goo(int a) { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void goo(int a) { }]@35", "Insert [(int a)]@43", "Insert [int a]@44"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.goo")) }); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784")] [Fact] public void PrivateMethodInsert_WithAttribute() { var src1 = @" class C { static void Main(string[] args) { Console.ReadLine(); } }"; var src2 = @" class C { [System.Obsolete] void goo(int a) { } static void Main(string[] args) { Console.ReadLine(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [[System.Obsolete] void goo(int a) { }]@18", "Insert [(int a)]@49", "Insert [int a]@50"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodInsert_Virtual() { var src1 = @" class C { }"; var src2 = @" class C { public virtual void F() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public virtual void F()", FeaturesResources.method)); } [Fact] public void MethodInsert_Abstract() { var src1 = @" abstract class C { }"; var src2 = @" abstract class C { public abstract void F(); } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public abstract void F()", FeaturesResources.method)); } [Fact] public void MethodInsert_Override() { var src1 = @" class C { }"; var src2 = @" class C { public override void F() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertVirtual, "public override void F()", FeaturesResources.method)); } [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void ExternMethodInsert() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( @"Insert [[DllImport(""msvcrt.dll"")] private static extern int puts(string c);]@74", "Insert [(string c)]@135", "Insert [string c]@136"); // CLR doesn't support methods without a body edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "private static extern int puts(string c)", FeaturesResources.method)); } [Fact] [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethodDeleteInsert() { var srcA1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); }"; var srcA2 = @" using System; using System.Runtime.InteropServices; "; var srcB1 = @" using System; using System.Runtime.InteropServices; "; var srcB2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); } "; // TODO: The method does not need to be updated since there are no sequence points generated for it. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")), }) }); } [Fact] [WorkItem(755784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755784"), WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] public void ExternMethod_Attribute_DeleteInsert() { var srcA1 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] private static extern int puts(string c); }"; var srcA2 = @" using System; using System.Runtime.InteropServices; "; var srcB1 = @" using System; using System.Runtime.InteropServices; "; var srcB2 = @" using System; using System.Runtime.InteropServices; class C { [DllImport(""msvcrt.dll"")] [Obsolete] private static extern int puts(string c); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.puts")), }) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodReorder1() { var src1 = "class C { void f(int a, int b) { a = b; } void g() { } }"; var src2 = "class C { void g() { } void f(int a, int b) { a = b; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Reorder [void g() { }]@42 -> @10"); } [Fact] public void MethodInsertDelete1() { var src1 = "class C { class D { } void f(int a, int b) { a = b; } }"; var src2 = "class C { class D { void f(int a, int b) { a = b; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [void f(int a, int b) { a = b; }]@20", "Insert [(int a, int b)]@26", "Insert [int a]@27", "Insert [int b]@34", "Delete [void f(int a, int b) { a = b; }]@22", "Delete [(int a, int b)]@28", "Delete [int a]@29", "Delete [int b]@36"); } [Fact] public void MethodUpdate_AddParameter() { var src1 = @" class C { static void Main() { } }"; var src2 = @" class C { static void Main(string[] args) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [string[] args]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "string[] args", FeaturesResources.parameter)); } [Fact] public void MethodUpdate_UpdateParameter() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] b) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [string[] args]@35 -> [string[] b]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "string[] b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_UpdateParameterAndBody() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] b) { System.Console.Write(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.RenamingNotSupportedByRuntime, "string[] b", FeaturesResources.parameter)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Method_Name_Update() { var src1 = @" class C { static void Main(string[] args) { } }"; var src2 = @" class C { static void EntryPoint(string[] args) { } }"; var edits = GetTopEdits(src1, src2); var expectedEdit = @"Update [static void Main(string[] args) { }]@18 -> [static void EntryPoint(string[] args) { }]@18"; edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "static void EntryPoint(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AsyncMethod0() { var src1 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(1000); return 1; } }"; var src2 = @" class Test { public async Task<int> WaitAsync() { await Task.Delay(500); return 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [Fact] public void MethodUpdate_AsyncMethod1() { var src1 = @" class Test { static void Main(string[] args) { Test f = new Test(); string result = f.WaitAsync().Result; } public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Done""; } }"; var src2 = @" class Test { static void Main(string[] args) { Test f = new Test(); string result = f.WaitAsync().Result; } public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Not Done""; } }"; var edits = GetTopEdits(src1, src2); var expectedEdit = @"Update [public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Done""; }]@151 -> [public async Task<string> WaitAsync() { await Task.Delay(1000); return ""Not Done""; }]@151"; edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AddReturnTypeAttribute() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [return: Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[return: Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute_SupportedByRuntime() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [static void Main(string[] args) { System.Console.Write(5); }]@38 -> [[Obsolete] static void Main(string[] args) { System.Console.Write(5); }]@38"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Test.Main")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_Attribute_ArrayParameter() { var src1 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { } }"; var src2 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 4, 5, 6})] void M() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void MethodUpdate_Attribute_ArrayParameter_NoChange() { var src1 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { var x = 1; } }"; var src2 = @" class AAttribute : System.Attribute { public AAttribute(int[] nums) { } } class C { [A(new int[] { 1, 2, 3})] void M() { var x = 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AddAttribute2() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute3() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] [Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_AddAttribute4() { var src1 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_UpdateAttribute() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete("""")] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [WorkItem(754853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754853")] [Fact] public void MethodUpdate_DeleteAttribute() { var src1 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_DeleteAttribute2() { var src1 = @" using System; class Test { [Obsolete, Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_DeleteAttribute3() { var src1 = @" using System; class Test { [Obsolete] [Serializable] static void Main(string[] args) { System.Console.Write(5); } }"; var src2 = @" using System; class Test { [Obsolete] static void Main(string[] args) { System.Console.Write(5); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "static void Main(string[] args)", FeaturesResources.method)); } [Fact] public void MethodUpdate_ExplicitlyImplemented1() { var src1 = @" class C : I, J { void I.Goo() { Console.WriteLine(2); } void J.Goo() { Console.WriteLine(1); } }"; var src2 = @" class C : I, J { void I.Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void I.Goo() { Console.WriteLine(2); }]@25 -> [void I.Goo() { Console.WriteLine(1); }]@25", "Update [void J.Goo() { Console.WriteLine(1); }]@69 -> [void J.Goo() { Console.WriteLine(2); }]@69"); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_ExplicitlyImplemented2() { var src1 = @" class C : I, J { void I.Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var src2 = @" class C : I, J { void Goo() { Console.WriteLine(1); } void J.Goo() { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void I.Goo() { Console.WriteLine(1); }]@25 -> [void Goo() { Console.WriteLine(1); }]@25"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "void Goo()", FeaturesResources.method)); } [WorkItem(754255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754255")] [Fact] public void MethodUpdate_UpdateStackAlloc() { var src1 = @" class C { static void Main(string[] args) { int i = 10; unsafe { int* px2 = &i; } } }"; var src2 = @" class C { static void Main(string[] args) { int i = 10; unsafe { char* buffer = stackalloc char[16]; int* px2 = &i; } } }"; var expectedEdit = @"Update [static void Main(string[] args) { int i = 10; unsafe { int* px2 = &i; } }]@18 -> [static void Main(string[] args) { int i = 10; unsafe { char* buffer = stackalloc char[16]; int* px2 = &i; } }]@18"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(expectedEdit); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method)); } [Theory] [InlineData("stackalloc int[3]")] [InlineData("stackalloc int[3] { 1, 2, 3 }")] [InlineData("stackalloc int[] { 1, 2, 3 }")] [InlineData("stackalloc[] { 1, 2, 3 }")] public void MethodUpdate_UpdateStackAlloc2(string stackallocDecl) { var src1 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 1; } }"; var src2 = @"unsafe class C { static int F() { var x = " + stackallocDecl + "; return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.method)); } [Fact] public void MethodUpdate_UpdateStackAllocInLambda1() { var src1 = "unsafe class C { void M() { F(1, () => { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, () => { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInLambda2() { var src1 = "unsafe class C { void M() { F(1, x => { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, x => { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInAnonymousMethod() { var src1 = "unsafe class C { void M() { F(1, delegate(int x) { int* a = stackalloc int[10]; }); } }"; var src2 = "unsafe class C { void M() { F(2, delegate(int x) { int* a = stackalloc int[10]; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateStackAllocInLocalFunction() { var src1 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(1); } }"; var src2 = "class C { void M() { unsafe void f(int x) { int* a = stackalloc int[10]; } f(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLambda1() { var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }"; var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLambda2() { var src1 = "class C { void M() { F(1, a => a switch { 0 => 0, _ => 2 }); } }"; var src2 = "class C { void M() { F(2, a => a switch { 0 => 0, _ => 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInAnonymousMethod() { var src1 = "class C { void M() { F(1, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }"; var src2 = "class C { void M() { F(2, delegate(int a) { return a switch { 0 => 0, _ => 2 }; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInLocalFunction() { var src1 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(1); } }"; var src2 = "class C { void M() { int f(int a) => a switch { 0 => 0, _ => 2 }; f(2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_SwitchExpressionInQuery() { var src1 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 1; } }"; var src2 = "class C { void M() { var x = from z in new[] { 1, 2, 3 } where z switch { 0 => true, _ => false } select z + 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_UpdateAnonymousMethod() { var src1 = "class C { void M() { F(1, delegate(int a) { return a; }); } }"; var src2 = "class C { void M() { F(2, delegate(int a) { return a; }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_UpdateAnonymousMethod() { var src1 = "class C { void M() => F(1, delegate(int a) { return a; }); }"; var src2 = "class C { void M() => F(2, delegate(int a) { return a; }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_Query() { var src1 = "class C { void M() { F(1, from goo in bar select baz); } }"; var src2 = "class C { void M() { F(2, from goo in bar select baz); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_Query() { var src1 = "class C { void M() => F(1, from goo in bar select baz); }"; var src2 = "class C { void M() => F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_AnonymousType() { var src1 = "class C { void M() { F(1, new { A = 1, B = 2 }); } }"; var src2 = "class C { void M() { F(2, new { A = 1, B = 2 }); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodWithExpressionBody_Update_AnonymousType() { var src1 = "class C { void M() => F(new { A = 1, B = 2 }); }"; var src2 = "class C { void M() => F(new { A = 10, B = 20 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_Iterator_YieldReturn() { var src1 = "class C { IEnumerable<int> M() { yield return 1; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [Fact] public void MethodUpdate_AddYieldReturn() { var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: false); } [Fact] public void MethodUpdate_AddYieldReturn_NotSupported() { var src1 = "class C { IEnumerable<int> M() { return new[] { 1, 2, 3}; } }"; var src2 = "class C { IEnumerable<int> M() { yield return 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.MakeMethodIterator, "IEnumerable<int> M()")); } [Fact] public void MethodUpdate_Iterator_YieldBreak() { var src1 = "class C { IEnumerable<int> M() { F(); yield break; } }"; var src2 = "class C { IEnumerable<int> M() { G(); yield break; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); VerifyPreserveLocalVariables(edits, preserveLocalVariables: true); } [WorkItem(1087305, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087305")] [Fact] public void MethodUpdate_LabeledStatement() { var src1 = @" class C { static void Main(string[] args) { goto Label1; Label1: { Console.WriteLine(1); } } }"; var src2 = @" class C { static void Main(string[] args) { goto Label1; Label1: { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void MethodUpdate_LocalFunctionsParameterRefnessInBody() { var src1 = @"class C { public void M(int a) { void f(ref int b) => b = 1; } }"; var src2 = @"class C { public void M(int a) { void f(out int b) => b = 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public void M(int a) { void f(ref int b) => b = 1; }]@10 -> [public void M(int a) { void f(out int b) => b = 1; }]@10"); } [Fact] public void MethodUpdate_LambdaParameterRefnessInBody() { var src1 = @"class C { public void M(int a) { f((ref int b) => b = 1); } }"; var src2 = @"class C { public void M(int a) { f((out int b) => b = 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public void M(int a) { f((ref int b) => b = 1); }]@10 -> [public void M(int a) { f((out int b) => b = 1); }]@10"); } [Fact] public void Method_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int M(in int b) => throw null;]@13", "Insert [(in int b)]@18", "Insert [in int b]@19"); edits.VerifyRudeDiagnostics(); } [Fact] public void Method_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "class Test { int M() => throw null; }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@19"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Method_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { int M(int b) => throw null; }"; var src2 = "class Test { int M(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@19 -> [in int b]@19"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } [Fact] public void Method_ReadOnlyRef_ReturnType_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int M() => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int M() => throw null;]@13", "Insert [()]@31"); edits.VerifyRudeDiagnostics(); } [Fact] public void Method_ReadOnlyRef_ReturnType_Update() { var src1 = "class Test { int M() => throw null; }"; var src2 = "class Test { ref readonly int M() => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int M() => throw null;]@13 -> [ref readonly int M() => throw null;]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int M()", FeaturesResources.method)); } [Fact] public void Method_ImplementingInterface_Add() { var src1 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; } "; var src2 = @" using System; public interface ISample { string Get(); } public interface IConflict { string Get(); } public class BaseClass : ISample { public virtual string Get() => string.Empty; } public class SubClass : BaseClass, IConflict { public override string Get() => string.Empty; string IConflict.Get() => String.Empty; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [string IConflict.Get() => String.Empty;]@325", "Insert [()]@345"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, "string IConflict.Get()", FeaturesResources.method)); } [Fact] public void Method_Partial_DeleteInsert_DefinitionPart() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { partial void F() { } }"; var srcC2 = "partial class C { partial void F(); }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(), }); } [Fact] public void Method_Partial_DeleteInsert_ImplementationPart() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { }"; var srcC2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), }); } [Fact, WorkItem(51011, "https://github.com/dotnet/roslyn/issues/51011")] public void Method_Partial_Swap_ImplementationAndDefinitionParts() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { partial void F() { } }"; var srcB2 = "partial class C { partial void F(); }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), DocumentResults(), }); } [Fact] public void Method_Partial_DeleteImplementation() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void Method_Partial_DeleteBoth() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.Delete, "partial class C", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } [Fact] public void Method_Partial_DeleteInsertBoth() { var srcA1 = "partial class C { partial void F(); }"; var srcB1 = "partial class C { partial void F() { } }"; var srcC1 = "partial class C { }"; var srcD1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { }"; var srcC2 = "partial class C { partial void F(); }"; var srcD2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2), GetTopEdits(srcC1, srcC2), GetTopEdits(srcD1, srcD2) }, new[] { DocumentResults(), DocumentResults(), DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }) }); } [Fact] public void Method_Partial_Insert() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { partial void F(); }"; var srcB2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F").PartialImplementationPart) }), }); } [Fact] public void Method_Partial_Insert_Reloadable() { var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { partial void F(); }"; var srcB2 = "partial class C { partial void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } #endregion #region Operators [Theory] [InlineData("implicit", "explicit")] [InlineData("explicit", "implicit")] public void Operator_Modifiers_Update(string oldModifiers, string newModifiers) { var src1 = "class C { public static " + oldModifiers + " operator int (C c) => 0; }"; var src2 = "class C { public static " + newModifiers + " operator int (C c) => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static " + oldModifiers + " operator int (C c) => 0;]@10 -> [public static " + newModifiers + " operator int (C c) => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public static " + newModifiers + " operator int (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void Operator_Modifiers_Update_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static implicit operator int (C c) => 0; }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { public static explicit operator int (C c) => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Operator_Conversion_ExternModifiers_Add() { var src1 = "class C { public static implicit operator bool (C c) => default; }"; var src2 = "class C { extern public static implicit operator bool (C c); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "extern public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void Operator_Conversion_ExternModifiers_Remove() { var src1 = "class C { extern public static implicit operator bool (C c); }"; var src2 = "class C { public static implicit operator bool (C c) => default; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator)); } [Fact] public void OperatorInsert() { var src1 = @" class C { } "; var src2 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertOperator, "public static implicit operator bool (C c)", CSharpFeaturesResources.conversion_operator), Diagnostic(RudeEditKind.InsertOperator, "public static C operator +(C c, C d)", FeaturesResources.operator_)); } [Fact] public void OperatorDelete() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } } "; var src2 = @" class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(CSharpFeaturesResources.conversion_operator, "implicit operator bool(C c)")), Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.operator_, "operator +(C c, C d)"))); } [Fact] public void OperatorInsertDelete() { var srcA1 = @" partial class C { public static implicit operator bool (C c) => false; } "; var srcB1 = @" partial class C { public static C operator +(C c, C d) => c; } "; var srcA2 = srcB1; var srcB2 = srcA1; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Addition")) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("op_Implicit")) }), }); } [Fact] public void OperatorUpdate() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static C operator +(C c, C d) { return c; } } "; var src2 = @" class C { public static implicit operator bool (C c) { return true; } public static C operator +(C c, C d) { return d; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")), }); } [Fact] public void OperatorWithExpressionBody_Update() { var src1 = @" class C { public static implicit operator bool (C c) => false; public static C operator +(C c, C d) => c; } "; var src2 = @" class C { public static implicit operator bool (C c) => true; public static C operator +(C c, C d) => d; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Implicit")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")), }); } [Fact] public void OperatorWithExpressionBody_ToBlockBody() { var src1 = "class C { public static C operator +(C c, C d) => d; }"; var src2 = "class C { public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static C operator +(C c, C d) => d;]@10 -> [public static C operator +(C c, C d) { return c; }]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")) }); } [Fact] public void OperatorWithBlockBody_ToExpressionBody() { var src1 = "class C { public static C operator +(C c, C d) { return c; } }"; var src2 = "class C { public static C operator +(C c, C d) => d; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public static C operator +(C c, C d) { return c; }]@10 -> [public static C operator +(C c, C d) => d;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.op_Addition")) }); } [Fact] public void OperatorReorder1() { var src1 = @" class C { public static implicit operator bool (C c) { return false; } public static implicit operator int (C c) { return 1; } } "; var src2 = @" class C { public static implicit operator int (C c) { return 1; } public static implicit operator bool (C c) { return false; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [public static implicit operator int (C c) { return 1; }]@84 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void OperatorReorder2() { var src1 = @" class C { public static C operator +(C c, C d) { return c; } public static C operator -(C c, C d) { return d; } } "; var src2 = @" class C { public static C operator -(C c, C d) { return d; } public static C operator +(C c, C d) { return c; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [public static C operator -(C c, C d) { return d; }]@74 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void Operator_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { public static bool operator !(in Test b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public static bool operator !(in Test b) => throw null;]@13", "Insert [(in Test b)]@42", "Insert [in Test b]@43"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertOperator, "public static bool operator !(in Test b)", FeaturesResources.operator_)); } [Fact] public void Operator_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { public static bool operator !(Test b) => throw null; }"; var src2 = "class Test { public static bool operator !(in Test b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Test b]@43 -> [in Test b]@43"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in Test b", FeaturesResources.parameter)); } #endregion #region Constructor, Destructor [Fact] public void Constructor_Parameter_AddAttribute() { var src1 = @" class C { private int x = 1; public C(int a) { } }"; var src2 = @" class C { private int x = 2; public C([System.Obsolete]int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [x = 1]@30 -> [x = 2]@30", "Update [int a]@53 -> [[System.Obsolete]int a]@53"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C..ctor")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] [WorkItem(2068, "https://github.com/dotnet/roslyn/issues/2068")] public void Constructor_ExternModifier_Add() { var src1 = "class C { }"; var src2 = "class C { public extern C(); }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [public extern C();]@10", "Insert [()]@25"); // This can be allowed as the compiler generates an empty constructor, but it's not worth the complexity. edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public extern C()", FeaturesResources.constructor)); } [Fact] public void ConstructorInitializer_Update1() { var src1 = @" class C { public C(int a) : base(a) { } }"; var src2 = @" class C { public C(int a) : base(a + 1) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@18 -> [public C(int a) : base(a + 1) { }]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void ConstructorInitializer_Update2() { var src1 = @" class C<T> { public C(int a) : base(a) { } }"; var src2 = @" class C<T> { public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@21 -> [public C(int a) { }]@21"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)")); } [Fact] public void ConstructorInitializer_Update3() { var src1 = @" class C { public C(int a) { } }"; var src2 = @" class C { public C(int a) : base(a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) { }]@18 -> [public C(int a) : base(a) { }]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void ConstructorInitializer_Update4() { var src1 = @" class C<T> { public C(int a) : base(a) { } }"; var src2 = @" class C<T> { public C(int a) : base(a + 1) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public C(int a) : base(a) { }]@21 -> [public C(int a) : base(a + 1) { }]@21"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "public C(int a)")); } [WorkItem(743552, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/743552")] [Fact] public void ConstructorUpdate_AddParameter() { var src1 = @" class C { public C(int a) { } }"; var src2 = @" class C { public C(int a, int b) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a)]@26 -> [(int a, int b)]@26", "Insert [int b]@34"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "int b", FeaturesResources.parameter)); } [Fact] public void DestructorDelete() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { }"; var expectedEdit1 = @"Delete [~B() { }]@10"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(expectedEdit1); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); } [Fact] public void DestructorDelete_InsertConstructor() { var src1 = @"class B { ~B() { } }"; var src2 = @"class B { B() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [B() { }]@10", "Insert [()]@11", "Delete [~B() { }]@10"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "B()", FeaturesResources.constructor), Diagnostic(RudeEditKind.Delete, "class B", DeletedSymbolDisplay(CSharpFeaturesResources.destructor, "~B()"))); } [Fact] [WorkItem(789577, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/789577")] public void ConstructorUpdate_AnonymousTypeInFieldInitializer() { var src1 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 1; } }"; var src2 = "class C { int a = F(new { A = 1, B = 2 }); C() { x = 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Constructor_Static_Delete() { var src1 = "class C { static C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.static_constructor, "C()"))); } [Fact] public void Constructor_Static_Delete_Reloadable() { var src1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { static C() { } }"; var src2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"))); } [Fact] public void Constructor_Static_Insert() { var src1 = "class C { }"; var src2 = "class C { static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void InstanceCtorDelete_Public() { var src1 = "class C { public C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("protected")] [InlineData("internal")] [InlineData("private protected")] [InlineData("protected internal")] public void InstanceCtorDelete_NonPublic(string accessibility) { var src1 = "class C { [System.Obsolete] " + accessibility + " C() { } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")), Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void InstanceCtorDelete_Public_PartialWithInitializerUpdate() { var srcA1 = "partial class C { public C() { } }"; var srcB1 = "partial class C { int x = 1; }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }) }); } [Fact] public void InstanceCtorInsert_Public_Implicit() { var src1 = "class C { }"; var src2 = "class C { public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void InstanceCtorInsert_Partial_Public_Implicit() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // no change in document A DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtorInsert_Public_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty)) }); } [Fact] public void InstanceCtorInsert_Partial_Public_NoImplicit() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { public C(int a) { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { public C(int a) { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(c => c.Parameters.IsEmpty)) }), // no change in document B DocumentResults(), }); } [Fact] public void InstanceCtorInsert_Private_Implicit1() { var src1 = "class C { }"; var src2 = "class C { private C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "private C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Private_Implicit2() { var src1 = "class C { }"; var src2 = "class C { C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Protected_PublicImplicit() { var src1 = "class C { }"; var src2 = "class C { protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "protected C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Internal_PublicImplicit() { var src1 = "class C { }"; var src2 = "class C { internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorInsert_Internal_ProtectedImplicit() { var src1 = "abstract class C { }"; var src2 = "abstract class C { internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor)); } [Fact] public void InstanceCtorUpdate_ProtectedImplicit() { var src1 = "abstract class C { }"; var src2 = "abstract class C { protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void InstanceCtorInsert_Private_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } private C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C") .InstanceConstructors.Single(ctor => ctor.DeclaredAccessibility == Accessibility.Private)) }); } [Fact] public void InstanceCtorInsert_Internal_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } internal C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void InstanceCtorInsert_Protected_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void InstanceCtorInsert_InternalProtected_NoImplicit() { var src1 = "class C { public C(int a) { } }"; var src2 = "class C { public C(int a) { } internal protected C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void StaticCtor_Partial_DeleteInsert() { var srcA1 = "partial class C { static C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { static C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePrivateInsertPrivate() { var srcA1 = "partial class C { C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePublicInsertPublic() { var srcA1 = "partial class C { public C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void InstanceCtor_Partial_DeletePrivateInsertPublic() { var srcA1 = "partial class C { C() { } }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { public C() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // delete of the constructor in partial part will be reported as rude edit in the other document where it was inserted back with changed accessibility DocumentResults( semanticEdits: NoSemanticEdits), DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }), }); } [Fact] public void StaticCtor_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { static C() { } }"; var srcA2 = "partial class C { static C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPublicDeletePublic() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { public C() { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPrivateDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { private C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_DeleteInternalInsertInternal() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { internal C() { } }"; var srcA2 = "partial class C { internal C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertInternalDeleteInternal_WithBody() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { internal C() { } }"; var srcA2 = "partial class C { internal C() { Console.WriteLine(1); } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), // delete of the constructor in partial part will be represented as a semantic update in the other document where it was inserted back DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertPublicDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { public C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "public C()", FeaturesResources.constructor) }), // delete of the constructor in partial part will be reported as rude in the the other document where it was inserted with changed accessibility DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_InsertInternalDeletePrivate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { private C() { } }"; var srcA2 = "partial class C { internal C() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ChangingAccessibility, "internal C()", FeaturesResources.constructor) }), DocumentResults(), }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 2</N:0.2>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer_Trivia1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); /*new trivia*/public C() { F(<N:0.2>c => c + 1</N:0.2>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Update_LambdaInInitializer_ExplicitInterfaceImpl1() { var src1 = @" using System; public interface I { int B { get; } } public interface J { int B { get; } } partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C : I, J { int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>); int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>); public C() { F(<N:0.3>c => c + 1</N:0.3>); } } "; var src2 = @" using System; public interface I { int B { get; } } public interface J { int B { get; } } partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C : I, J { int I.B { get; } = F(<N:0.1>ib => ib + 1</N:0.1>); int J.B { get; } = F(<N:0.2>jb => jb + 1</N:0.2>); public C() { F(<N:0.3>c => c + 2</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void InstanceCtor_Partial_Insert_Parameterless_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C() // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()")); // TODO: //var syntaxMap = GetSyntaxMap(src1, src2); //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void InstanceCtor_Partial_Insert_WithParameters_LambdaInInitializer1() { var src1 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; partial class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int B { get; } = F(<N:0.1>b => b + 1</N:0.1>); public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)")); // TODO: bug https://github.com/dotnet/roslyn/issues/2504 //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void InstanceCtor_Partial_Explicit_Update() { var srcA1 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(bool arg) => Console.WriteLine(1); } "; var srcB1 = @" using System; partial class C { int a <N:0.0>= 1</N:0.0>; C(uint arg) => Console.WriteLine(2); } "; var srcA2 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(bool arg) => Console.WriteLine(1); } "; var srcB2 = @" using System; partial class C { int a <N:0.0>= 2</N:0.0>; // updated field initializer C(uint arg) => Console.WriteLine(2); C(byte arg) => Console.WriteLine(3); // new ctor } "; var syntaxMapB = GetSyntaxMap(srcB1, srcB2)[0]; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // No changes in document A DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Int32"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Boolean"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "UInt32"), partialType: "C", syntaxMap: syntaxMapB), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(c => c.Parameters.Single().Type.Name == "Byte"), syntaxMap: null), }) }); } [Fact] public void InstanceCtor_Partial_Explicit_Update_SemanticError() { var srcA1 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(int arg) => Console.WriteLine(1); } "; var srcB1 = @" using System; partial class C { int a = 1; } "; var srcA2 = @" using System; partial class C { C(int arg) => Console.WriteLine(0); C(int arg) => Console.WriteLine(1); } "; var srcB2 = @" using System; partial class C { int a = 2; C(int arg) => Console.WriteLine(2); } "; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { // No changes in document A DocumentResults(), // The actual edits do not matter since there are semantic errors in the compilation. // We just should not crash. DocumentResults(diagnostics: Array.Empty<RudeEditDiagnosticDescription>()) }); } [Fact] public void InstanceCtor_Partial_Implicit_Update() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { int G = 1; }"; var srcA2 = "partial class C { int F = 2; }"; var srcB2 = "partial class C { int G = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void ParameterlessConstructor_SemanticError_Delete1() { var src1 = @" class C { D() {} } "; var src2 = @" class C { } "; var edits = GetTopEdits(src1, src2); // The compiler interprets D() as a constructor declaration. edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, "class C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Fact] public void Constructor_SemanticError_Partial() { var src1 = @" partial class C { partial void C(int x); } partial class C { partial void C(int x) { System.Console.WriteLine(1); } } "; var src2 = @" partial class C { partial void C(int x); } partial class C { partial void C(int x) { System.Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("C").PartialImplementationPart) }); } [Fact] public void PartialDeclaration_Delete() { var srcA1 = "partial class C { public C() { } void F() { } }"; var srcB1 = "partial class C { int x = 1; }"; var srcA2 = ""; var srcB2 = "partial class C { int x = 2; void F() { } }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void PartialDeclaration_Insert() { var srcA1 = ""; var srcB1 = "partial class C { int x = 1; void F() { } }"; var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = "partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IMethodSymbol>("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void PartialDeclaration_Insert_Reloadable() { var srcA1 = ""; var srcB1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 1; void F() { } }"; var srcA2 = "partial class C { public C() { } void F() { } }"; var srcB2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C { int x = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void Constructor_DeleteParameterless(string typeKind) { var src1 = @" " + typeKind + @" C { private int a = 10; private int b; public C() { b = 3; } } "; var src2 = @" " + typeKind + @" C { private int a = 10; private int b; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [public C() { b = 3; }]@66", "Delete [()]@74"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void Constructor_InsertParameterless(string typeKind) { var src1 = @" " + typeKind + @" C { private int a = 10; private int b; } "; var src2 = @" " + typeKind + @" C { private int a = 10; private int b; public C() { b = 3; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [public C() { b = 3; }]@66", "Insert [()]@74"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_BlockBodyToExpressionBody() { var src1 = @" public class C { private int _value; public C(int value) { _value = value; } } "; var src2 = @" public class C { private int _value; public C(int value) => _value = value; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) { _value = value; }]@52 -> [public C(int value) => _value = value;]@52"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void ConstructorWithInitializer_BlockBodyToExpressionBody() { var src1 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) { _value = value; } } "; var src2 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) => _value = value; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [public C(int value) : base(value) { _value = value; }]@90 -> [public C(int value) : base(value) => _value = value;]@90"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Constructor_ExpressionBodyToBlockBody() { var src1 = @" public class C { private int _value; public C(int value) => _value = value; } "; var src2 = @" public class C { private int _value; public C(int value) { _value = value; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) => _value = value;]@52 -> [public C(int value) { _value = value; }]@52"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void ConstructorWithInitializer_ExpressionBodyToBlockBody() { var src1 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) => _value = value; } "; var src2 = @" public class B { B(int value) {} } public class C : B { private int _value; public C(int value) : base(value) { _value = value; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits(@"Update [public C(int value) : base(value) => _value = value;]@90 -> [public C(int value) : base(value) { _value = value; }]@90"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_BlockBodyToExpressionBody() { var src1 = @" public class C { ~C() { Console.WriteLine(0); } } "; var src2 = @" public class C { ~C() => Console.WriteLine(0); } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() { Console.WriteLine(0); }]@25 -> [~C() => Console.WriteLine(0);]@25"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Destructor_ExpressionBodyToBlockBody() { var src1 = @" public class C { ~C() => Console.WriteLine(0); } "; var src2 = @" public class C { ~C() { Console.WriteLine(0); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [~C() => Console.WriteLine(0);]@25 -> [~C() { Console.WriteLine(0); }]@25"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Finalize"), preserveLocalVariables: false) }); } [Fact] public void Constructor_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [Test(in int b) => throw null;]@13", "Insert [(in int b)]@17", "Insert [in int b]@18"); edits.VerifyRudeDiagnostics(); } [Fact] public void Constructor_ReadOnlyRef_Parameter_InsertParameter() { var src1 = "class Test { Test() => throw null; }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [in int b]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "in int b", FeaturesResources.parameter)); } [Fact] public void Constructor_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { Test(int b) => throw null; }"; var src2 = "class Test { Test(in int b) => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@18 -> [in int b]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int b", FeaturesResources.parameter)); } #endregion #region Fields and Properties with Initializers [Theory] [InlineData("class ")] [InlineData("struct")] public void FieldInitializer_Update1(string typeKind) { var src1 = typeKind + " C { int a = 0; }"; var src2 = typeKind + " C { int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@15 -> [a = 1]@15"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void PropertyInitializer_Update1(string typeKind) { var src1 = typeKind + " C { int a { get; } = 0; }"; var src2 = typeKind + " C { int a { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get; } = 0;]@11 -> [int a { get; } = 1;]@11"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializer_Update2() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a]@14"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializer_Update2() { var src1 = "class C { int a { get; } = 0; }"; var src2 = "class C { int a { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get; } = 0;]@10 -> [int a { get { return 1; } }]@10", "Update [get;]@18 -> [get { return 1; }]@18"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true)); } [Fact] public void PropertyInitializer_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int a { get; } = 0; }"; var srcA2 = "partial class C { int a { get { return 1; } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults() }); } [Fact] public void FieldInitializer_Update3() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializer_Update3() { var src1 = "class C { int a { get { return 1; } } }"; var src2 = "class C { int a { get; } = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a { get { return 1; } }]@10 -> [int a { get; } = 0;]@10", "Update [get { return 1; }]@18 -> [get;]@18"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IPropertySymbol>("C.a").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorUpdate1() { var src1 = "class C { static int a; static C() { } }"; var src2 = "class C { static int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21", "Delete [static C() { }]@24", "Delete [()]@32"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_StaticCtorUpdate1() { var src1 = "class C { static int a { get; } = 1; static C() { } }"; var src2 = "class C { static int a { get; } = 2;}"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void FieldInitializerUpdate_InstanceCtorUpdate_Private(string typeKind) { var src1 = typeKind + " C { int a; [System.Obsolete]C() { } }"; var src2 = typeKind + " C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, $"{typeKind} C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()")), Diagnostic(RudeEditKind.ChangingAccessibility, $"{typeKind} C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Theory] [InlineData("class ")] [InlineData("struct")] public void PropertyInitializerUpdate_InstanceCtorUpdate_Private(string typeKind) { var src1 = typeKind + " C { int a { get; } = 1; C() { } }"; var src2 = typeKind + " C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ChangingAccessibility, $"{typeKind} C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } [Theory] [InlineData("class ")] [InlineData("struct")] public void FieldInitializerUpdate_InstanceCtorUpdate_Public(string typeKind) { var src1 = typeKind + " C { int a; public C() { } }"; var src2 = typeKind + " C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void PropertyInitializerUpdate_InstanceCtorUpdate_Public(string typeKind) { var src1 = typeKind + " C { int a { get; } = 1; public C() { } }"; var src2 = typeKind + " C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorUpdate2() { var src1 = "class C { static int a; static C() { } }"; var src2 = "class C { static int a = 0; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_StaticCtorUpdate2() { var src1 = "class C { static int a { get; } = 1; static C() { } }"; var src2 = "class C { static int a { get; } = 2; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void FieldInitializerUpdate_InstanceCtorUpdate2(string typeKind) { var src1 = typeKind + " C { int a; public C() { } }"; var src2 = typeKind + " C { int a = 0; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@15 -> [a = 0]@15"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void PropertyInitializerUpdate_InstanceCtorUpdate2(string typeKind) { var src1 = typeKind + " C { int a { get; } = 1; public C() { } }"; var src2 = typeKind + " C { int a { get; } = 2; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate3() { var src1 = "class C { int a; }"; var src2 = "class C { int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate3() { var src1 = "class C { int a { get; } = 1; }"; var src2 = "class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate4() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [a]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate5() { var src1 = "class C { int a; private C(int a) { } private C(bool a) { } }"; var src2 = "class C { int a = 0; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), }); } [Fact] public void FieldInitializerUpdate_Struct_InstanceCtorUpdate5() { var src1 = "struct C { int a; private C(int a) { } private C(bool a) { } }"; var src2 = "struct C { int a = 0; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@15 -> [a = 0]@15"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C()"), preserveLocalVariables: true), }); } [Fact] public void PropertyInitializerUpdate_InstanceCtorUpdate5() { var src1 = "class C { int a { get; } = 1; private C(int a) { } private C(bool a) { } }"; var src2 = "class C { int a { get; } = 10000; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), }); } [Fact] public void PropertyInitializerUpdate_Struct_InstanceCtorUpdate5() { var src1 = "struct C { int a { get; } = 1; private C(int a) { } private C(bool a) { } }"; var src2 = "struct C { int a { get; } = 10000; private C(int a) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(int)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C()"), preserveLocalVariables: true), }); } [Fact] public void FieldInitializerUpdate_InstanceCtorUpdate6() { var src1 = "class C { int a; private C(int a) : this(true) { } private C(bool a) { } }"; var src2 = "class C { int a = 0; private C(int a) : this(true) { } private C(bool a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@14 -> [a = 0]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(m => m.ToString() == "C.C(bool)"), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_StaticCtorInsertImplicit() { var src1 = "class C { static int a; }"; var src2 = "class C { static int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Fact] public void FieldInitializerUpdate_StaticCtorInsertExplicit() { var src1 = "class C { static int a; }"; var src2 = "class C { static int a = 0; static C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [static C() { }]@28", "Insert [()]@36", "Update [a]@21 -> [a = 0]@21"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").StaticConstructors.Single()) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void FieldInitializerUpdate_InstanceCtorInsertExplicit(string typeKind) { var src1 = typeKind + " C { int a; }"; var src2 = typeKind + " C { int a = 0; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Theory] [InlineData("class ")] [InlineData("struct")] public void PropertyInitializerUpdate_InstanceCtorInsertExplicit(string typeKind) { var src1 = typeKind + " C { int a { get; } = 1; }"; var src2 = typeKind + " C { int a { get; } = 2; public C() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_GenericType() { var src1 = "class C<T> { int a = 1; }"; var src2 = "class C<T> { int a = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@17 -> [a = 2]@17"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "a = 2"), Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>")); } [Fact] public void PropertyInitializerUpdate_GenericType() { var src1 = "class C<T> { int a { get; } = 1; }"; var src2 = "class C<T> { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "int a"), Diagnostic(RudeEditKind.GenericTypeUpdate, "class C<T>")); } [Fact] public void FieldInitializerUpdate_StackAllocInConstructor() { var src1 = "unsafe class C { int a = 1; public C() { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a = 2; public C() { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@21 -> [a = 2]@21"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void FieldInitializerUpdate_SwitchExpressionInConstructor() { var src1 = "class C { int a = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor1() { var src1 = "unsafe class C { int a { get; } = 1; public C() { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); // TODO (tomat): diagnostic should point to the property initializer edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor2() { var src1 = "unsafe class C { int a { get; } = 1; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() : this(1) { int* a = stackalloc int[10]; } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_StackAllocInConstructor3() { var src1 = "unsafe class C { int a { get; } = 1; public C() { } public C(int b) { int* a = stackalloc int[10]; } }"; var src2 = "unsafe class C { int a { get; } = 2; public C() { } public C(int b) { int* a = stackalloc int[10]; } }"; var edits = GetTopEdits(src1, src2); // TODO (tomat): diagnostic should point to the property initializer edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", FeaturesResources.constructor)); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor1() { var src1 = "class C { int a { get; } = 1; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a { get; } = 2; public C() { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor2() { var src1 = "class C { int a { get; } = 1; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }"; var src2 = "class C { int a { get; } = 2; public C() : this(1) { var b = a switch { 0 => 0, _ => 1 }; } public C(int a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] [WorkItem(37172, "https://github.com/dotnet/roslyn/issues/37172")] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void PropertyInitializerUpdate_SwitchExpressionInConstructor3() { var src1 = "class C { int a { get; } = 1; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }"; var src2 = "class C { int a { get; } = 2; public C() { } public C(int b) { var b = a switch { 0 => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_LambdaInConstructor() { var src1 = "class C { int a = 1; public C() { F(() => {}); } static void F(System.Action a) {} }"; var src2 = "class C { int a = 2; public C() { F(() => {}); } static void F(System.Action a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@14 -> [a = 2]@14"); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_LambdaInConstructor() { var src1 = "class C { int a { get; } = 1; public C() { F(() => {}); } static void F(System.Action a) {} }"; var src2 = "class C { int a { get; } = 2; public C() { F(() => {}); } static void F(System.Action a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_QueryInConstructor() { var src1 = "using System.Linq; class C { int a = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var src2 = "using System.Linq; class C { int a = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@33 -> [a = 2]@33"); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_QueryInConstructor() { var src1 = "using System.Linq; class C { int a { get; } = 1; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var src2 = "using System.Linq; class C { int a { get; } = 2; public C() { F(from a in new[] {1,2,3} select a + 1); } static void F(System.Collections.Generic.IEnumerable<int> x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_AnonymousTypeInConstructor() { var src1 = "class C { int a = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var src2 = "class C { int a = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void PropertyInitializerUpdate_AnonymousTypeInConstructor() { var src1 = "class C { int a { get; } = 1; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var src2 = "class C { int a { get; } = 2; C() { F(new { A = 1, B = 2 }); } static void F(object x) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void FieldInitializerUpdate_PartialTypeWithSingleDeclaration() { var src1 = "partial class C { int a = 1; }"; var src2 = "partial class C { int a = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@22 -> [a = 2]@22"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_PartialTypeWithSingleDeclaration() { var src1 = "partial class C { int a { get; } = 1; }"; var src2 = "partial class C { int a { get; } = 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_PartialTypeWithMultipleDeclarations() { var src1 = "partial class C { int a = 1; } partial class C { }"; var src2 = "partial class C { int a = 2; } partial class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 1]@22 -> [a = 2]@22"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void PropertyInitializerUpdate_PartialTypeWithMultipleDeclarations() { var src1 = "partial class C { int a { get; } = 1; } partial class C { }"; var src2 = "partial class C { int a { get; } = 2; } partial class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), preserveLocalVariables: true) }); } [Fact] public void FieldInitializerUpdate_ParenthesizedLambda() { var src1 = "class C { int a = F(1, (x, y) => x + y); }"; var src2 = "class C { int a = F(2, (x, y) => x + y); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_ParenthesizedLambda() { var src1 = "class C { int a { get; } = F(1, (x, y) => x + y); }"; var src2 = "class C { int a { get; } = F(2, (x, y) => x + y); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_SimpleLambda() { var src1 = "class C { int a = F(1, x => x); }"; var src2 = "class C { int a = F(2, x => x); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_SimpleLambda() { var src1 = "class C { int a { get; } = F(1, x => x); }"; var src2 = "class C { int a { get; } = F(2, x => x); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_Query() { var src1 = "class C { int a = F(1, from goo in bar select baz); }"; var src2 = "class C { int a = F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_Query() { var src1 = "class C { int a { get; } = F(1, from goo in bar select baz); }"; var src2 = "class C { int a { get; } = F(2, from goo in bar select baz); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_AnonymousType() { var src1 = "class C { int a = F(1, new { A = 1, B = 2 }); }"; var src2 = "class C { int a = F(2, new { A = 1, B = 2 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyInitializerUpdate_AnonymousType() { var src1 = "class C { int a { get; } = F(1, new { A = 1, B = 2 }); }"; var src2 = "class C { int a { get; } = F(2, new { A = 1, B = 2 }); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_ImplicitCtor_EditInitializerWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 1; int B = F(<N:0.0>b => b + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 2; int B = F(<N:0.0>b => b + 1</N:0.0>); } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C() {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C() {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_CtorIncludingInitializers_EditInitializerWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 1; int B = F(<N:0.0>b => b + 1</N:0.0>); public C() {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = 2; int B = F(<N:0.0>b => b + 1</N:0.0>); public C() {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializers_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) {} public C(bool b) {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C(int a) {} public C(bool b) {} } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 2</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditInitializerWithLambda_Trivia1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 2</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithLambda_Trivia1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(<N:0.2>c => c + 1</N:0.2>); } public C(bool b) { F(d => d + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Int32 a)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_MultipleCtorsIncludingInitializersContainingLambdas_EditConstructorWithoutLambda1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_EditConstructorNotIncludingInitializers() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(2); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)")) }); } [Fact] public void FieldInitializerUpdate_Lambdas_RemoveCtorInitializer1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); unsafe public C(int a) { char* buffer = stackalloc char[16]; F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_AddCtorInitializer1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(a => a + 1); int B = F(b => b + 1); public C(int a) { F(c => c + 1); } public C(bool b) : this(1) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)")) }); } [Fact] public void FieldInitializerUpdate_Lambdas_UpdateBaseCtorInitializerWithLambdas1() { var src1 = @" using System; class B { public B(int a) { } } class C : B { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(bool b) : base(F(<N:0.2>c => c + 1</N:0.2>)) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var src2 = @" using System; class B { public B(int a) { } } class C : B { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(<N:0.1>b => b + 1</N:0.1>); public C(bool b) : base(F(<N:0.2>c => c + 2</N:0.2>)) { F(<N:0.3>d => d + 1</N:0.3>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(ctor => ctor.ToTestDisplayString() == "C..ctor(System.Boolean b)"), syntaxMap[0]) }); } [Fact] public void FieldInitializerUpdate_Lambdas_PartialDeclarationDelete_SingleDocument() { var src1 = @" partial class C { int x = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int y = F(<N:0.1>a => a + 10</N:0.1>); } partial class C { public C() { } static int F(Func<int, int> x) => 1; } "; var src2 = @" partial class C { int x = F(<N:0.0>a => a + 1</N:0.0>); } partial class C { int y = F(<N:0.1>a => a + 10</N:0.1>); static int F(Func<int, int> x) => 1; } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), syntaxMap[0]), }); } [Fact] public void FieldInitializerUpdate_ActiveStatements1() { var src1 = @" using System; class C { <AS:0>int A = <N:0.0>1</N:0.0>;</AS:0> int B = 1; public C(int a) { Console.WriteLine(1); } public C(bool b) { Console.WriteLine(1); } } "; var src2 = @" using System; class C { <AS:0>int A = <N:0.0>1</N:0.0>;</AS:0> int B = 2; public C(int a) { Console.WriteLine(1); } public C(bool b) { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); var activeStatements = GetActiveStatements(src1, src2); edits.VerifySemantics( activeStatements, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[0], syntaxMap[0]), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors[1], syntaxMap[0]), }); } [Fact] public void PropertyWithInitializer_SemanticError_Partial() { var src1 = @" partial class C { partial int P => 1; } partial class C { partial int P => 1; } "; var src2 = @" partial class C { partial int P => 1; } partial class C { partial int P => 2; public C() { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(ActiveStatementsDescription.Empty, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => ((IPropertySymbol)c.GetMember<INamedTypeSymbol>("C").GetMembers("P").First()).GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Partial_DeleteInsert_InitializerRemoval() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int F; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } [Fact] public void Field_Partial_DeleteInsert_InitializerUpdate() { var srcA1 = "partial class C { int F = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { int F = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }); } #endregion #region Fields [Fact] public void Field_Rename() { var src1 = "class C { int a = 0; }"; var src2 = "class C { int b = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a = 0]@14 -> [b = 0]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "b = 0", FeaturesResources.field)); } [Fact] public void Field_Kind_Update() { var src1 = "class C { Action a; }"; var src2 = "class C { event Action a; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Action a;]@10 -> [event Action a;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.FieldKindUpdate, "event Action a", FeaturesResources.event_)); } [Theory] [InlineData("static")] [InlineData("volatile")] [InlineData("const")] public void Field_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F = 0; }"; var src2 = "class C { " + newModifiers + "int F = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F = 0;]@10 -> [" + newModifiers + "int F = 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F = 0", FeaturesResources.field)); } [Fact] public void Field_Modifier_Add_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int F; }"; var srcA2 = "partial class C { static int F; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.ModifiersUpdate, "F", FeaturesResources.field) }), DocumentResults(), }); } [Fact] public void Field_Attribute_Add_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int F; }"; var srcA2 = "partial class C { [System.Obsolete]int F; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }), DocumentResults(), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_FixedSize_Update() { var src1 = "struct S { public unsafe fixed byte a[1], b[2]; }"; var src2 = "struct S { public unsafe fixed byte a[2], b[3]; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a[1]]@36 -> [a[2]]@36", "Update [b[2]]@42 -> [b[3]]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "a[2]", FeaturesResources.field), Diagnostic(RudeEditKind.FixedSizeFieldUpdate, "b[3]", FeaturesResources.field)); } [WorkItem(1120407, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1120407")] [Fact] public void Field_Const_Update() { var src1 = "class C { const int x = 0; }"; var src2 = "class C { const int x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [x = 0]@20 -> [x = 1]@20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, "x = 1", FeaturesResources.const_field)); } [Fact] public void Field_Event_VariableDeclarator_Update() { var src1 = "class C { event Action a; }"; var src2 = "class C { event Action a = () => { }; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [a]@23 -> [a = () => { }]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void Field_Reorder() { var src1 = "class C { int a = 0; int b = 1; int c = 2; }"; var src2 = "class C { int c = 2; int a = 0; int b = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int c = 2;]@32 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int c = 2", FeaturesResources.field)); } [Fact] public void Field_Insert() { var src1 = "class C { }"; var src2 = "class C { int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a = 1;]@10", "Insert [int a = 1]@10", "Insert [a = 1]@14"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true) }); } [Fact] public void Field_Insert_IntoStruct() { var src1 = @" struct S { public int a; public S(int z) { this = default(S); a = z; } } "; var src2 = @" struct S { public int a; private int b; private static int c; private static int f = 1; private event System.Action d; public S(int z) { this = default(S); a = z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "b", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "c", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "f = 1", FeaturesResources.field, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "d", CSharpFeaturesResources.event_field, CSharpFeaturesResources.struct_)); } [Fact] public void Field_Insert_IntoLayoutClass_Auto() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Auto)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Auto)] class C { private int a; private int b; private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.b")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.c")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.d")), }); } [Fact] public void Field_Insert_IntoLayoutClass_Explicit() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Explicit)] class C { [FieldOffset(0)] private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Explicit)] class C { [FieldOffset(0)] private int a; [FieldOffset(0)] private int b; [FieldOffset(4)] private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_)); } [Fact] public void Field_Insert_IntoLayoutClass_Sequential() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; private int b; private int c; private static int d; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "b", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "c", FeaturesResources.field, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "d", FeaturesResources.field, FeaturesResources.class_)); } [Fact] public void Field_Insert_WithInitializersAndLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C() { F(<N:0.1>c => c + 1</N:0.1>); } } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C() { F(<N:0.1>c => c + 1</N:0.1>); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact] public void Field_Insert_ConstructorReplacingImplicitConstructor_WithInitializersAndLambdas() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C() // new ctor replacing existing implicit constructor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ParameterlessConstructorInsert_WithInitializersAndLambdas() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C(int x) {} } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); public C(int x) {} public C() // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C()")); // TODO (bug https://github.com/dotnet/roslyn/issues/2504): //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] // { // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) // }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersAndLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(<N:0.0>a => a + 1</N:0.0>); int B = F(b => b + 1); // new field public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); _ = GetSyntaxMap(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, "public C(int x)")); // TODO (bug https://github.com/dotnet/roslyn/issues/2504): //edits.VerifySemantics( // ActiveStatementsDescription.Empty, // new[] // { // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), // SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<NamedTypeSymbol>("C").Constructors.Single(), syntaxMap[0]) // }); } [Fact, WorkItem(2504, "https://github.com/dotnet/roslyn/issues/2504")] public void Field_Insert_ConstructorInsert_WithInitializersButNoExistingLambdas1() { var src1 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(null); } "; var src2 = @" using System; class C { static int F(Func<int, int> x) => 1; int A = F(null); int B = F(b => b + 1); // new field public C(int x) // new ctor { F(c => c + 1); } } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.B")), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").Constructors.Single()) }); } [Fact] public void Field_Insert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { public int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddStaticFieldToExistingType, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field)); } [Fact] public void Field_Insert_Static_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { public static int a = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities | EditAndContinueCapabilities.AddInstanceFieldToExistingType, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "a = 1", FeaturesResources.field)); } [Fact] public void Field_Attribute_Add_NotSupportedByRuntime() { var src1 = @" class C { public int a = 1, x = 1; }"; var src2 = @" class C { [System.Obsolete]public int a = 1, x = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [public int a = 1, x = 1;]@18 -> [[System.Obsolete]public int a = 1, x = 1;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "public int a = 1, x = 1", FeaturesResources.field)); } [Fact] public void Field_Attribute_Add() { var src1 = @" class C { public int a, b; }"; var src2 = @" class C { [System.Obsolete]public int a, b; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.b")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Attribute_Add_WithInitializer() { var src1 = @" class C { int a; }"; var src2 = @" class C { [System.Obsolete]int a = 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), preserveLocalVariables: true), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Attribute_DeleteInsertUpdate_WithInitializer() { var srcA1 = "partial class C { int a = 1; }"; var srcB1 = "partial class C { }"; var srcA2 = "partial class C { }"; var srcB2 = "partial class C { [System.Obsolete]int a = 2; }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.a"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Delete1() { var src1 = "class C { int a = 1; }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a = 1;]@10", "Delete [int a = 1]@10", "Delete [a = 1]@14"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void Field_UnsafeModifier_Update() { var src1 = "struct Node { unsafe Node* left; }"; var src2 = "struct Node { Node* left; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [unsafe Node* left;]@14 -> [Node* left;]@14"); edits.VerifyRudeDiagnostics(); } [Fact] public void Field_ModifierAndType_Update() { var src1 = "struct Node { unsafe Node* left; }"; var src2 = "struct Node { Node left; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [unsafe Node* left;]@14 -> [Node left;]@14", "Update [Node* left]@21 -> [Node left]@14"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "Node left", FeaturesResources.field)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Field_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { " + oldType + " F, G; }"; var src2 = "class C { " + newType + " F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Field_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { " + oldType + " F, G; }"; var src2 = "class C { " + newType + " F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, newType + " F, G", FeaturesResources.field)); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Field_Event_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { event System.Action<" + oldType + "> F, G; }"; var src2 = "class C { event System.Action<" + newType + "> F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.G"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Field_Event_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { event System.Action<" + oldType + "> F, G; }"; var src2 = "class C { event System.Action<" + newType + "> F, G; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_), Diagnostic(RudeEditKind.TypeUpdate, "event System.Action<" + newType + "> F, G", FeaturesResources.event_)); } [Fact] public void Field_Type_Update_ReorderRemoveAdd() { var src1 = "class C { int F, G, H; bool U; }"; var src2 = "class C { string G, F; double V, U; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int F, G, H]@10 -> [string G, F]@10", "Reorder [G]@17 -> @17", "Update [bool U]@23 -> [double V, U]@23", "Insert [V]@30", "Delete [H]@20"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "G", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "string G, F", FeaturesResources.field), Diagnostic(RudeEditKind.TypeUpdate, "double V, U", FeaturesResources.field), Diagnostic(RudeEditKind.Delete, "string G, F", DeletedSymbolDisplay(FeaturesResources.field, "H"))); } [Fact] public void Field_Event_Reorder() { var src1 = "class C { int a = 0; int b = 1; event int c = 2; }"; var src2 = "class C { event int c = 2; int a = 0; int b = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [event int c = 2;]@32 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "event int c = 2", CSharpFeaturesResources.event_field)); } [Fact] public void Field_Event_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { event int E = 2; }"; var srcA2 = "partial class C { event int E = 2; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults(), }); } #endregion #region Properties [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Property_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int F => 0; }"; var src2 = "class C { " + newModifiers + "int F => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int F => 0;]@10 -> [" + newModifiers + "int F => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int F", FeaturesResources.property_)); } [Fact] public void Property_ExpressionBody_Rename() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int Q => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void Property_ExpressionBody_Update() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P => 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int P => 1;]@10 -> [int P => 2;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact, WorkItem(48628, "https://github.com/dotnet/roslyn/issues/48628")] public void Property_ExpressionBody_ModifierUpdate() { var src1 = "class C { int P => 1; }"; var src2 = "class C { unsafe int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [int P => 1;]@10 -> [unsafe int P => 1;]@10"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ExpressionBodyToBlockBody1() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get { return 2; } }]@10", "Insert [{ get { return 2; } }]@16", "Insert [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact] public void Property_ExpressionBodyToBlockBody2() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get { return 2; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get { return 2; } set { } }]@10", "Insert [{ get { return 2; } set { } }]@16", "Insert [get { return 2; }]@18", "Insert [set { }]@36"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_P"), preserveLocalVariables: false) }); } [Fact] public void Property_BlockBodyToExpressionBody1() { var src1 = "class C { int P { get { return 2; } } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get { return 2; } }]@10 -> [int P => 1;]@10", "Delete [{ get { return 2; } }]@16", "Delete [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact] public void Property_BlockBodyToExpressionBody2() { var src1 = "class C { int P { get { return 2; } set { } } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get { return 2; } set { } }]@10 -> [int P => 1;]@10", "Delete [{ get { return 2; } set { } }]@16", "Delete [get { return 2; }]@18", "Delete [set { }]@36"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_ExpressionBodyToGetterExpressionBody() { var src1 = "class C { int P => 1; }"; var src2 = "class C { int P { get => 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P => 1;]@10 -> [int P { get => 2; }]@10", "Insert [{ get => 2; }]@16", "Insert [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyToExpressionBody() { var src1 = "class C { int P { get => 2; } }"; var src2 = "class C { int P => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get => 2; }]@10 -> [int P => 1;]@10", "Delete [{ get => 2; }]@16", "Delete [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterBlockBodyToGetterExpressionBody() { var src1 = "class C { int P { get { return 2; } } }"; var src2 = "class C { int P { get => 2; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_SetterBlockBodyToSetterExpressionBody() { var src1 = "class C { int P { set { } } }"; var src2 = "class C { int P { set => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [set { }]@18 -> [set => F();]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_InitBlockBodyToInitExpressionBody() { var src1 = "class C { int P { init { } } }"; var src2 = "class C { int P { init => F(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [init { }]@18 -> [init => F();]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod, preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyToGetterBlockBody() { var src1 = "class C { int P { get => 2; } }"; var src2 = "class C { int P { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterBlockBodyWithSetterToGetterExpressionBodyWithSetter() { var src1 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }"; var src2 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 2;]@18 -> [get { return 2; }]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Property_GetterExpressionBodyWithSetterToGetterBlockBodyWithSetter() { var src1 = "class C { int P { get { return 2; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int P { get => 2; set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 2; }]@18 -> [get => 2;]@18"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_P"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_P"), preserveLocalVariables: false) }); } [Fact] public void Property_Rename1() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { int Q { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void Property_Rename2() { var src1 = "class C { int I.P { get { return 1; } } }"; var src2 = "class C { int J.P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int J.P", FeaturesResources.property_)); } [Fact] public void Property_RenameAndUpdate() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { int Q { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int Q", FeaturesResources.property_)); } [Fact] public void PropertyDelete() { var src1 = "class C { int P { get { return 1; } } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.property_, "P"))); } [Fact] public void PropertyReorder1() { var src1 = "class C { int P { get { return 1; } } int Q { get { return 1; } } }"; var src2 = "class C { int Q { get { return 1; } } int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int Q { get { return 1; } }]@38 -> @10"); // TODO: we can allow the move since the property doesn't have a backing field edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.property_)); } [Fact] public void PropertyReorder2() { var src1 = "class C { int P { get; set; } int Q { get; set; } }"; var src2 = "class C { int Q { get; set; } int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int Q { get; set; }]@30 -> @10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "int Q", FeaturesResources.auto_property)); } [Fact] public void PropertyAccessorReorder_GetSet() { var src1 = "class C { int P { get { return 1; } set { } } }"; var src2 = "class C { int P { set { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [set { }]@36 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyAccessorReorder_GetInit() { var src1 = "class C { int P { get { return 1; } init { } } }"; var src2 = "class C { int P { init { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [init { }]@36 -> @18"); edits.VerifyRudeDiagnostics(); } [Fact] public void PropertyTypeUpdate() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { char P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get; set; }]@10 -> [char P { get; set; }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "char P", FeaturesResources.property_)); } [Fact] public void PropertyUpdate_AddAttribute() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { [System.Obsolete]int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int P", FeaturesResources.property_)); } [Fact] public void PropertyUpdate_AddAttribute_SupportedByRuntime() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { [System.Obsolete]int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.P")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyAccessorUpdate_AddAttribute() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { [System.Obsolete]get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "get", CSharpFeaturesResources.property_getter)); } [Fact] public void PropertyAccessorUpdate_AddAttribute2() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; [System.Obsolete]set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "set", CSharpFeaturesResources.property_setter)); } [Fact] public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { [System.Obsolete]get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyAccessorUpdate_AddAttribute_SupportedByRuntime2() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; [System.Obsolete]set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void PropertyInsert() { var src1 = "class C { }"; var src2 = "class C { int P { get => 1; set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("P"))); } [Fact] public void PropertyInsert_NotSupportedByRuntime() { var src1 = "class C { }"; var src2 = "class C { int P { get => 1; set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.BaselineCapabilities, Diagnostic(RudeEditKind.InsertNotSupportedByRuntime, "int P", FeaturesResources.auto_property)); } [WorkItem(835827, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/835827")] [Fact] public void PropertyInsert_PInvoke() { var src1 = @" using System; using System.Runtime.InteropServices; class C { }"; var src2 = @" using System; using System.Runtime.InteropServices; class C { private static extern int P1 { [DllImport(""x.dll"")]get; } private static extern int P2 { [DllImport(""x.dll"")]set; } private static extern int P3 { [DllImport(""x.dll"")]get; [DllImport(""x.dll"")]set; } } "; var edits = GetTopEdits(src1, src2); // CLR doesn't support methods without a body edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertExtern, "private static extern int P1", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "private static extern int P2", FeaturesResources.property_), Diagnostic(RudeEditKind.InsertExtern, "private static extern int P3", FeaturesResources.property_)); } [Fact] public void PropertyInsert_IntoStruct() { var src1 = @" struct S { public int a; public S(int z) { a = z; } } "; var src2 = @" struct S { public int a; private static int c { get; set; } private static int e { get { return 0; } set { } } private static int g { get; } = 1; private static int i { get; set; } = 1; private static int k => 1; public S(int z) { a = z; } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoStruct, "private static int c { get; set; }", FeaturesResources.auto_property, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "private static int g { get; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_), Diagnostic(RudeEditKind.InsertIntoStruct, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, CSharpFeaturesResources.struct_)); } [Fact] public void PropertyInsert_IntoLayoutClass_Sequential() { var src1 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; } "; var src2 = @" using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private int a; private int b { get; set; } private static int c { get; set; } private int d { get { return 0; } set { } } private static int e { get { return 0; } set { } } private int f { get; } = 1; private static int g { get; } = 1; private int h { get; set; } = 1; private static int i { get; set; } = 1; private int j => 1; private static int k => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int b { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int c { get; set; }", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int f { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int g { get; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private int h { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_), Diagnostic(RudeEditKind.InsertIntoClassWithLayout, "private static int i { get; set; } = 1;", FeaturesResources.auto_property, FeaturesResources.class_)); } // Design: Adding private accessors should also be allowed since we now allow adding private methods // and adding public properties and/or public accessors are not allowed. [Fact] public void PrivateProperty_AccessorAdd() { var src1 = "class C { int _p; int P { get { return 1; } } }"; var src2 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { _p = value; }]@44"); edits.VerifyRudeDiagnostics(); } [WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")] [Fact] public void PrivatePropertyAccessorDelete() { var src1 = "class C { int _p; int P { get { return 1; } set { _p = value; } } }"; var src2 = "class C { int _p; int P { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set { _p = value; }]@44"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void PrivateAutoPropertyAccessorAdd1() { var src1 = "class C { int P { get; } }"; var src2 = "class C { int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd2() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; private set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [private set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd4() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd5() { var src1 = "class C { public int P { get; } }"; var src2 = "class C { public int P { get; internal set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [internal set;]@30"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd6() { var src1 = "class C { int P { get; } = 1; }"; var src2 = "class C { int P { get; set; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set;]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void PrivateAutoPropertyAccessorAdd_Init() { var src1 = "class C { int P { get; } = 1; }"; var src2 = "class C { int P { get; init; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [init;]@23"); edits.VerifyRudeDiagnostics(); } [WorkItem(755975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755975")] [Fact] public void PrivateAutoPropertyAccessorDelete_Get() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [get;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_getter, "P.get"))); } [Fact] public void AutoPropertyAccessor_SetToInit() { var src1 = "class C { int P { get; set; } }"; var src2 = "class C { int P { get; init; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [set;]@23 -> [init;]@23"); // not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq) edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "init", CSharpFeaturesResources.property_setter)); } [Fact] public void AutoPropertyAccessor_InitToSet() { var src1 = "class C { int P { get; init; } }"; var src2 = "class C { int P { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [init;]@23 -> [set;]@23"); // not allowed since it changes the backing field readonly-ness and the signature of the setter (modreq) edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter)); } [Fact] public void PrivateAutoPropertyAccessorDelete_Set() { var src1 = "class C { int P { get; set; } = 1; }"; var src2 = "class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set;]@23"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.set"))); } [Fact] public void PrivateAutoPropertyAccessorDelete_Init() { var src1 = "class C { int P { get; init; } = 1; }"; var src2 = "class C { int P { get; } = 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [init;]@23"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int P", DeletedSymbolDisplay(CSharpFeaturesResources.property_setter, "P.init"))); } [Fact] public void AutoPropertyAccessorUpdate() { var src1 = "class C { int P { get; } }"; var src2 = "class C { int P { set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get;]@18 -> [set;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.AccessorKindUpdate, "set", CSharpFeaturesResources.property_setter)); } [WorkItem(992578, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/992578")] [Fact] public void InsertIncompleteProperty() { var src1 = "class C { }"; var src2 = "class C { public int P { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [public int P { }]@10", "Insert [{ }]@23"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ReadOnlyRef_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int P { get; }]@13", "Insert [{ get; }]@32", "Insert [get;]@34"); edits.VerifyRudeDiagnostics(); } [Fact] public void Property_ReadOnlyRef_Update() { var src1 = "class Test { int P { get; } }"; var src2 = "class Test { ref readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int P { get; }]@13 -> [ref readonly int P { get; }]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int P", FeaturesResources.property_)); } [Fact] public void Property_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get => 1; set { } } }"; var srcA2 = "partial class C { int P { get => 1; set { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod) }), DocumentResults(), }); } [Fact] public void PropertyInit_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int Q { get => 1; init { } }}"; var srcA2 = "partial class C { int Q { get => 1; init { } }}"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod) }), DocumentResults(), }); } [Fact] public void AutoProperty_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get; set; } int Q { get; init; } }"; var srcA2 = "partial class C { int P { get; set; } int Q { get; init; } }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("Q").SetMethod), }), DocumentResults(), }); } [Fact] public void AutoPropertyWithInitializer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P { get; set; } = 1; }"; var srcA2 = "partial class C { int P { get; set; } = 1; }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").SetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").InstanceConstructors.Single(), partialType: "C", preserveLocalVariables: true) }), DocumentResults(), }); } [Fact] public void PropertyWithExpressionBody_Partial_InsertDeleteUpdate() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int P => 1; }"; var srcA2 = "partial class C { int P => 2; }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("P").GetMethod) }), DocumentResults(), }); } [Fact] public void AutoProperty_ReadOnly_Add() { var src1 = @" struct S { int P { get; } }"; var src2 = @" struct S { readonly int P { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Property_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { int P1 { get => 1; } int P2 { get => 1; set {}} int P3 { get => 1; set {}} int P4 { get => 1; set {}} }"; var src2 = @" struct S { readonly int P1 { get => 1; } int P2 { readonly get => 1; set {}} int P3 { get => 1; readonly set {}} readonly int P4 { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P1", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int P4", CSharpFeaturesResources.property_setter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.property_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.property_setter)); } [Fact] public void Property_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes var src1 = @" readonly struct S { int P1 { get => 1; } int P2 { get => 1; set {}} int P3 { get => 1; set {}} int P4 { get => 1; set {}} }"; var src2 = @" readonly struct S { readonly int P1 { get => 1; } int P2 { readonly get => 1; set {}} int P3 { get => 1; readonly set {}} readonly int P4 { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated edits.VerifySemantics(new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P2").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IPropertySymbol>("P3").SetMethod, preserveLocalVariables: false) }); } #endregion #region Indexers [Theory] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Indexer_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "int this[int a] => 0; }"; var src2 = "class C { " + newModifiers + "int this[int a] => 0; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "int this[int a] => 0;]@10 -> [" + newModifiers + "int this[int a] => 0;]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "int this[int a]", FeaturesResources.indexer_)); } [Fact] public void Indexer_GetterUpdate() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] { get { return 2; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [get { return 1; }]@28 -> [get { return 2; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_SetterUpdate() { var src1 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value); } } }"; var src2 = "class C { int this[int a] { get { return 1; } set { System.Console.WriteLine(value + 1); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [set { System.Console.WriteLine(value); }]@46 -> [set { System.Console.WriteLine(value + 1); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_InitUpdate() { var src1 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value); } } }"; var src2 = "class C { int this[int a] { get { return 1; } init { System.Console.WriteLine(value + 1); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [init { System.Console.WriteLine(value); }]@46 -> [init { System.Console.WriteLine(value + 1); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void IndexerWithExpressionBody_Update() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] => 2; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] => 2;]@10"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => a + 1)() + 10; } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => 2)() + 11; // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => a + 1)() + 10;]@35 -> [int this[int a] => new Func<int>(() => 2)() + 11;]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_2() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => a + 1)(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => 2)(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => a + 1)();]@35 -> [int this[int a] => new Func<int>(() => 2)();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_3() { var src1 = @" using System; class C { int this[int a] => new Func<int>(() => { return a + 1; })(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(() => { return 2; })(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(() => { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(() => { return 2; })();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Update_LiftedParameter_4() { var src1 = @" using System; class C { int this[int a] => new Func<int>(delegate { return a + 1; })(); } "; var src2 = @" using System; class C { int this[int a] => new Func<int>(delegate { return 2; })(); // not capturing a anymore }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => new Func<int>(delegate { return a + 1; })();]@35 -> [int this[int a] => new Func<int>(delegate { return 2; })();]@35"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a")); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToBlockBody() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } }]@10", "Insert [{ get { return 1; } }]@26", "Insert [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_BlockBodyToExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get { return 1; } }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get { return 1; } }]@26", "Delete [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToBlockBody() { var src1 = "class C { int this[int a] { get => 1; } }"; var src2 = "class C { int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_BlockBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } } }"; var src2 = "class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28"); edits.VerifyRudeDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToExpressionBody() { var src1 = "class C { int this[int a] { get => 1; } }"; var src2 = "class C { int this[int a] => 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get => 1; }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get => 1; }]@26", "Delete [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get => 1; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get => 1; }]@10", "Insert [{ get => 1; }]@26", "Insert [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterBlockBodyToGetterExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get { return 1; }]@28 -> [get => 1;]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_SetterBlockBodyToSetterExpressionBody() { var src1 = "class C { int this[int a] { set { } } void F() { } }"; var src2 = "class C { int this[int a] { set => F(); } void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [set { }]@28 -> [set => F();]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_InitBlockBodyToInitExpressionBody() { var src1 = "class C { int this[int a] { init { } } void F() { } }"; var src2 = "class C { int this[int a] { init => F(); } void F() { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [init { }]@28 -> [init => F();]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")), }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterExpressionBodyToGetterBlockBody() { var src1 = "class C { int this[int a] { get => 1; set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [get => 1;]@28 -> [get { return 1; }]@28"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_GetterAndSetterBlockBodiesToExpressionBody() { var src1 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var src2 = "class C { int this[int a] => 1; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10 -> [int this[int a] => 1;]@10", "Delete [{ get { return 1; } set { Console.WriteLine(0); } }]@26", "Delete [get { return 1; }]@28", "Delete [set { Console.WriteLine(0); }]@46"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "int this[int a]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int a].set"))); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Indexer_ExpressionBodyToGetterAndSetterBlockBodies() { var src1 = "class C { int this[int a] => 1; }"; var src2 = "class C { int this[int a] { get { return 1; } set { Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] => 1;]@10 -> [int this[int a] { get { return 1; } set { Console.WriteLine(0); } }]@10", "Insert [{ get { return 1; } set { Console.WriteLine(0); } }]@26", "Insert [get { return 1; }]@28", "Insert [set { Console.WriteLine(0); }]@46"); edits.VerifySemantics(ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.get_Item"), preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("C.set_Item"), preserveLocalVariables: false) }); } [Fact] public void Indexer_Rename() { var src1 = "class C { int I.this[int a] { get { return 1; } } }"; var src2 = "class C { int J.this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "int J.this[int a]", CSharpFeaturesResources.indexer)); } [Fact] public void Indexer_Reorder1() { var src1 = "class C { int this[int a] { get { return 1; } } int this[string a] { get { return 1; } } }"; var src2 = "class C { int this[string a] { get { return 1; } } int this[int a] { get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int this[string a] { get { return 1; } }]@48 -> @10"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_AccessorReorder() { var src1 = "class C { int this[int a] { get { return 1; } set { } } }"; var src2 = "class C { int this[int a] { set { } get { return 1; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [set { }]@46 -> @28"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_TypeUpdate() { var src1 = "class C { int this[int a] { get; set; } }"; var src2 = "class C { string this[int a] { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int a] { get; set; }]@10 -> [string this[int a] { get; set; }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "string this[int a]", CSharpFeaturesResources.indexer)); } [Fact] public void Tuple_TypeUpdate() { var src1 = "class C { (int, int) M() { throw new System.Exception(); } }"; var src2 = "class C { (string, int) M() { throw new System.Exception(); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) M() { throw new System.Exception(); }]@10 -> [(string, int) M() { throw new System.Exception(); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(string, int) M()", FeaturesResources.method)); } [Fact] public void TupleElementDelete() { var src1 = "class C { (int, int, int a) M() { return (1, 2, 3); } }"; var src2 = "class C { (int, int) M() { return (1, 2); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int, int a) M() { return (1, 2, 3); }]@10 -> [(int, int) M() { return (1, 2); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(int, int) M()", FeaturesResources.method)); } [Fact] public void TupleElementAdd() { var src1 = "class C { (int, int) M() { return (1, 2); } }"; var src2 = "class C { (int, int, int a) M() { return (1, 2, 3); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int, int) M() { return (1, 2); }]@10 -> [(int, int, int a) M() { return (1, 2, 3); }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "(int, int, int a) M()", FeaturesResources.method)); } [Fact] public void Indexer_ParameterUpdate() { var src1 = "class C { int this[int a] { get; set; } }"; var src2 = "class C { int this[string a] { get; set; } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "string a", FeaturesResources.parameter)); } [Fact] public void Indexer_AddGetAccessor() { var src1 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { set { arr[i] = value; } } }"; var src2 = @" class Test { static void Main(string[] args) { SampleCollection<string> stringCollection = new SampleCollection<string>(); stringCollection[0] = ""hello""; } } class SampleCollection<T> { private T[] arr = new T[100]; public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [get { return arr[i]; }]@304"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "get", CSharpFeaturesResources.indexer_getter)); } [Fact] public void Indexer_AddSetAccessor() { var src1 = @" class C { public int this[int i] { get { return default; } } }"; var src2 = @" class C { public int this[int i] { get { return default; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@67"); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod)); } [Fact] public void Indexer_AddSetAccessor_GenericType() { var src1 = @" class C<T> { public T this[int i] { get { return default; } } }"; var src2 = @" class C<T> { public T this[int i] { get { return default; } set { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [set { }]@68"); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.InsertIntoGenericType, "set", CSharpFeaturesResources.indexer_setter)); } [WorkItem(750109, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750109")] [Fact] public void Indexer_DeleteGetAccessor() { var src1 = @" class C<T> { public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } }"; var src2 = @" class C<T> { public T this[int i] { set { arr[i] = value; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [get { return arr[i]; }]@58"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public T this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_getter, "this[int i].get"))); } [Fact] public void Indexer_DeleteSetAccessor() { var src1 = @" class C { public int this[int i] { get { return 0; } set { } } }"; var src2 = @" class C { public int this[int i] { get { return 0; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [set { }]@61"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "public int this[int i]", DeletedSymbolDisplay(CSharpFeaturesResources.indexer_setter, "this[int i].set"))); } [Fact, WorkItem(1174850, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1174850")] public void Indexer_Insert() { var src1 = "struct C { }"; var src2 = "struct C { public int this[int x, int y] { get { return x + y; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_Parameter_InsertWhole() { var src1 = "class Test { }"; var src2 = "class Test { int this[in int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int this[in int i] => throw null;]@13", "Insert [[in int i]]@21", "Insert [in int i]@22"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_Parameter_Update() { var src1 = "class Test { int this[int i] => throw null; }"; var src2 = "class Test { int this[in int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int i]@22 -> [in int i]@22"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "in int i", FeaturesResources.parameter)); } [Fact] public void Indexer_ReadOnlyRef_ReturnType_Insert() { var src1 = "class Test { }"; var src2 = "class Test { ref readonly int this[int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [ref readonly int this[int i] => throw null;]@13", "Insert [[int i]]@34", "Insert [int i]@35"); edits.VerifyRudeDiagnostics(); } [Fact] public void Indexer_ReadOnlyRef_ReturnType_Update() { var src1 = "class Test { int this[int i] => throw null; }"; var src2 = "class Test { ref readonly int this[int i] => throw null; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int this[int i] => throw null;]@13 -> [ref readonly int this[int i] => throw null;]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, "ref readonly int this[int i]", FeaturesResources.indexer_)); } [Fact] public void Indexer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get => 1; set { } } }"; var srcA2 = "partial class C { int this[int x] { get => 1; set { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod) }), DocumentResults(), }); } [Fact] public void IndexerInit_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get => 1; init { } }}"; var srcA2 = "partial class C { int this[int x] { get => 1; init { } }}"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod) }), DocumentResults(), }); } [Fact] public void AutoIndexer_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { int this[int x] { get; set; } }"; var srcA2 = "partial class C { int this[int x] { get; set; } }"; var srcB2 = "partial class C { }"; // Accessors need to be updated even though they do not have an explicit body. // There is still a sequence point generated for them whose location needs to be updated. EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").GetMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IPropertySymbol>("this[]").SetMethod), }), DocumentResults(), }); } [Fact, WorkItem(51297, "https://github.com/dotnet/roslyn/issues/51297")] public void IndexerWithExpressionBody_Partial_InsertDeleteUpdate_LiftedParameter() { var srcA1 = @" partial class C { }"; var srcB1 = @" partial class C { int this[int a] => new System.Func<int>(() => a + 1); }"; var srcA2 = @" partial class C { int this[int a] => new System.Func<int>(() => 2); // no capture }"; var srcB2 = @" partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.NotCapturingVariable, "a", "a") }), DocumentResults(), }); } [Fact] public void AutoIndexer_ReadOnly_Add() { var src1 = @" struct S { int this[int x] { get; } }"; var src2 = @" struct S { readonly int this[int x] { get; } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter)); } [Fact] public void Indexer_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { int this[int x] { get => 1; } int this[uint x] { get => 1; set {}} int this[byte x] { get => 1; set {}} int this[sbyte x] { get => 1; set {}} }"; var src2 = @" struct S { readonly int this[int x] { get => 1; } int this[uint x] { readonly get => 1; set {}} int this[byte x] { get => 1; readonly set {}} readonly int this[sbyte x] { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[int x]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly int this[sbyte x]", CSharpFeaturesResources.indexer_setter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly get", CSharpFeaturesResources.indexer_getter), Diagnostic(RudeEditKind.ModifiersUpdate, "readonly set", CSharpFeaturesResources.indexer_setter)); } [Fact] public void Indexer_InReadOnlyStruct_ReadOnly_Add() { // indent to align accessor bodies and avoid updates caused by sequence point location changes var src1 = @" readonly struct S { int this[int x] { get => 1; } int this[uint x] { get => 1; set {}} int this[byte x] { get => 1; set {}} int this[sbyte x] { get => 1; set {}} }"; var src2 = @" readonly struct S { readonly int this[int x] { get => 1; } int this[uint x] { readonly get => 1; set {}} int this[byte x] { get => 1; readonly set {}} readonly int this[sbyte x] { get => 1; set {}} }"; var edits = GetTopEdits(src1, src2); // updates only for accessors whose modifiers were explicitly updated edits.VerifySemantics(new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "UInt32").GetMethod, preserveLocalVariables: false), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMembers("this[]").Cast<IPropertySymbol>().Single(m => m.Parameters.Single().Type.Name == "Byte").SetMethod, preserveLocalVariables: false) }); } #endregion #region Events [Theory] [InlineData("static")] [InlineData("virtual")] [InlineData("abstract")] [InlineData("override")] [InlineData("sealed override", "override")] public void Event_Modifiers_Update(string oldModifiers, string newModifiers = "") { if (oldModifiers != "") { oldModifiers += " "; } if (newModifiers != "") { newModifiers += " "; } var src1 = "class C { " + oldModifiers + "event Action F { add {} remove {} } }"; var src2 = "class C { " + newModifiers + "event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [" + oldModifiers + "event Action F { add {} remove {} }]@10 -> [" + newModifiers + "event Action F { add {} remove {} }]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, newModifiers + "event Action F", FeaturesResources.event_)); } [Fact] public void Event_Accessor_Reorder1() { var src1 = "class C { event int E { add { } remove { } } }"; var src2 = "class C { event int E { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [remove { }]@32 -> @24"); edits.VerifyRudeDiagnostics(); } [Fact] public void Event_Accessor_Reorder2() { var src1 = "class C { event int E1 { add { } remove { } } event int E1 { add { } remove { } } }"; var src2 = "class C { event int E2 { remove { } add { } } event int E2 { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event int E1 { add { } remove { } }]@10 -> [event int E2 { remove { } add { } }]@10", "Update [event int E1 { add { } remove { } }]@49 -> [event int E2 { remove { } add { } }]@49", "Reorder [remove { }]@33 -> @25", "Reorder [remove { }]@72 -> @64"); } [Fact] public void Event_Accessor_Reorder3() { var src1 = "class C { event int E1 { add { } remove { } } event int E2 { add { } remove { } } }"; var src2 = "class C { event int E2 { remove { } add { } } event int E1 { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [event int E2 { add { } remove { } }]@49 -> @10", "Reorder [remove { }]@72 -> @25", "Reorder [remove { }]@33 -> @64"); } [Fact] public void Event_Insert() { var src1 = "class C { }"; var src2 = "class C { event int E { remove { } add { } } }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Insert, c => c.GetMember<INamedTypeSymbol>("C").GetMember("E"))); } [Fact] public void Event_Delete() { var src1 = "class C { event int E { remove { } add { } } }"; var src2 = "class C { }"; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.event_, "E"))); } [Fact] public void Event_Insert_IntoLayoutClass_Sequential() { var src1 = @" using System; using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { } "; var src2 = @" using System; using System.Runtime.InteropServices; [StructLayoutAttribute(LayoutKind.Sequential)] class C { private event Action c { add { } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Event_ExpressionBodyToBlockBody() { var src1 = @" using System; public class C { event Action E { add => F(); remove => F(); } } "; var src2 = @" using System; public class C { event Action E { add { F(); } remove { } } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [add => F();]@57 -> [add { F(); }]@56", "Update [remove => F();]@69 -> [remove { }]@69" ); edits.VerifySemanticDiagnostics(); } [Fact, WorkItem(17681, "https://github.com/dotnet/roslyn/issues/17681")] public void Event_BlockBodyToExpressionBody() { var src1 = @" using System; public class C { event Action E { add { F(); } remove { } } } "; var src2 = @" using System; public class C { event Action E { add => F(); remove => F(); } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [add { F(); }]@56 -> [add => F();]@57", "Update [remove { }]@69 -> [remove => F();]@69" ); edits.VerifySemanticDiagnostics(); } [Fact] public void Event_Partial_InsertDelete() { var srcA1 = "partial class C { }"; var srcB1 = "partial class C { event int E { add { } remove { } } }"; var srcA2 = "partial class C { event int E { add { } remove { } } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember<IEventSymbol>("E").RemoveMethod) }), DocumentResults(), }); } [Fact] public void Event_InMutableStruct_ReadOnly_Add() { var src1 = @" struct S { public event Action E { add {} remove {} } }"; var src2 = @" struct S { public readonly event Action E { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "public readonly event Action E", FeaturesResources.event_)); } [Fact] public void Event_InReadOnlyStruct_ReadOnly_Add1() { var src1 = @" readonly struct S { public event Action E { add {} remove {} } }"; var src2 = @" readonly struct S { public readonly event Action E { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); // Currently, an edit is produced eventhough bodies nor IsReadOnly attribute have changed. Consider improving. edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("S").GetMember<IEventSymbol>("E").RemoveMethod)); } [Fact] public void Field_Event_Attribute_Add() { var src1 = @" class C { event Action F; }"; var src2 = @" class C { [System.Obsolete]event Action F; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event Action F;]@18 -> [[System.Obsolete]event Action F;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Attribute_Add() { var src1 = @" class C { event Action F { add {} remove {} } }"; var src2 = @" class C { [System.Obsolete]event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [event Action F { add {} remove {} }]@18 -> [[System.Obsolete]event Action F { add {} remove {} }]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Accessor_Attribute_Add() { var src1 = @" class C { event Action F { add {} remove {} } }"; var src2 = @" class C { event Action F { add {} [System.Obsolete]remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [remove {}]@42 -> [[System.Obsolete]remove {}]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "remove", FeaturesResources.event_accessor)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Field_Event_Attribute_Delete() { var src1 = @" class C { [System.Obsolete]event Action F; }"; var src2 = @" class C { event Action F; }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]event Action F;]@18 -> [event Action F;]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Attribute_Delete() { var src1 = @" class C { [System.Obsolete]event Action F { add {} remove {} } }"; var src2 = @" class C { event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]event Action F { add {} remove {} }]@18 -> [event Action F { add {} remove {} }]@18"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "event Action F", FeaturesResources.event_)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F")), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").AddMethod), SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Event_Accessor_Attribute_Delete() { var src1 = @" class C { event Action F { add {} [System.Obsolete]remove {} } }"; var src2 = @" class C { event Action F { add {} remove {} } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete]remove {}]@42 -> [remove {}]@42"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "remove", FeaturesResources.event_accessor)); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<IEventSymbol>("C.F").RemoveMethod) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Parameter [Fact] public void ParameterRename_Method1() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [int b]@24"); } [Fact] public void ParameterRename_Ctor1() { var src1 = @"class C { public C(int a) {} }"; var src2 = @"class C { public C(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@19 -> [int b]@19"); } [Fact] public void ParameterRename_Operator1() { var src1 = @"class C { public static implicit operator int(C a) {} }"; var src2 = @"class C { public static implicit operator int(C b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [C a]@46 -> [C b]@46"); } [Fact] public void ParameterRename_Operator2() { var src1 = @"class C { public static int operator +(C a, C b) { return 0; } }"; var src2 = @"class C { public static int operator +(C a, C x) { return 0; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [C b]@44 -> [C x]@44"); } [Fact] public void ParameterRename_Indexer2() { var src1 = @"class C { public int this[int a, int b] { get { return 0; } } }"; var src2 = @"class C { public int this[int a, int x] { get { return 0; } } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int b]@33 -> [int x]@33"); } [Fact] public void ParameterInsert1() { var src1 = @"class C { public void M() {} }"; var src2 = @"class C { public void M(int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [int a]@24"); } [Fact] public void ParameterInsert2() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int a, ref int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a)]@23 -> [(int a, ref int b)]@23", "Insert [ref int b]@31"); } [Fact] public void ParameterDelete1() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [int a]@24"); } [Fact] public void ParameterDelete2() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [(int a, int b)]@23 -> [(int b)]@23", "Delete [int a]@24"); } [Fact] public void ParameterUpdate() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M(int b) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [int b]@24"); } [Fact] public void ParameterReorder() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b, int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int b]@31 -> @24"); } [Fact] public void ParameterReorderAndUpdate() { var src1 = @"class C { public void M(int a, int b) {} }"; var src2 = @"class C { public void M(int b, int c) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [int b]@31 -> @24", "Update [int a]@24 -> [int c]@31"); } [Theory] [InlineData("string", "string?")] [InlineData("object", "dynamic")] [InlineData("(int a, int b)", "(int a, int c)")] public void Parameter_Type_Update_RuntimeTypeUnchanged(string oldType, string newType) { var src1 = "class C { static void M(" + oldType + " a) {} }"; var src2 = "class C { static void M(" + newType + " a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifySemantics( SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M"))); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void Parameter_Type_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C { static void M(" + oldType + " a) {} }"; var src2 = "class C { static void M(" + newType + " a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.TypeUpdate, newType + " a", FeaturesResources.parameter)); } [Fact] public void Parameter_Type_Nullable() { var src1 = @" #nullable enable class C { static void M(string a) { } } "; var src2 = @" #nullable disable class C { static void M(string a) { } } "; var edits = GetTopEdits(src1, src2); edits.VerifySemantics(); } [Theory] [InlineData("this")] [InlineData("ref")] [InlineData("out")] [InlineData("params")] public void Parameter_Modifier_Remove(string modifier) { var src1 = @"static class C { static void F(" + modifier + " int[] a) { } }"; var src2 = @"static class C { static void F(int[] a) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ModifiersUpdate, "int[] a", FeaturesResources.parameter)); } [Theory] [InlineData("int a = 1", "int a = 2")] [InlineData("int a = 1", "int a")] [InlineData("int a", "int a = 2")] [InlineData("object a = null", "object a")] [InlineData("object a", "object a = null")] [InlineData("double a = double.NaN", "double a = 1.2")] public void Parameter_Initializer_Update(string oldParameter, string newParameter) { var src1 = @"static class C { static void F(" + oldParameter + ") { } }"; var src2 = @"static class C { static void F(" + newParameter + ") { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.InitializerUpdate, newParameter, FeaturesResources.parameter)); } [Fact] public void Parameter_Initializer_NaN() { var src1 = @"static class C { static void F(double a = System.Double.NaN) { } }"; var src2 = @"static class C { static void F(double a = double.NaN) { } }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics(); } [Fact] public void Parameter_Initializer_InsertDeleteUpdate() { var srcA1 = @"partial class C { }"; var srcB1 = @"partial class C { public static void F(int x = 1) {} }"; var srcA2 = @"partial class C { public static void F(int x = 2) {} }"; var srcB2 = @"partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( diagnostics: new[] { Diagnostic(RudeEditKind.InitializerUpdate, "int x = 2", FeaturesResources.parameter) }), DocumentResults(), }); } [Fact] public void Parameter_Attribute_Insert() { var attribute = "public class A : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@63 -> [[A]int a]@63"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.M")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_NonCustomAttribute() { var src1 = @"class C { public void M(int a) {} }"; var src2 = @"class C { public void M([System.Runtime.InteropServices.InAttribute]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@24 -> [[System.Runtime.InteropServices.InAttribute]int a]@24"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute1() { var attribute = "public class AAttribute : System.Security.Permissions.SecurityAttribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@101 -> [[A]int a]@101"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_SupportedByRuntime_SecurityAttribute2() { var attribute = "public class BAttribute : System.Security.Permissions.SecurityAttribute { }\n\n" + "public class AAttribute : BAttribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@143 -> [[A]int a]@143"); edits.VerifyRudeDiagnostics( capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_NotSupportedByRuntime1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M(int a) {} }"; var src2 = attribute + @"class C { public void M([A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a]@72 -> [[A]int a]@72"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Insert_NotSupportedByRuntime2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([A]int a) {} }"; var src2 = attribute + @"class C { public void M([A, B]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]int a]@120 -> [[A, B]int a]@120"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Delete_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([A]int a) {} }"; var src2 = attribute + @"class C { public void M(int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]int a]@72 -> [int a]@72"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Update_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M([System.Obsolete(""1""), B]int a) {} }"; var src2 = attribute + @"class C { public void M([System.Obsolete(""2""), A]int a) {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]int a]@120 -> [[System.Obsolete(\"2\"), A]int a]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "int a", FeaturesResources.parameter)); } [Fact] public void Parameter_Attribute_Update() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F([A(0)]int a) {} }"; var src2 = attribute + "class C { void F([A(1)]int a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(0)]int a]@67 -> [[A(1)]int a]@67"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Parameter_Attribute_Update_WithBodyUpdate() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F([A(0)]int a) { F(0); } }"; var src2 = attribute + "class C { void F([A(1)]int a) { F(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void F([A(0)]int a) { F(0); }]@60 -> [void F([A(1)]int a) { F(1); }]@60", "Update [[A(0)]int a]@67 -> [[A(1)]int a]@67"); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.F")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Method Type Parameter [Fact] public void MethodTypeParameterInsert1() { var src1 = @"class C { public void M() {} }"; var src2 = @"class C { public void M<A>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@23", "Insert [A]@24"); } [Fact] public void MethodTypeParameterInsert2() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M<A,B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@23 -> [<A,B>]@23", "Insert [B]@26"); } [Fact] public void MethodTypeParameterDelete1() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@23", "Delete [A]@24"); } [Fact] public void MethodTypeParameterDelete2() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@23 -> [<B>]@23", "Delete [A]@24"); } [Fact] public void MethodTypeParameterUpdate() { var src1 = @"class C { public void M<A>() {} }"; var src2 = @"class C { public void M<B>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [A]@24 -> [B]@24"); } [Fact] public void MethodTypeParameterReorder() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B,A>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@26 -> @24"); } [Fact] public void MethodTypeParameterReorderAndUpdate() { var src1 = @"class C { public void M<A,B>() {} }"; var src2 = @"class C { public void M<B,C>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@26 -> @24", "Update [A]@24 -> [C]@26"); } [Fact] public void MethodTypeParameter_Attribute_Insert1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<T>() {} }"; var src2 = attribute + @"class C { public void M<[A]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@72 -> [[A]T]@72"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T"), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method)); } [Fact] public void MethodTypeParameter_Attribute_Insert2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[A]T>() {} }"; var src2 = attribute + @"class C { public void M<[A, B]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@120 -> [[A, B]T]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T"), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method)); } [Fact] public void MethodTypeParameter_Attribute_Delete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[A]T>() {} }"; var src2 = attribute + @"class C { public void M<T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@72 -> [T]@72"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodTriviaUpdate, "", FeaturesResources.method), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update_NotSupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C { public void M<[System.Obsolete(""1""), B]T>() {} }"; var src2 = attribute + @"class C { public void M<[System.Obsolete(""2""), A]T>() {} } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]T]@120 -> [[System.Obsolete(\"2\"), A]T]@120"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F<[A(0)]T>(T a) {} }"; var src2 = attribute + "class C { void F<[A(1)]T>(T a) {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A(0)]T]@67 -> [[A(1)]T]@67"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } [Fact] public void MethodTypeParameter_Attribute_Update_WithBodyUpdate() { var attribute = "class A : System.Attribute { public A(int x) {} } "; var src1 = attribute + "class C { void F<[A(0)]T>(T a) { F(0); } }"; var src2 = attribute + "class C { void F<[A(1)]T>(T a) { F(1); } }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [void F<[A(0)]T>(T a) { F(0); }]@60 -> [void F<[A(1)]T>(T a) { F(1); }]@60", "Update [[A(0)]T]@67 -> [[A(1)]T]@67"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericMethodUpdate, "void F<[A(1)]T>(T a)"), Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericMethodUpdate, "T")); } #endregion #region Type Type Parameter [Fact] public void TypeTypeParameterInsert1() { var src1 = @"class C {}"; var src2 = @"class C<A> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [<A>]@7", "Insert [A]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "A", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterInsert2() { var src1 = @"class C<A> {}"; var src2 = @"class C<A,B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A>]@7 -> [<A,B>]@7", "Insert [B]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "B", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterDelete1() { var src1 = @"class C<A> { }"; var src2 = @"class C { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [<A>]@7", "Delete [A]@8"); } [Fact] public void TypeTypeParameterDelete2() { var src1 = @"class C<A,B> {}"; var src2 = @"class C<B> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [<A,B>]@7 -> [<B>]@7", "Delete [A]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C<B>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "A"))); } [Fact] public void TypeTypeParameterUpdate() { var src1 = @"class C<A> {}"; var src2 = @"class C<B> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [A]@8 -> [B]@8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Renamed, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "B")); } [Fact] public void TypeTypeParameterReorder() { var src1 = @"class C<A,B> { }"; var src2 = @"class C<B,A> { } "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@10 -> @8"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter)); } [Fact] public void TypeTypeParameterReorderAndUpdate() { var src1 = @"class C<A,B> {}"; var src2 = @"class C<B,C> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [B]@10 -> @8", "Update [A]@8 -> [C]@10"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "B", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.Renamed, "C", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "C")); } [Fact] public void TypeTypeParameterAttributeInsert1() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<T> {}"; var src2 = attribute + @"class C<[A]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@56 -> [[A]T]@56"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeInsert2() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[A]T> {}"; var src2 = attribute + @"class C<[A, B]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@104 -> [[A, B]T]@104"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeInsert_SupportedByRuntime() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<T> {}"; var src2 = attribute + @"class C<[A]T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [T]@56 -> [[A]T]@56"); edits.VerifyRudeDiagnostics( EditAndContinueTestHelpers.Net6RuntimeCapabilities, Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeDelete() { var attribute = "public class AAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[A]T> {}"; var src2 = attribute + @"class C<T> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[A]T]@56 -> [T]@56"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameterAttributeUpdate() { var attribute = "public class AAttribute : System.Attribute { }\n\n" + "public class BAttribute : System.Attribute { }\n\n"; var src1 = attribute + @"class C<[System.Obsolete(""1""), B]T> {}"; var src2 = attribute + @"class C<[System.Obsolete(""2""), A]T> {} "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [[System.Obsolete(\"1\"), B]T]@104 -> [[System.Obsolete(\"2\"), A]T]@104"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingAttributesNotSupportedByRuntime, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = "partial class C<T> { }" + attributes; var srcB1 = "partial class C<T> { }"; var srcA2 = "partial class C<[A]T> { }" + attributes; var srcB2 = "partial class C<[B]T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }), DocumentResults(diagnostics: new[] { Diagnostic(RudeEditKind.GenericTypeUpdate, "T"), }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void TypeTypeParameter_Partial_Attribute_AddMultiple_Reloadable() { var attributes = @" class A : System.Attribute {} class B : System.Attribute {} "; var srcA1 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<T> { }" + attributes; var srcB1 = "partial class C<T> { }"; var srcA2 = ReloadableAttributeSrc + "[CreateNewOnMetadataUpdate]partial class C<[A]T> { }" + attributes; var srcB2 = "partial class C<[B]T> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), DocumentResults(semanticEdits: new[] { SemanticEdit(SemanticEditKind.Replace, c => c.GetMember("C"), partialType: "C") }), }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } #endregion #region Type Parameter Constraints [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void TypeConstraint_Insert(string newConstraint) { var src1 = "class C<S,T> { }"; var src2 = "class C<S,T> where T : " + newConstraint + " { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [where T : " + newConstraint + "]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where T : " + newConstraint, FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : " + newConstraint)); } [Theory] [InlineData("nonnull")] [InlineData("struct")] [InlineData("class")] [InlineData("new()")] [InlineData("unmanaged")] [InlineData("System.IDisposable")] [InlineData("System.Delegate")] public void TypeConstraint_Delete(string oldConstraint) { var src1 = "class C<S,T> where T : " + oldConstraint + " { }"; var src2 = "class C<S,T> { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [where T : " + oldConstraint + "]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "T")); } [Theory] [InlineData("string", "string?")] [InlineData("(int a, int b)", "(int a, int c)")] public void TypeConstraint_Update_RuntimeTypeUnchanged(string oldType, string newType) { // note: dynamic is not allowed in constraints var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">")); } [Theory] [InlineData("int", "string")] [InlineData("int", "int?")] [InlineData("(int a, int b)", "(int a, double b)")] public void TypeConstraint_Update_RuntimeTypeChanged(string oldType, string newType) { var src1 = "class C<T> where T : System.Collections.Generic.List<" + oldType + "> {}"; var src2 = "class C<T> where T : System.Collections.Generic.List<" + newType + "> {}"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where T : System.Collections.Generic.List<" + newType + ">", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : System.Collections.Generic.List<" + newType + ">")); } [Fact] public void TypeConstraint_Delete_WithParameter() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<S> where S : new() { }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, "class C<S>", DeletedSymbolDisplay(FeaturesResources.type_parameter, "T"))); } [Fact] public void TypeConstraint_MultipleClauses_Insert() { var src1 = "class C<S,T> where T : class { }"; var src2 = "class C<S,T> where S : unmanaged where T : class { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Insert [where S : unmanaged]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "where S : unmanaged", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : unmanaged")); } [Fact] public void TypeConstraint_MultipleClauses_Delete() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<S,T> where T : class { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Delete [where S : new()]@13"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangingConstraints, "S", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "S")); } [Fact] public void TypeConstraint_MultipleClauses_Reorder() { var src1 = "class C<S,T> where S : struct where T : class { }"; var src2 = "class C<S,T> where T : class where S : struct { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [where T : class]@30 -> @13"); edits.VerifyRudeDiagnostics(); } [Fact] public void TypeConstraint_MultipleClauses_UpdateAndReorder() { var src1 = "class C<S,T> where S : new() where T : class { }"; var src2 = "class C<T,S> where T : class, I where S : class, new() { }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Reorder [where T : class]@29 -> @13", "Reorder [T]@10 -> @8", "Update [where T : class]@29 -> [where T : class, I]@13", "Update [where S : new()]@13 -> [where S : class, new()]@32"); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Move, "T", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.ChangingConstraints, "where T : class, I", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where T : class, I"), Diagnostic(RudeEditKind.ChangingConstraints, "where S : class, new()", FeaturesResources.type_parameter), Diagnostic(RudeEditKind.GenericTypeUpdate, "where S : class, new()")); } #endregion #region Top Level Statements [Fact] public void TopLevelStatements_Update() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_InsertAndUpdate() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello World""); Console.WriteLine(""What is your name?""); var name = Console.ReadLine(); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [Console.WriteLine(\"Hello\");]@19 -> [Console.WriteLine(\"Hello World\");]@19", "Insert [Console.WriteLine(\"What is your name?\");]@54", "Insert [var name = Console.ReadLine();]@96"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Insert_NoImplicitMain() { var src1 = @" using System; "; var src2 = @" using System; Console.WriteLine(""Hello World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"Hello World\");]@19"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Insert, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Insert_ImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello""); "; var src2 = @" using System; Console.WriteLine(""Hello""); Console.WriteLine(""World""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Insert [Console.WriteLine(\"World\");]@48"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_Delete_NoImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello World""); "; var src2 = @" using System; "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"Hello World\");]@19"); edits.VerifyRudeDiagnostics(Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.global_statement)); } [Fact] public void TopLevelStatements_Delete_ImplicitMain() { var src1 = @" using System; Console.WriteLine(""Hello""); Console.WriteLine(""World""); "; var src2 = @" using System; Console.WriteLine(""Hello""); "; var edits = GetTopEdits(src1, src2); edits.VerifyEdits("Delete [Console.WriteLine(\"World\");]@48"); edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_StackAlloc() { var src1 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(1); }"; var src2 = @"unsafe { var x = stackalloc int[3]; System.Console.Write(2); }"; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.StackAllocUpdate, "stackalloc", CSharpFeaturesResources.global_statement)); } [Fact] public void TopLevelStatements_VoidToInt1() { var src1 = @" using System; Console.Write(1); "; var src2 = @" using System; Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToInt2() { var src1 = @" using System; Console.Write(1); return; "; var src2 = @" using System; Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToInt3() { var src1 = @" using System; Console.Write(1); int Goo() { return 1; } "; var src2 = @" using System; Console.Write(1); return 1; int Goo() { return 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_AddAwait() { var src1 = @" using System.Threading.Tasks; await Task.Delay(100); "; var src2 = @" using System.Threading.Tasks; await Task.Delay(100); await Task.Delay(200); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Insert, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_DeleteAwait() { var src1 = @" using System.Threading.Tasks; await Task.Delay(100); await Task.Delay(200); "; var src2 = @" using System.Threading.Tasks; await Task.Delay(100); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_VoidToTask() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "await Task.Delay(100);")); } [Fact] public void TopLevelStatements_TaskToTaskInt() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); return 1; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return 1;")); } [Fact] public void TopLevelStatements_VoidToTaskInt() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); return await GetInt(); Task<int> GetInt() { return Task.FromResult(1); } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return await GetInt();")); } [Fact] public void TopLevelStatements_IntToVoid1() { var src1 = @" using System; Console.Write(1); return 1; "; var src2 = @" using System; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_IntToVoid2() { var src1 = @" using System; Console.Write(1); return 1; "; var src2 = @" using System; Console.Write(1); return; "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "return;")); } [Fact] public void TopLevelStatements_IntToVoid3() { var src1 = @" using System; Console.Write(1); return 1; int Goo() { return 1; } "; var src2 = @" using System; Console.Write(1); int Goo() { return 1; } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "int Goo()\r\n{\r\n return 1;\r\n}")); } [Fact] public void TopLevelStatements_IntToVoid4() { var src1 = @" using System; Console.Write(1); return 1; public class C { public int Goo() { return 1; } } "; var src2 = @" using System; Console.Write(1); public class C { public int Goo() { return 1; } } "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_TaskToVoid() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"), Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_TaskIntToTask() { var src1 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); return 1; "; var src2 = @" using System; using System.Threading.Tasks; await Task.Delay(100); Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);")); } [Fact] public void TopLevelStatements_TaskIntToVoid() { var src1 = @" using System; using System.Threading.Tasks; Console.Write(1); return await GetInt(); Task<int> GetInt() { return Task.FromResult(1); } "; var src2 = @" using System; using System.Threading.Tasks; Console.Write(1); "; var edits = GetTopEdits(src1, src2); edits.VerifyRudeDiagnostics( Diagnostic(RudeEditKind.ChangeImplicitMainReturnType, "Console.Write(1);"), Diagnostic(RudeEditKind.Delete, null, CSharpFeaturesResources.await_expression)); } [Fact] public void TopLevelStatements_WithLambda_Insert() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_WithLambda_Update() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); public class C { } "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(2); public class C { } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_WithLambda_Delete() { var src1 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; Console.WriteLine(1); public class C { } "; var src2 = @" using System; Func<int> a = () => { <N:0.0>return 1;</N:0.0> }; Func<Func<int>> b = () => () => { <N:0.1>return 1;</N:0.1> }; public class C { } "; var edits = GetTopEdits(src1, src2); var syntaxMap = GetSyntaxMap(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"), syntaxMap[0]) }); } [Fact] public void TopLevelStatements_UpdateMultiple() { var src1 = @" using System; Console.WriteLine(1); Console.WriteLine(2); public class C { } "; var src2 = @" using System; Console.WriteLine(3); Console.WriteLine(4); public class C { } "; var edits = GetTopEdits(src1, src2); // Since each individual statement is a separate update to a separate node, this just validates we correctly // only analyze the things once edits.VerifySemantics(SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$"))); } [Fact] public void TopLevelStatements_MoveToOtherFile() { var srcA1 = @" using System; Console.WriteLine(1); public class A { }"; var srcB1 = @" using System; public class B { }"; var srcA2 = @" using System; public class A { }"; var srcB2 = @" using System; Console.WriteLine(2); public class B { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults(), DocumentResults(semanticEdits: new [] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Program.<Main>$")) }), }); } #endregion } }
1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Features/CSharp/Portable/EditAndContinue/CSharpEditAndContinueAnalyzer.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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue { internal sealed class CSharpEditAndContinueAnalyzer : AbstractEditAndContinueAnalyzer { [ExportLanguageServiceFactory(typeof(IEditAndContinueAnalyzer), LanguageNames.CSharp), Shared] internal sealed class Factory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) { return new CSharpEditAndContinueAnalyzer(testFaultInjector: null); } } // Public for testing purposes public CSharpEditAndContinueAnalyzer(Action<SyntaxNode>? testFaultInjector = null) : base(testFaultInjector) { } #region Syntax Analysis private enum BlockPart { OpenBrace = DefaultStatementPart, CloseBrace = 1, } private enum ForEachPart { ForEach = DefaultStatementPart, VariableDeclaration = 1, In = 2, Expression = 3, } private enum SwitchExpressionPart { WholeExpression = DefaultStatementPart, // An active statement that covers IL generated for the decision tree: // <governing-expression> [|switch { <arm>, ..., <arm> }|] // This active statement is never a leaf active statement (does not correspond to a breakpoint span). SwitchBody = 1, } /// <returns> /// <see cref="BaseMethodDeclarationSyntax"/> for methods, operators, constructors, destructors and accessors. /// <see cref="VariableDeclaratorSyntax"/> for field initializers. /// <see cref="PropertyDeclarationSyntax"/> for property initializers and expression bodies. /// <see cref="IndexerDeclarationSyntax"/> for indexer expression bodies. /// <see cref="ArrowExpressionClauseSyntax"/> for getter of an expression-bodied property/indexer. /// </returns> internal override bool TryFindMemberDeclaration(SyntaxNode? root, SyntaxNode node, out OneOrMany<SyntaxNode> declarations) { var current = node; while (current != null && current != root) { switch (current.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: declarations = new(current); return true; case SyntaxKind.PropertyDeclaration: // int P { get; } = [|initializer|]; RoslynDebug.Assert(((PropertyDeclarationSyntax)current).Initializer != null); declarations = new(current); return true; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: // Active statements encompassing modifiers or type correspond to the first initialized field. // [|public static int F = 1|], G = 2; declarations = new(((BaseFieldDeclarationSyntax)current).Declaration.Variables.First()); return true; case SyntaxKind.VariableDeclarator: // public static int F = 1, [|G = 2|]; RoslynDebug.Assert(current.Parent.IsKind(SyntaxKind.VariableDeclaration)); switch (current.Parent.Parent!.Kind()) { case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: declarations = new(current); return true; } current = current.Parent; break; case SyntaxKind.ArrowExpressionClause: // represents getter symbol declaration node of a property/indexer with expression body if (current.Parent.IsKind(SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration)) { declarations = new(current); return true; } break; } current = current.Parent; } declarations = default; return false; } /// <returns> /// Given a node representing a declaration or a top-level match node returns: /// - <see cref="BlockSyntax"/> for method-like member declarations with block bodies (methods, operators, constructors, destructors, accessors). /// - <see cref="ExpressionSyntax"/> for variable declarators of fields, properties with an initializer expression, or /// for method-like member declarations with expression bodies (methods, properties, indexers, operators) /// - <see cref="CompilationUnitSyntax"/> for top level statements /// /// A null reference otherwise. /// </returns> internal override SyntaxNode? TryGetDeclarationBody(SyntaxNode node) { if (node.IsKind(SyntaxKind.VariableDeclarator, out VariableDeclaratorSyntax? variableDeclarator)) { return variableDeclarator.Initializer?.Value; } if (node is CompilationUnitSyntax unit && unit.ContainsTopLevelStatements()) { // For top level statements, where there is no syntax node to represent the entire body of the synthesized // main method we just use the compilation unit itself return node; } return SyntaxUtilities.TryGetMethodDeclarationBody(node); } internal override bool IsDeclarationWithSharedBody(SyntaxNode declaration) => false; protected override ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody) { if (memberBody is CompilationUnitSyntax unit && unit.ContainsTopLevelStatements()) { return model.AnalyzeDataFlow(((GlobalStatementSyntax)unit.Members[0]).Statement, unit.Members.OfType<GlobalStatementSyntax>().Last().Statement)!.Captured; } Debug.Assert(memberBody.IsKind(SyntaxKind.Block) || memberBody is ExpressionSyntax); return model.AnalyzeDataFlow(memberBody).Captured; } protected override bool AreHandledEventsEqual(IMethodSymbol oldMethod, IMethodSymbol newMethod) => true; internal override bool HasParameterClosureScope(ISymbol member) { // in instance constructor parameters are lifted to a closure different from method body return (member as IMethodSymbol)?.MethodKind == MethodKind.Constructor; } protected override IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken) { Debug.Assert(localOrParameter is IParameterSymbol || localOrParameter is ILocalSymbol || localOrParameter is IRangeVariableSymbol); // not supported (it's non trivial to find all places where "this" is used): Debug.Assert(!localOrParameter.IsThisParameter()); return from root in roots from node in root.DescendantNodesAndSelf() where node.IsKind(SyntaxKind.IdentifierName) let nameSyntax = (IdentifierNameSyntax)node where (string?)nameSyntax.Identifier.Value == localOrParameter.Name && (model.GetSymbolInfo(nameSyntax, cancellationToken).Symbol?.Equals(localOrParameter) ?? false) select node; } /// <returns> /// If <paramref name="node"/> is a method, accessor, operator, destructor, or constructor without an initializer, /// tokens of its block body, or tokens of the expression body. /// /// If <paramref name="node"/> is an indexer declaration the tokens of its expression body. /// /// If <paramref name="node"/> is a property declaration the tokens of its expression body or initializer. /// /// If <paramref name="node"/> is a constructor with an initializer, /// tokens of the initializer concatenated with tokens of the constructor body. /// /// If <paramref name="node"/> is a variable declarator of a field with an initializer, /// subset of the tokens of the field declaration depending on which variable declarator it is. /// /// Null reference otherwise. /// </returns> internal override IEnumerable<SyntaxToken>? TryGetActiveTokens(SyntaxNode node) { if (node.IsKind(SyntaxKind.VariableDeclarator)) { // TODO: The logic is similar to BreakpointSpans.TryCreateSpanForVariableDeclaration. Can we abstract it? var declarator = node; var fieldDeclaration = (BaseFieldDeclarationSyntax)declarator.Parent!.Parent!; var variableDeclaration = fieldDeclaration.Declaration; if (fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword)) { return null; } if (variableDeclaration.Variables.Count == 1) { if (variableDeclaration.Variables[0].Initializer == null) { return null; } return fieldDeclaration.Modifiers.Concat(variableDeclaration.DescendantTokens()).Concat(fieldDeclaration.SemicolonToken); } if (declarator == variableDeclaration.Variables[0]) { return fieldDeclaration.Modifiers.Concat(variableDeclaration.Type.DescendantTokens()).Concat(node.DescendantTokens()); } return declarator.DescendantTokens(); } if (node is PropertyDeclarationSyntax { ExpressionBody: var propertyExpressionBody and not null }) { return propertyExpressionBody.Expression.DescendantTokens(); } if (node is IndexerDeclarationSyntax { ExpressionBody: var indexerExpressionBody and not null }) { return indexerExpressionBody.Expression.DescendantTokens(); } var bodyTokens = SyntaxUtilities.TryGetMethodDeclarationBody(node)?.DescendantTokens(); if (node.IsKind(SyntaxKind.ConstructorDeclaration, out ConstructorDeclarationSyntax? ctor)) { if (ctor.Initializer != null) { bodyTokens = ctor.Initializer.DescendantTokens().Concat(bodyTokens ?? Enumerable.Empty<SyntaxToken>()); } } return bodyTokens; } internal override (TextSpan envelope, TextSpan hole) GetActiveSpanEnvelope(SyntaxNode declaration) => (BreakpointSpans.GetEnvelope(declaration), default); protected override SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot) { // Constructor may contain active nodes outside of its body (constructor initializer), // but within the body of the member declaration (the parent). if (bodyOrMatchRoot.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { return bodyOrMatchRoot.Parent; } // Field initializer match root -- an active statement may include the modifiers // and type specification of the field declaration. if (bodyOrMatchRoot.IsKind(SyntaxKind.EqualsValueClause) && bodyOrMatchRoot.Parent.IsKind(SyntaxKind.VariableDeclarator) && bodyOrMatchRoot.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) { return bodyOrMatchRoot.Parent.Parent; } // Field initializer body -- an active statement may include the modifiers // and type specification of the field declaration. if (bodyOrMatchRoot.Parent.IsKind(SyntaxKind.EqualsValueClause) && bodyOrMatchRoot.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) && bodyOrMatchRoot.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) { return bodyOrMatchRoot.Parent.Parent.Parent; } // otherwise all active statements are covered by the body/match root itself: return bodyOrMatchRoot; } protected override SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, TextSpan span, SyntaxNode? partnerDeclarationBody, out SyntaxNode? partner, out int statementPart) { var position = span.Start; SyntaxUtilities.AssertIsBody(declarationBody, allowLambda: false); if (position < declarationBody.SpanStart) { // Only constructors and the field initializers may have an [|active statement|] starting outside of the <<body>>. // Constructor: [|public C()|] <<{ }>> // Constructor initializer: public C() : [|base(expr)|] <<{ }>> // Constructor initializer with lambda: public C() : base(() => { [|...|] }) <<{ }>> // Field initializers: [|public int a = <<expr>>|], [|b = <<expr>>|]; // No need to special case property initializers here, the active statement always spans the initializer expression. if (declarationBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { var constructor = (ConstructorDeclarationSyntax)declarationBody.Parent; var partnerConstructor = (ConstructorDeclarationSyntax?)partnerDeclarationBody?.Parent; if (constructor.Initializer == null || position < constructor.Initializer.ColonToken.SpanStart) { statementPart = DefaultStatementPart; partner = partnerConstructor; return constructor; } declarationBody = constructor.Initializer; partnerDeclarationBody = partnerConstructor?.Initializer; } } if (!declarationBody.FullSpan.Contains(position)) { // invalid position, let's find a labeled node that encompasses the body: position = declarationBody.SpanStart; } SyntaxNode node; if (partnerDeclarationBody != null) { SyntaxUtilities.FindLeafNodeAndPartner(declarationBody, position, partnerDeclarationBody, out node, out partner); } else { node = declarationBody.FindToken(position).Parent!; partner = null; } while (true) { var isBody = node == declarationBody || LambdaUtilities.IsLambdaBodyStatementOrExpression(node); if (isBody || SyntaxComparer.Statement.HasLabel(node)) { switch (node.Kind()) { case SyntaxKind.Block: statementPart = (int)GetStatementPart((BlockSyntax)node, position); return node; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: Debug.Assert(!isBody); statementPart = (int)GetStatementPart((CommonForEachStatementSyntax)node, position); return node; case SyntaxKind.DoStatement: // The active statement of DoStatement node is the while condition, // which is lexically not the closest breakpoint span (the body is). // do { ... } [|while (condition);|] Debug.Assert(position == ((DoStatementSyntax)node).WhileKeyword.SpanStart); Debug.Assert(!isBody); goto default; case SyntaxKind.PropertyDeclaration: // The active span corresponding to a property declaration is the span corresponding to its initializer (if any), // not the span corresponding to the accessor. // int P { [|get;|] } = [|<initializer>|]; Debug.Assert(position == ((PropertyDeclarationSyntax)node).Initializer!.SpanStart); goto default; case SyntaxKind.VariableDeclaration: // VariableDeclaration ::= TypeSyntax CommaSeparatedList(VariableDeclarator) // // The compiler places sequence points after each local variable initialization. // The TypeSyntax is considered to be part of the first sequence span. Debug.Assert(!isBody); node = ((VariableDeclarationSyntax)node).Variables.First(); if (partner != null) { partner = ((VariableDeclarationSyntax)partner).Variables.First(); } statementPart = DefaultStatementPart; return node; case SyntaxKind.SwitchExpression: // An active statement that covers IL generated for the decision tree: // <governing-expression> [|switch { <arm>, ..., <arm> }|] // This active statement is never a leaf active statement (does not correspond to a breakpoint span). var switchExpression = (SwitchExpressionSyntax)node; if (position == switchExpression.SwitchKeyword.SpanStart) { Debug.Assert(span.End == switchExpression.CloseBraceToken.Span.End); statementPart = (int)SwitchExpressionPart.SwitchBody; return node; } // The switch expression itself can be (a part of) an active statement associated with the containing node // For example, when it is used as a switch arm expression like so: // <expr> switch { <pattern> [|when <expr> switch { ... }|] ... } Debug.Assert(position == switchExpression.Span.Start); if (isBody) { goto default; } // ascend to parent node: break; case SyntaxKind.SwitchExpressionArm: // An active statement may occur in the when clause and in the arm expression: // <constant-pattern> [|when <condition>|] => [|<expression>|] // The former is covered by when-clause node - it's a labeled node. // The latter isn't enclosed in a distinct labeled syntax node and thus needs to be covered // by the arm node itself. Debug.Assert(position == ((SwitchExpressionArmSyntax)node).Expression.SpanStart); Debug.Assert(!isBody); goto default; default: statementPart = DefaultStatementPart; return node; } } node = node.Parent!; if (partner != null) { partner = partner.Parent; } } } private static BlockPart GetStatementPart(BlockSyntax node, int position) => position < node.OpenBraceToken.Span.End ? BlockPart.OpenBrace : BlockPart.CloseBrace; private static TextSpan GetActiveSpan(BlockSyntax node, BlockPart part) => part switch { BlockPart.OpenBrace => node.OpenBraceToken.Span, BlockPart.CloseBrace => node.CloseBraceToken.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static ForEachPart GetStatementPart(CommonForEachStatementSyntax node, int position) => position < node.OpenParenToken.SpanStart ? ForEachPart.ForEach : position < node.InKeyword.SpanStart ? ForEachPart.VariableDeclaration : position < node.Expression.SpanStart ? ForEachPart.In : ForEachPart.Expression; private static TextSpan GetActiveSpan(ForEachStatementSyntax node, ForEachPart part) => part switch { ForEachPart.ForEach => node.ForEachKeyword.Span, ForEachPart.VariableDeclaration => TextSpan.FromBounds(node.Type.SpanStart, node.Identifier.Span.End), ForEachPart.In => node.InKeyword.Span, ForEachPart.Expression => node.Expression.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static TextSpan GetActiveSpan(ForEachVariableStatementSyntax node, ForEachPart part) => part switch { ForEachPart.ForEach => node.ForEachKeyword.Span, ForEachPart.VariableDeclaration => TextSpan.FromBounds(node.Variable.SpanStart, node.Variable.Span.End), ForEachPart.In => node.InKeyword.Span, ForEachPart.Expression => node.Expression.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static TextSpan GetActiveSpan(SwitchExpressionSyntax node, SwitchExpressionPart part) => part switch { SwitchExpressionPart.WholeExpression => node.Span, SwitchExpressionPart.SwitchBody => TextSpan.FromBounds(node.SwitchKeyword.SpanStart, node.CloseBraceToken.Span.End), _ => throw ExceptionUtilities.UnexpectedValue(part), }; protected override bool AreEquivalent(SyntaxNode left, SyntaxNode right) => SyntaxFactory.AreEquivalent(left, right); private static bool AreEquivalentIgnoringLambdaBodies(SyntaxNode left, SyntaxNode right) { // usual case: if (SyntaxFactory.AreEquivalent(left, right)) { return true; } return LambdaUtilities.AreEquivalentIgnoringLambdaBodies(left, right); } internal override SyntaxNode FindDeclarationBodyPartner(SyntaxNode leftRoot, SyntaxNode rightRoot, SyntaxNode leftNode) => SyntaxUtilities.FindPartner(leftRoot, rightRoot, leftNode); internal override bool IsClosureScope(SyntaxNode node) => LambdaUtilities.IsClosureScope(node); protected override SyntaxNode? FindEnclosingLambdaBody(SyntaxNode? container, SyntaxNode node) { var root = GetEncompassingAncestor(container); var current = node; while (current != root && current != null) { if (LambdaUtilities.IsLambdaBodyStatementOrExpression(current, out var body)) { return body; } current = current.Parent; } return null; } protected override IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody) => SpecializedCollections.SingletonEnumerable(lambdaBody); protected override SyntaxNode? TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda) => LambdaUtilities.TryGetCorrespondingLambdaBody(oldBody, newLambda); protected override Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit) => SyntaxComparer.TopLevel.ComputeMatch(oldCompilationUnit, newCompilationUnit); protected override Match<SyntaxNode> ComputeTopLevelDeclarationMatch(SyntaxNode oldDeclaration, SyntaxNode newDeclaration) { Contract.ThrowIfNull(oldDeclaration.Parent); Contract.ThrowIfNull(newDeclaration.Parent); var comparer = new SyntaxComparer(oldDeclaration.Parent, newDeclaration.Parent, new[] { oldDeclaration }, new[] { newDeclaration }, compareStatementSyntax: false); return comparer.ComputeMatch(oldDeclaration.Parent, newDeclaration.Parent); } protected override Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>>? knownMatches) { SyntaxUtilities.AssertIsBody(oldBody, allowLambda: true); SyntaxUtilities.AssertIsBody(newBody, allowLambda: true); if (oldBody is ExpressionSyntax || newBody is ExpressionSyntax || (oldBody.Parent.IsKind(SyntaxKind.LocalFunctionStatement) && newBody.Parent.IsKind(SyntaxKind.LocalFunctionStatement))) { Debug.Assert(oldBody is ExpressionSyntax || oldBody is BlockSyntax); Debug.Assert(newBody is ExpressionSyntax || newBody is BlockSyntax); // The matching algorithm requires the roots to match each other. // Lambda bodies, field/property initializers, and method/property/indexer/operator expression-bodies may also be lambda expressions. // Say we have oldBody 'x => x' and newBody 'F(x => x + 1)', then // the algorithm would match 'x => x' to 'F(x => x + 1)' instead of // matching 'x => x' to 'x => x + 1'. // We use the parent node as a root: // - for field/property initializers the root is EqualsValueClause. // - for member expression-bodies the root is ArrowExpressionClauseSyntax. // - for block bodies the root is a method/operator/accessor declaration (only happens when matching expression body with a block body) // - for lambdas the root is a LambdaExpression. // - for query lambdas the root is the query clause containing the lambda (e.g. where). // - for local functions the root is LocalFunctionStatement. static SyntaxNode GetMatchingRoot(SyntaxNode body) { var parent = body.Parent!; // We could apply this change across all ArrowExpressionClause consistently not just for ones with LocalFunctionStatement parents // but it would require an essential refactoring. return parent.IsKind(SyntaxKind.ArrowExpressionClause) && parent.Parent.IsKind(SyntaxKind.LocalFunctionStatement) ? parent.Parent : parent; } var oldRoot = GetMatchingRoot(oldBody); var newRoot = GetMatchingRoot(newBody); return new SyntaxComparer(oldRoot, newRoot, GetChildNodes(oldRoot, oldBody), GetChildNodes(newRoot, newBody), compareStatementSyntax: true).ComputeMatch(oldRoot, newRoot, knownMatches); } if (oldBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { // We need to include constructor initializer in the match, since it may contain lambdas. // Use the constructor declaration as a root. RoslynDebug.Assert(oldBody.IsKind(SyntaxKind.Block)); RoslynDebug.Assert(newBody.IsKind(SyntaxKind.Block)); RoslynDebug.Assert(newBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)); RoslynDebug.Assert(newBody.Parent is object); return SyntaxComparer.Statement.ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches); } return SyntaxComparer.Statement.ComputeMatch(oldBody, newBody, knownMatches); } private static IEnumerable<SyntaxNode> GetChildNodes(SyntaxNode root, SyntaxNode body) { if (root is LocalFunctionStatementSyntax localFunc) { // local functions have multiple children we need to process for matches, but we won't automatically // descend into them, assuming they're nested, so we override the default behaviour and return // multiple children foreach (var attributeList in localFunc.AttributeLists) { yield return attributeList; } yield return localFunc.ReturnType; if (localFunc.TypeParameterList is not null) { yield return localFunc.TypeParameterList; } yield return localFunc.ParameterList; if (localFunc.Body is not null) { yield return localFunc.Body; } else if (localFunc.ExpressionBody is not null) { // Skip the ArrowExpressionClause that is ExressionBody and just return the expression itself yield return localFunc.ExpressionBody.Expression; } } else { yield return body; } } internal override void ReportDeclarationInsertDeleteRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode, ISymbol oldSymbol, ISymbol newSymbol, CancellationToken cancellationToken) { // Global statements have a declaring syntax reference to the compilation unit itself, which we can just ignore // for the purposes of declaration rude edits if (oldNode.IsKind(SyntaxKind.CompilationUnit) || newNode.IsKind(SyntaxKind.CompilationUnit)) { return; } // Compiler generated methods of records have a declaring syntax reference to the record declaration itself // but their explicitly implemented counterparts reference the actual member. Compiler generated properties // of records reference the parameter that names them. // // Since there is no useful "old" syntax node for these members, we can't compute declaration or body edits // using the standard tree comparison code. // // Based on this, we can detect a new explicit implementation of a record member by checking if the // declaration kind has changed. If it hasn't changed, then our standard code will handle it. if (oldNode.RawKind == newNode.RawKind) { base.ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldNode, newNode, oldSymbol, newSymbol, cancellationToken); return; } // When explicitly implementing a property that is represented by a positional parameter // what looks like an edit could actually be a rude delete, or something else if (oldNode is ParameterSyntax && newNode is PropertyDeclarationSyntax property) { if (property.AccessorList!.Accessors.Count == 1) { // Explicitly implementing a property with only one accessor is a delete of the init accessor, so a rude edit. // Not implementing the get accessor would be a compile error diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ImplementRecordParameterAsReadOnly, GetDiagnosticSpan(newNode, EditKind.Delete), oldNode, new[] { property.Identifier.ToString() })); } else if (property.AccessorList.Accessors.Any(a => a.IsKind(SyntaxKind.SetAccessorDeclaration))) { // The compiler implements the properties with an init accessor so explicitly implementing // it with a set accessor is a rude accessor change edit diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ImplementRecordParameterWithSet, GetDiagnosticSpan(newNode, EditKind.Delete), oldNode, new[] { property.Identifier.ToString() })); } } else if (oldNode is RecordDeclarationSyntax && newNode is MethodDeclarationSyntax && !oldSymbol.GetParameters().Select(p => p.Name).SequenceEqual(newSymbol.GetParameters().Select(p => p.Name))) { // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 // Explicitly implemented methods must have parameter names that match the compiler generated versions // exactly otherwise symbol matching won't work for them. // We don't need to worry about parameter types, because if they were different then we wouldn't get here // as this wouldn't be the explicit implementation of a known method. // We don't need to worry about access modifiers because the symbol matching still works, and most of the // time changing access modifiers for these known methods is a compile error anyway. diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, GetDiagnosticSpan(newNode, EditKind.Update), oldNode, new[] { oldSymbol.ToDisplayString(SymbolDisplayFormats.NameFormat) })); } } protected override void ReportLocalFunctionsDeclarationRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> bodyMatch) { var bodyEditsForLambda = bodyMatch.GetTreeEdits(); var editMap = BuildEditMap(bodyEditsForLambda); foreach (var edit in bodyEditsForLambda.Edits) { if (HasParentEdit(editMap, edit)) { return; } var classifier = new EditClassifier(this, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, bodyMatch); classifier.ClassifyEdit(); } } protected override bool TryMatchActiveStatement( SyntaxNode oldStatement, int statementPart, SyntaxNode oldBody, SyntaxNode newBody, [NotNullWhen(true)] out SyntaxNode? newStatement) { SyntaxUtilities.AssertIsBody(oldBody, allowLambda: true); SyntaxUtilities.AssertIsBody(newBody, allowLambda: true); switch (oldStatement.Kind()) { case SyntaxKind.ThisConstructorInitializer: case SyntaxKind.BaseConstructorInitializer: case SyntaxKind.ConstructorDeclaration: var newConstructor = (ConstructorDeclarationSyntax)(newBody.Parent.IsKind(SyntaxKind.ArrowExpressionClause) ? newBody.Parent.Parent : newBody.Parent)!; newStatement = (SyntaxNode?)newConstructor.Initializer ?? newConstructor; return true; default: // TODO: Consider mapping an expression body to an equivalent statement expression or return statement and vice versa. // It would benefit transformations of expression bodies to block bodies of lambdas, methods, operators and properties. // See https://github.com/dotnet/roslyn/issues/22696 // field initializer, lambda and query expressions: if (oldStatement == oldBody && !newBody.IsKind(SyntaxKind.Block)) { newStatement = newBody; return true; } newStatement = null; return false; } } #endregion #region Syntax and Semantic Utils protected override TextSpan GetGlobalStatementDiagnosticSpan(SyntaxNode node) { if (node is CompilationUnitSyntax unit) { // When deleting something from a compilation unit we just report diagnostics for the last global statement return unit.Members.OfType<GlobalStatementSyntax>().LastOrDefault()?.Span ?? default; } return GetDiagnosticSpan(node, EditKind.Delete); } protected override string LineDirectiveKeyword => "line"; protected override ushort LineDirectiveSyntaxKind => (ushort)SyntaxKind.LineDirectiveTrivia; protected override IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes) => SyntaxComparer.GetSequenceEdits(oldNodes, newNodes); internal override SyntaxNode EmptyCompilationUnit => SyntaxFactory.CompilationUnit(); // there are no experimental features at this time. internal override bool ExperimentalFeaturesEnabled(SyntaxTree tree) => false; protected override bool StateMachineSuspensionPointKindEquals(SyntaxNode suspensionPoint1, SyntaxNode suspensionPoint2) => (suspensionPoint1 is CommonForEachStatementSyntax) ? suspensionPoint2 is CommonForEachStatementSyntax : suspensionPoint1.RawKind == suspensionPoint2.RawKind; protected override bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2) => SyntaxComparer.Statement.GetLabel(node1) == SyntaxComparer.Statement.GetLabel(node2); protected override bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span) => BreakpointSpans.TryGetClosestBreakpointSpan(root, position, out span); protected override bool TryGetActiveSpan(SyntaxNode node, int statementPart, int minLength, out TextSpan span) { switch (node.Kind()) { case SyntaxKind.Block: span = GetActiveSpan((BlockSyntax)node, (BlockPart)statementPart); return true; case SyntaxKind.ForEachStatement: span = GetActiveSpan((ForEachStatementSyntax)node, (ForEachPart)statementPart); return true; case SyntaxKind.ForEachVariableStatement: span = GetActiveSpan((ForEachVariableStatementSyntax)node, (ForEachPart)statementPart); return true; case SyntaxKind.DoStatement: // The active statement of DoStatement node is the while condition, // which is lexically not the closest breakpoint span (the body is). // do { ... } [|while (condition);|] Debug.Assert(statementPart == DefaultStatementPart); var doStatement = (DoStatementSyntax)node; return BreakpointSpans.TryGetClosestBreakpointSpan(node, doStatement.WhileKeyword.SpanStart, out span); case SyntaxKind.PropertyDeclaration: // The active span corresponding to a property declaration is the span corresponding to its initializer (if any), // not the span corresponding to the accessor. // int P { [|get;|] } = [|<initializer>|]; Debug.Assert(statementPart == DefaultStatementPart); var propertyDeclaration = (PropertyDeclarationSyntax)node; if (propertyDeclaration.Initializer != null && BreakpointSpans.TryGetClosestBreakpointSpan(node, propertyDeclaration.Initializer.SpanStart, out span)) { return true; } span = default; return false; case SyntaxKind.SwitchExpression: span = GetActiveSpan((SwitchExpressionSyntax)node, (SwitchExpressionPart)statementPart); return true; case SyntaxKind.SwitchExpressionArm: // An active statement may occur in the when clause and in the arm expression: // <constant-pattern> [|when <condition>|] => [|<expression>|] // The former is covered by when-clause node - it's a labeled node. // The latter isn't enclosed in a distinct labeled syntax node and thus needs to be covered // by the arm node itself. Debug.Assert(statementPart == DefaultStatementPart); span = ((SwitchExpressionArmSyntax)node).Expression.Span; return true; default: // make sure all nodes that use statement parts are handled above: Debug.Assert(statementPart == DefaultStatementPart); return BreakpointSpans.TryGetClosestBreakpointSpan(node, node.SpanStart, out span); } } protected override IEnumerable<(SyntaxNode statement, int statementPart)> EnumerateNearStatements(SyntaxNode statement) { var direction = +1; SyntaxNodeOrToken nodeOrToken = statement; var fieldOrPropertyModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(statement); while (true) { nodeOrToken = (direction < 0) ? nodeOrToken.GetPreviousSibling() : nodeOrToken.GetNextSibling(); if (nodeOrToken.RawKind == 0) { var parent = statement.Parent; if (parent == null) { yield break; } switch (parent.Kind()) { case SyntaxKind.Block: // The next sequence point hit after the last statement of a block is the closing brace: yield return (parent, (int)(direction > 0 ? BlockPart.CloseBrace : BlockPart.OpenBrace)); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // The next sequence point hit after the body is the in keyword: // [|foreach|] ([|variable-declaration|] [|in|] [|expression|]) [|<body>|] yield return (parent, (int)ForEachPart.In); break; } if (direction > 0) { nodeOrToken = statement; direction = -1; continue; } if (fieldOrPropertyModifiers.HasValue) { // We enumerated all members and none of them has an initializer. // We don't have any better place where to place the span than the initial field. // Consider: in non-partial classes we could find a single constructor. // Otherwise, it would be confusing to select one arbitrarily. yield return (statement, -1); } nodeOrToken = statement = parent; fieldOrPropertyModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(statement); direction = +1; yield return (nodeOrToken.AsNode()!, DefaultStatementPart); } else { var node = nodeOrToken.AsNode(); if (node == null) { continue; } if (fieldOrPropertyModifiers.HasValue) { var nodeModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(node); if (!nodeModifiers.HasValue || nodeModifiers.Value.Any(SyntaxKind.StaticKeyword) != fieldOrPropertyModifiers.Value.Any(SyntaxKind.StaticKeyword)) { continue; } } switch (node.Kind()) { case SyntaxKind.Block: yield return (node, (int)(direction > 0 ? BlockPart.OpenBrace : BlockPart.CloseBrace)); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: yield return (node, (int)ForEachPart.ForEach); break; } yield return (node, DefaultStatementPart); } } } protected override bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart) { if (oldStatement.Kind() != newStatement.Kind()) { return false; } switch (oldStatement.Kind()) { case SyntaxKind.Block: // closing brace of a using statement or a block that contains using local declarations: if (statementPart == (int)BlockPart.CloseBrace) { if (oldStatement.Parent.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? oldUsing)) { return newStatement.Parent.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? newUsing) && AreEquivalentActiveStatements(oldUsing, newUsing); } return HasEquivalentUsingDeclarations((BlockSyntax)oldStatement, (BlockSyntax)newStatement); } return true; case SyntaxKind.ConstructorDeclaration: // The call could only change if the base type of the containing class changed. return true; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // only check the expression, edits in the body and the variable declaration are allowed: return AreEquivalentActiveStatements((CommonForEachStatementSyntax)oldStatement, (CommonForEachStatementSyntax)newStatement); case SyntaxKind.IfStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((IfStatementSyntax)oldStatement, (IfStatementSyntax)newStatement); case SyntaxKind.WhileStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((WhileStatementSyntax)oldStatement, (WhileStatementSyntax)newStatement); case SyntaxKind.DoStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((DoStatementSyntax)oldStatement, (DoStatementSyntax)newStatement); case SyntaxKind.SwitchStatement: return AreEquivalentActiveStatements((SwitchStatementSyntax)oldStatement, (SwitchStatementSyntax)newStatement); case SyntaxKind.LockStatement: return AreEquivalentActiveStatements((LockStatementSyntax)oldStatement, (LockStatementSyntax)newStatement); case SyntaxKind.UsingStatement: return AreEquivalentActiveStatements((UsingStatementSyntax)oldStatement, (UsingStatementSyntax)newStatement); // fixed and for statements don't need special handling since the active statement is a variable declaration default: return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement); } } private static bool HasEquivalentUsingDeclarations(BlockSyntax oldBlock, BlockSyntax newBlock) { var oldUsingDeclarations = oldBlock.Statements.Where(s => s is LocalDeclarationStatementSyntax l && l.UsingKeyword != default); var newUsingDeclarations = newBlock.Statements.Where(s => s is LocalDeclarationStatementSyntax l && l.UsingKeyword != default); return oldUsingDeclarations.SequenceEqual(newUsingDeclarations, AreEquivalentIgnoringLambdaBodies); } private static bool AreEquivalentActiveStatements(IfStatementSyntax oldNode, IfStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(WhileStatementSyntax oldNode, WhileStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(DoStatementSyntax oldNode, DoStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(SwitchStatementSyntax oldNode, SwitchStatementSyntax newNode) { // only check the expression, edits in the body are allowed, unless the switch expression contains patterns: if (!AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression)) { return false; } // Check that switch statement decision tree has not changed. var hasDecitionTree = oldNode.Sections.Any(s => s.Labels.Any(l => l is CasePatternSwitchLabelSyntax)); return !hasDecitionTree || AreEquivalentSwitchStatementDecisionTrees(oldNode, newNode); } private static bool AreEquivalentActiveStatements(LockStatementSyntax oldNode, LockStatementSyntax newNode) { // only check the expression, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression); } private static bool AreEquivalentActiveStatements(FixedStatementSyntax oldNode, FixedStatementSyntax newNode) => AreEquivalentIgnoringLambdaBodies(oldNode.Declaration, newNode.Declaration); private static bool AreEquivalentActiveStatements(UsingStatementSyntax oldNode, UsingStatementSyntax newNode) { // only check the expression/declaration, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies( (SyntaxNode?)oldNode.Declaration ?? oldNode.Expression!, (SyntaxNode?)newNode.Declaration ?? newNode.Expression!); } private static bool AreEquivalentActiveStatements(CommonForEachStatementSyntax oldNode, CommonForEachStatementSyntax newNode) { if (oldNode.Kind() != newNode.Kind() || !AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression)) { return false; } switch (oldNode.Kind()) { case SyntaxKind.ForEachStatement: return AreEquivalentIgnoringLambdaBodies(((ForEachStatementSyntax)oldNode).Type, ((ForEachStatementSyntax)newNode).Type); case SyntaxKind.ForEachVariableStatement: return AreEquivalentIgnoringLambdaBodies(((ForEachVariableStatementSyntax)oldNode).Variable, ((ForEachVariableStatementSyntax)newNode).Variable); default: throw ExceptionUtilities.UnexpectedValue(oldNode.Kind()); } } private static bool AreSimilarActiveStatements(CommonForEachStatementSyntax oldNode, CommonForEachStatementSyntax newNode) { List<SyntaxToken>? oldTokens = null; List<SyntaxToken>? newTokens = null; SyntaxComparer.GetLocalNames(oldNode, ref oldTokens); SyntaxComparer.GetLocalNames(newNode, ref newTokens); // A valid foreach statement declares at least one variable. RoslynDebug.Assert(oldTokens != null); RoslynDebug.Assert(newTokens != null); return DeclareSameIdentifiers(oldTokens.ToArray(), newTokens.ToArray()); } internal override bool IsInterfaceDeclaration(SyntaxNode node) => node.IsKind(SyntaxKind.InterfaceDeclaration); internal override bool IsRecordDeclaration(SyntaxNode node) => node.IsKind(SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration); internal override SyntaxNode? TryGetContainingTypeDeclaration(SyntaxNode node) => node is CompilationUnitSyntax ? null : node.Parent!.FirstAncestorOrSelf<BaseTypeDeclarationSyntax>(); internal override bool HasBackingField(SyntaxNode propertyOrIndexerDeclaration) => propertyOrIndexerDeclaration.IsKind(SyntaxKind.PropertyDeclaration, out PropertyDeclarationSyntax? propertyDecl) && SyntaxUtilities.HasBackingField(propertyDecl); internal override bool TryGetAssociatedMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? declaration) { if (node.IsKind(SyntaxKind.Parameter, SyntaxKind.TypeParameter)) { Contract.ThrowIfFalse(node.IsParentKind(SyntaxKind.ParameterList, SyntaxKind.TypeParameterList, SyntaxKind.BracketedParameterList)); declaration = node.Parent!.Parent!; return true; } if (node.Parent.IsParentKind(SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.EventDeclaration)) { declaration = node.Parent.Parent!; return true; } declaration = null; return false; } internal override bool IsDeclarationWithInitializer(SyntaxNode declaration) => declaration is VariableDeclaratorSyntax { Initializer: not null } || declaration is PropertyDeclarationSyntax { Initializer: not null }; internal override bool IsRecordPrimaryConstructorParameter(SyntaxNode declaration) => declaration is ParameterSyntax { Parent: ParameterListSyntax { Parent: RecordDeclarationSyntax } }; private static bool IsPropertyDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType) { if (newContainingType.IsRecord && declaration is PropertyDeclarationSyntax { Identifier: { ValueText: var name } }) { // We need to use symbol information to find the primary constructor, because it could be in another file if the type is partial foreach (var reference in newContainingType.DeclaringSyntaxReferences) { // Since users can define as many constructors as they like, going back to syntax to find the parameter list // in the record declaration is the simplest way to check if there is a matching parameter if (reference.GetSyntax() is RecordDeclarationSyntax record && record.ParameterList is not null && record.ParameterList.Parameters.Any(p => p.Identifier.ValueText.Equals(name))) { return true; } } } return false; } internal override bool IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType, out bool isFirstAccessor) { isFirstAccessor = false; if (declaration is AccessorDeclarationSyntax { Parent: AccessorListSyntax { Parent: PropertyDeclarationSyntax property } list } && IsPropertyDeclarationMatchingPrimaryConstructorParameter(property, newContainingType)) { isFirstAccessor = list.Accessors[0] == declaration; return true; } return false; } internal override bool IsConstructorWithMemberInitializers(SyntaxNode constructorDeclaration) => constructorDeclaration is ConstructorDeclarationSyntax ctor && (ctor.Initializer == null || ctor.Initializer.IsKind(SyntaxKind.BaseConstructorInitializer)); internal override bool IsPartial(INamedTypeSymbol type) { var syntaxRefs = type.DeclaringSyntaxReferences; return syntaxRefs.Length > 1 || ((BaseTypeDeclarationSyntax)syntaxRefs.Single().GetSyntax()).Modifiers.Any(SyntaxKind.PartialKeyword); } protected override SyntaxNode GetSymbolDeclarationSyntax(SyntaxReference reference, CancellationToken cancellationToken) => reference.GetSyntax(cancellationToken); protected override OneOrMany<(ISymbol? oldSymbol, ISymbol? newSymbol, EditKind editKind)> GetSymbolEdits( EditKind editKind, SyntaxNode? oldNode, SyntaxNode? newNode, SemanticModel? oldModel, SemanticModel newModel, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken) { var oldSymbol = (oldNode != null) ? GetSymbolForEdit(oldNode, oldModel!, cancellationToken) : null; var newSymbol = (newNode != null) ? GetSymbolForEdit(newNode, newModel, cancellationToken) : null; switch (editKind) { case EditKind.Update: Contract.ThrowIfNull(oldNode); Contract.ThrowIfNull(newNode); Contract.ThrowIfNull(oldModel); // Certain updates of a property/indexer node affects its accessors. // Return all affected symbols for these updates. // 1) Old or new property/indexer has an expression body: // int this[...] => expr; // int this[...] { get => expr; } // int P => expr; // int P { get => expr; } = init if (oldNode is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null } || newNode is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null }) { Debug.Assert(oldSymbol is IPropertySymbol); Debug.Assert(newSymbol is IPropertySymbol); var oldGetterSymbol = ((IPropertySymbol)oldSymbol).GetMethod; var newGetterSymbol = ((IPropertySymbol)newSymbol).GetMethod; return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, editKind), (oldGetterSymbol, newGetterSymbol, editKind))); } // 2) Property/indexer declarations differ in readonly keyword. if (oldNode is PropertyDeclarationSyntax oldProperty && newNode is PropertyDeclarationSyntax newProperty && DiffersInReadOnlyModifier(oldProperty.Modifiers, newProperty.Modifiers) || oldNode is IndexerDeclarationSyntax oldIndexer && newNode is IndexerDeclarationSyntax newIndexer && DiffersInReadOnlyModifier(oldIndexer.Modifiers, newIndexer.Modifiers)) { Debug.Assert(oldSymbol is IPropertySymbol); Debug.Assert(newSymbol is IPropertySymbol); var oldPropertySymbol = (IPropertySymbol)oldSymbol; var newPropertySymbol = (IPropertySymbol)newSymbol; using var _ = ArrayBuilder<(ISymbol?, ISymbol?, EditKind)>.GetInstance(out var builder); builder.Add((oldPropertySymbol, newPropertySymbol, editKind)); if (oldPropertySymbol.GetMethod != null && newPropertySymbol.GetMethod != null && oldPropertySymbol.GetMethod.IsReadOnly != newPropertySymbol.GetMethod.IsReadOnly) { builder.Add((oldPropertySymbol.GetMethod, newPropertySymbol.GetMethod, editKind)); } if (oldPropertySymbol.SetMethod != null && newPropertySymbol.SetMethod != null && oldPropertySymbol.SetMethod.IsReadOnly != newPropertySymbol.SetMethod.IsReadOnly) { builder.Add((oldPropertySymbol.SetMethod, newPropertySymbol.SetMethod, editKind)); } return OneOrMany.Create(builder.ToImmutable()); } static bool DiffersInReadOnlyModifier(SyntaxTokenList oldModifiers, SyntaxTokenList newModifiers) => (oldModifiers.IndexOf(SyntaxKind.ReadOnlyKeyword) >= 0) != (newModifiers.IndexOf(SyntaxKind.ReadOnlyKeyword) >= 0); // Change in attributes or modifiers of a field affects all its variable declarations. if (oldNode is BaseFieldDeclarationSyntax oldField && newNode is BaseFieldDeclarationSyntax newField) { return GetFieldSymbolUpdates(oldField.Declaration.Variables, newField.Declaration.Variables); } // Chnage in type of a field affects all its variable declarations. if (oldNode is VariableDeclarationSyntax oldVariableDeclaration && newNode is VariableDeclarationSyntax newVariableDeclaration) { return GetFieldSymbolUpdates(oldVariableDeclaration.Variables, newVariableDeclaration.Variables); } OneOrMany<(ISymbol?, ISymbol?, EditKind)> GetFieldSymbolUpdates(SeparatedSyntaxList<VariableDeclaratorSyntax> oldVariables, SeparatedSyntaxList<VariableDeclaratorSyntax> newVariables) { if (oldVariables.Count == 1 && newVariables.Count == 1) { return OneOrMany.Create((oldModel.GetDeclaredSymbol(oldVariables[0], cancellationToken), newModel.GetDeclaredSymbol(newVariables[0], cancellationToken), EditKind.Update)); } var result = from oldVariable in oldVariables join newVariable in newVariables on oldVariable.Identifier.Text equals newVariable.Identifier.Text select (oldModel.GetDeclaredSymbol(oldVariable, cancellationToken), newModel.GetDeclaredSymbol(newVariable, cancellationToken), EditKind.Update); return OneOrMany.Create(result.ToImmutableArray()); } break; case EditKind.Delete: case EditKind.Insert: var node = oldNode ?? newNode; // If the entire block-bodied property/indexer is deleted/inserted (accessors and the list they are contained in), // ignore this edit. We will have a semantic edit for the property/indexer itself. if (node.IsKind(SyntaxKind.GetAccessorDeclaration)) { Debug.Assert(node.Parent.IsKind(SyntaxKind.AccessorList)); if (HasEdit(editMap, node.Parent, editKind) && !HasEdit(editMap, node.Parent.Parent, editKind)) { return OneOrMany<(ISymbol?, ISymbol?, EditKind)>.Empty; } } // Inserting/deleting an expression-bodied property/indexer affects two symbols: // the property/indexer itself and the getter. // int this[...] => expr; // int P => expr; if (node is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null }) { var oldGetterSymbol = ((IPropertySymbol?)oldSymbol)?.GetMethod; var newGetterSymbol = ((IPropertySymbol?)newSymbol)?.GetMethod; return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, editKind), (oldGetterSymbol, newGetterSymbol, editKind))); } // Inserting/deleting a type parameter constraint should result in an update of the corresponding type parameter symbol: if (node.IsKind(SyntaxKind.TypeParameterConstraintClause)) { return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, EditKind.Update))); } // Inserting/deleting a global statement should result in an update of the implicit main method: if (node.IsKind(SyntaxKind.GlobalStatement)) { return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, EditKind.Update))); } break; } return (editKind == EditKind.Delete ? oldSymbol : newSymbol) is null ? OneOrMany<(ISymbol?, ISymbol?, EditKind)>.Empty : new OneOrMany<(ISymbol?, ISymbol?, EditKind)>((oldSymbol, newSymbol, editKind)); } private static ISymbol? GetSymbolForEdit( SyntaxNode node, SemanticModel model, CancellationToken cancellationToken) { if (node.IsKind(SyntaxKind.UsingDirective, SyntaxKind.NamespaceDeclaration, SyntaxKind.FileScopedNamespaceDeclaration)) { return null; } if (node.IsKind(SyntaxKind.TypeParameterConstraintClause)) { var constraintClause = (TypeParameterConstraintClauseSyntax)node; var symbolInfo = model.GetSymbolInfo(constraintClause.Name, cancellationToken); return symbolInfo.Symbol; } // Top level code always lives in a synthesized Main method if (node.IsKind(SyntaxKind.GlobalStatement)) { return model.GetEnclosingSymbol(node.SpanStart, cancellationToken); } var symbol = model.GetDeclaredSymbol(node, cancellationToken); // TODO: this is incorrect (https://github.com/dotnet/roslyn/issues/54800) // Ignore partial method definition parts. // Partial method that does not have implementation part is not emitted to metadata. // Partial method without a definition part is a compilation error. if (symbol is IMethodSymbol { IsPartialDefinition: true }) { return null; } return symbol; } internal override bool ContainsLambda(SyntaxNode declaration) => declaration.DescendantNodes().Any(LambdaUtilities.IsLambda); internal override bool IsLambda(SyntaxNode node) => LambdaUtilities.IsLambda(node); internal override bool IsLocalFunction(SyntaxNode node) => node.IsKind(SyntaxKind.LocalFunctionStatement); internal override bool IsNestedFunction(SyntaxNode node) => node is AnonymousFunctionExpressionSyntax or LocalFunctionStatementSyntax; internal override bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? body1, out SyntaxNode? body2) => LambdaUtilities.TryGetLambdaBodies(node, out body1, out body2); internal override SyntaxNode GetLambda(SyntaxNode lambdaBody) => LambdaUtilities.GetLambda(lambdaBody); internal override IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken) { var bodyExpression = LambdaUtilities.GetNestedFunctionBody(lambdaExpression); return (IMethodSymbol)model.GetRequiredEnclosingSymbol(bodyExpression.SpanStart, cancellationToken); } internal override SyntaxNode? GetContainingQueryExpression(SyntaxNode node) => node.FirstAncestorOrSelf<QueryExpressionSyntax>(); internal override bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken) { switch (oldNode.Kind()) { case SyntaxKind.FromClause: case SyntaxKind.LetClause: case SyntaxKind.WhereClause: case SyntaxKind.OrderByClause: case SyntaxKind.JoinClause: var oldQueryClauseInfo = oldModel.GetQueryClauseInfo((QueryClauseSyntax)oldNode, cancellationToken); var newQueryClauseInfo = newModel.GetQueryClauseInfo((QueryClauseSyntax)newNode, cancellationToken); return MemberSignaturesEquivalent(oldQueryClauseInfo.CastInfo.Symbol, newQueryClauseInfo.CastInfo.Symbol) && MemberSignaturesEquivalent(oldQueryClauseInfo.OperationInfo.Symbol, newQueryClauseInfo.OperationInfo.Symbol); case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: var oldOrderingInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newOrderingInfo = newModel.GetSymbolInfo(newNode, cancellationToken); return MemberSignaturesEquivalent(oldOrderingInfo.Symbol, newOrderingInfo.Symbol); case SyntaxKind.SelectClause: var oldSelectInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newSelectInfo = newModel.GetSymbolInfo(newNode, cancellationToken); // Changing reduced select clause to a non-reduced form or vice versa // adds/removes a call to Select method, which is a supported change. return oldSelectInfo.Symbol == null || newSelectInfo.Symbol == null || MemberSignaturesEquivalent(oldSelectInfo.Symbol, newSelectInfo.Symbol); case SyntaxKind.GroupClause: var oldGroupByInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newGroupByInfo = newModel.GetSymbolInfo(newNode, cancellationToken); return MemberSignaturesEquivalent(oldGroupByInfo.Symbol, newGroupByInfo.Symbol, GroupBySignatureComparer); default: return true; } } private static bool GroupBySignatureComparer(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType) { // C# spec paragraph 7.16.2.6 "Groupby clauses": // // A query expression of the form // from x in e group v by k // is translated into // (e).GroupBy(x => k, x => v) // except when v is the identifier x, the translation is // (e).GroupBy(x => k) // // Possible signatures: // C<G<K, T>> GroupBy<K>(Func<T, K> keySelector); // C<G<K, E>> GroupBy<K, E>(Func<T, K> keySelector, Func<T, E> elementSelector); if (!TypesEquivalent(oldReturnType, newReturnType, exact: false)) { return false; } Debug.Assert(oldParameters.Length == 1 || oldParameters.Length == 2); Debug.Assert(newParameters.Length == 1 || newParameters.Length == 2); // The types of the lambdas have to be the same if present. // The element selector may be added/removed. if (!ParameterTypesEquivalent(oldParameters[0], newParameters[0], exact: false)) { return false; } if (oldParameters.Length == newParameters.Length && newParameters.Length == 2) { return ParameterTypesEquivalent(oldParameters[1], newParameters[1], exact: false); } return true; } #endregion #region Diagnostic Info protected override SymbolDisplayFormat ErrorDisplayFormat => SymbolDisplayFormat.CSharpErrorMessageFormat; protected override TextSpan? TryGetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node, editKind); internal static new TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node, editKind) ?? node.Span; private static TextSpan? TryGetDiagnosticSpanImpl(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node.Kind(), node, editKind); // internal for testing; kind is passed explicitly for testing as well internal static TextSpan? TryGetDiagnosticSpanImpl(SyntaxKind kind, SyntaxNode node, EditKind editKind) { switch (kind) { case SyntaxKind.CompilationUnit: return default(TextSpan); case SyntaxKind.GlobalStatement: return node.Span; case SyntaxKind.ExternAliasDirective: case SyntaxKind.UsingDirective: return node.Span; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: var ns = (BaseNamespaceDeclarationSyntax)node; return TextSpan.FromBounds(ns.NamespaceKeyword.SpanStart, ns.Name.Span.End); case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: var typeDeclaration = (TypeDeclarationSyntax)node; return GetDiagnosticSpan(typeDeclaration.Modifiers, typeDeclaration.Keyword, typeDeclaration.TypeParameterList ?? (SyntaxNodeOrToken)typeDeclaration.Identifier); case SyntaxKind.EnumDeclaration: var enumDeclaration = (EnumDeclarationSyntax)node; return GetDiagnosticSpan(enumDeclaration.Modifiers, enumDeclaration.EnumKeyword, enumDeclaration.Identifier); case SyntaxKind.DelegateDeclaration: var delegateDeclaration = (DelegateDeclarationSyntax)node; return GetDiagnosticSpan(delegateDeclaration.Modifiers, delegateDeclaration.DelegateKeyword, delegateDeclaration.ParameterList); case SyntaxKind.FieldDeclaration: var fieldDeclaration = (BaseFieldDeclarationSyntax)node; return GetDiagnosticSpan(fieldDeclaration.Modifiers, fieldDeclaration.Declaration, fieldDeclaration.Declaration); case SyntaxKind.EventFieldDeclaration: var eventFieldDeclaration = (EventFieldDeclarationSyntax)node; return GetDiagnosticSpan(eventFieldDeclaration.Modifiers, eventFieldDeclaration.EventKeyword, eventFieldDeclaration.Declaration); case SyntaxKind.VariableDeclaration: return TryGetDiagnosticSpanImpl(node.Parent!, editKind); case SyntaxKind.VariableDeclarator: return node.Span; case SyntaxKind.MethodDeclaration: var methodDeclaration = (MethodDeclarationSyntax)node; return GetDiagnosticSpan(methodDeclaration.Modifiers, methodDeclaration.ReturnType, methodDeclaration.ParameterList); case SyntaxKind.ConversionOperatorDeclaration: var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node; return GetDiagnosticSpan(conversionOperatorDeclaration.Modifiers, conversionOperatorDeclaration.ImplicitOrExplicitKeyword, conversionOperatorDeclaration.ParameterList); case SyntaxKind.OperatorDeclaration: var operatorDeclaration = (OperatorDeclarationSyntax)node; return GetDiagnosticSpan(operatorDeclaration.Modifiers, operatorDeclaration.ReturnType, operatorDeclaration.ParameterList); case SyntaxKind.ConstructorDeclaration: var constructorDeclaration = (ConstructorDeclarationSyntax)node; return GetDiagnosticSpan(constructorDeclaration.Modifiers, constructorDeclaration.Identifier, constructorDeclaration.ParameterList); case SyntaxKind.DestructorDeclaration: var destructorDeclaration = (DestructorDeclarationSyntax)node; return GetDiagnosticSpan(destructorDeclaration.Modifiers, destructorDeclaration.TildeToken, destructorDeclaration.ParameterList); case SyntaxKind.PropertyDeclaration: var propertyDeclaration = (PropertyDeclarationSyntax)node; return GetDiagnosticSpan(propertyDeclaration.Modifiers, propertyDeclaration.Type, propertyDeclaration.Identifier); case SyntaxKind.IndexerDeclaration: var indexerDeclaration = (IndexerDeclarationSyntax)node; return GetDiagnosticSpan(indexerDeclaration.Modifiers, indexerDeclaration.Type, indexerDeclaration.ParameterList); case SyntaxKind.EventDeclaration: var eventDeclaration = (EventDeclarationSyntax)node; return GetDiagnosticSpan(eventDeclaration.Modifiers, eventDeclaration.EventKeyword, eventDeclaration.Identifier); case SyntaxKind.EnumMemberDeclaration: return node.Span; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.UnknownAccessorDeclaration: var accessorDeclaration = (AccessorDeclarationSyntax)node; return GetDiagnosticSpan(accessorDeclaration.Modifiers, accessorDeclaration.Keyword, accessorDeclaration.Keyword); case SyntaxKind.TypeParameterConstraintClause: var constraint = (TypeParameterConstraintClauseSyntax)node; return TextSpan.FromBounds(constraint.WhereKeyword.SpanStart, constraint.Constraints.Last().Span.End); case SyntaxKind.TypeParameter: var typeParameter = (TypeParameterSyntax)node; return typeParameter.Identifier.Span; case SyntaxKind.AccessorList: case SyntaxKind.TypeParameterList: case SyntaxKind.ParameterList: case SyntaxKind.BracketedParameterList: if (editKind == EditKind.Delete) { return TryGetDiagnosticSpanImpl(node.Parent!, editKind); } else { return node.Span; } case SyntaxKind.Parameter: var parameter = (ParameterSyntax)node; // Lambda parameters don't have types or modifiers, so the parameter is the only node var startNode = parameter.Type ?? (SyntaxNode)parameter; return GetDiagnosticSpan(parameter.Modifiers, startNode, parameter); case SyntaxKind.AttributeList: var attributeList = (AttributeListSyntax)node; return attributeList.Span; case SyntaxKind.Attribute: return node.Span; case SyntaxKind.ArrowExpressionClause: return TryGetDiagnosticSpanImpl(node.Parent!, editKind); // We only need a diagnostic span if reporting an error for a child statement. // The following statements may have child statements. case SyntaxKind.Block: return ((BlockSyntax)node).OpenBraceToken.Span; case SyntaxKind.UsingStatement: var usingStatement = (UsingStatementSyntax)node; return TextSpan.FromBounds(usingStatement.UsingKeyword.SpanStart, usingStatement.CloseParenToken.Span.End); case SyntaxKind.FixedStatement: var fixedStatement = (FixedStatementSyntax)node; return TextSpan.FromBounds(fixedStatement.FixedKeyword.SpanStart, fixedStatement.CloseParenToken.Span.End); case SyntaxKind.LockStatement: var lockStatement = (LockStatementSyntax)node; return TextSpan.FromBounds(lockStatement.LockKeyword.SpanStart, lockStatement.CloseParenToken.Span.End); case SyntaxKind.StackAllocArrayCreationExpression: return ((StackAllocArrayCreationExpressionSyntax)node).StackAllocKeyword.Span; case SyntaxKind.ImplicitStackAllocArrayCreationExpression: return ((ImplicitStackAllocArrayCreationExpressionSyntax)node).StackAllocKeyword.Span; case SyntaxKind.TryStatement: return ((TryStatementSyntax)node).TryKeyword.Span; case SyntaxKind.CatchClause: return ((CatchClauseSyntax)node).CatchKeyword.Span; case SyntaxKind.CatchDeclaration: case SyntaxKind.CatchFilterClause: return node.Span; case SyntaxKind.FinallyClause: return ((FinallyClauseSyntax)node).FinallyKeyword.Span; case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)node; return TextSpan.FromBounds(ifStatement.IfKeyword.SpanStart, ifStatement.CloseParenToken.Span.End); case SyntaxKind.ElseClause: return ((ElseClauseSyntax)node).ElseKeyword.Span; case SyntaxKind.SwitchStatement: var switchStatement = (SwitchStatementSyntax)node; return TextSpan.FromBounds(switchStatement.SwitchKeyword.SpanStart, (switchStatement.CloseParenToken != default) ? switchStatement.CloseParenToken.Span.End : switchStatement.Expression.Span.End); case SyntaxKind.SwitchSection: return ((SwitchSectionSyntax)node).Labels.Last().Span; case SyntaxKind.WhileStatement: var whileStatement = (WhileStatementSyntax)node; return TextSpan.FromBounds(whileStatement.WhileKeyword.SpanStart, whileStatement.CloseParenToken.Span.End); case SyntaxKind.DoStatement: return ((DoStatementSyntax)node).DoKeyword.Span; case SyntaxKind.ForStatement: var forStatement = (ForStatementSyntax)node; return TextSpan.FromBounds(forStatement.ForKeyword.SpanStart, forStatement.CloseParenToken.Span.End); case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: var commonForEachStatement = (CommonForEachStatementSyntax)node; return TextSpan.FromBounds( (commonForEachStatement.AwaitKeyword.Span.Length > 0) ? commonForEachStatement.AwaitKeyword.SpanStart : commonForEachStatement.ForEachKeyword.SpanStart, commonForEachStatement.CloseParenToken.Span.End); case SyntaxKind.LabeledStatement: return ((LabeledStatementSyntax)node).Identifier.Span; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return ((CheckedStatementSyntax)node).Keyword.Span; case SyntaxKind.UnsafeStatement: return ((UnsafeStatementSyntax)node).UnsafeKeyword.Span; case SyntaxKind.LocalFunctionStatement: var lfd = (LocalFunctionStatementSyntax)node; return lfd.Identifier.Span; case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.ExpressionStatement: case SyntaxKind.EmptyStatement: case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: return node.Span; case SyntaxKind.LocalDeclarationStatement: var localDeclarationStatement = (LocalDeclarationStatementSyntax)node; return CombineSpans(localDeclarationStatement.AwaitKeyword.Span, localDeclarationStatement.UsingKeyword.Span, node.Span); case SyntaxKind.AwaitExpression: return ((AwaitExpressionSyntax)node).AwaitKeyword.Span; case SyntaxKind.AnonymousObjectCreationExpression: return ((AnonymousObjectCreationExpressionSyntax)node).NewKeyword.Span; case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)node).ParameterList.Span; case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)node).Parameter.Span; case SyntaxKind.AnonymousMethodExpression: return ((AnonymousMethodExpressionSyntax)node).DelegateKeyword.Span; case SyntaxKind.QueryExpression: return ((QueryExpressionSyntax)node).FromClause.FromKeyword.Span; case SyntaxKind.QueryBody: var queryBody = (QueryBodySyntax)node; return TryGetDiagnosticSpanImpl(queryBody.Clauses.FirstOrDefault() ?? queryBody.Parent!, editKind); case SyntaxKind.QueryContinuation: return ((QueryContinuationSyntax)node).IntoKeyword.Span; case SyntaxKind.FromClause: return ((FromClauseSyntax)node).FromKeyword.Span; case SyntaxKind.JoinClause: return ((JoinClauseSyntax)node).JoinKeyword.Span; case SyntaxKind.JoinIntoClause: return ((JoinIntoClauseSyntax)node).IntoKeyword.Span; case SyntaxKind.LetClause: return ((LetClauseSyntax)node).LetKeyword.Span; case SyntaxKind.WhereClause: return ((WhereClauseSyntax)node).WhereKeyword.Span; case SyntaxKind.OrderByClause: return ((OrderByClauseSyntax)node).OrderByKeyword.Span; case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return node.Span; case SyntaxKind.SelectClause: return ((SelectClauseSyntax)node).SelectKeyword.Span; case SyntaxKind.GroupClause: return ((GroupClauseSyntax)node).GroupKeyword.Span; case SyntaxKind.IsPatternExpression: case SyntaxKind.TupleType: case SyntaxKind.TupleExpression: case SyntaxKind.DeclarationExpression: case SyntaxKind.RefType: case SyntaxKind.RefExpression: case SyntaxKind.DeclarationPattern: case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.WhenClause: case SyntaxKind.SingleVariableDesignation: case SyntaxKind.CasePatternSwitchLabel: return node.Span; case SyntaxKind.SwitchExpression: return ((SwitchExpressionSyntax)node).SwitchKeyword.Span; case SyntaxKind.SwitchExpressionArm: return ((SwitchExpressionArmSyntax)node).EqualsGreaterThanToken.Span; default: return null; } } private static TextSpan GetDiagnosticSpan(SyntaxTokenList modifiers, SyntaxNodeOrToken start, SyntaxNodeOrToken end) => TextSpan.FromBounds((modifiers.Count != 0) ? modifiers.First().SpanStart : start.SpanStart, end.Span.End); private static TextSpan CombineSpans(TextSpan first, TextSpan second, TextSpan defaultSpan) => (first.Length > 0 && second.Length > 0) ? TextSpan.FromBounds(first.Start, second.End) : (first.Length > 0) ? first : (second.Length > 0) ? second : defaultSpan; internal override TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal) { Debug.Assert(ordinal >= 0); switch (lambda.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)lambda).ParameterList.Parameters[ordinal].Identifier.Span; case SyntaxKind.SimpleLambdaExpression: Debug.Assert(ordinal == 0); return ((SimpleLambdaExpressionSyntax)lambda).Parameter.Identifier.Span; case SyntaxKind.AnonymousMethodExpression: // since we are given a parameter ordinal there has to be a parameter list: return ((AnonymousMethodExpressionSyntax)lambda).ParameterList!.Parameters[ordinal].Identifier.Span; default: return lambda.Span; } } internal override string GetDisplayName(INamedTypeSymbol symbol) => symbol.TypeKind switch { TypeKind.Struct => symbol.IsRecord ? CSharpFeaturesResources.record_struct : CSharpFeaturesResources.struct_, TypeKind.Class => symbol.IsRecord ? CSharpFeaturesResources.record_ : FeaturesResources.class_, _ => base.GetDisplayName(symbol) }; internal override string GetDisplayName(IPropertySymbol symbol) => symbol.IsIndexer ? CSharpFeaturesResources.indexer : base.GetDisplayName(symbol); internal override string GetDisplayName(IMethodSymbol symbol) => symbol.MethodKind switch { MethodKind.PropertyGet => symbol.AssociatedSymbol is IPropertySymbol { IsIndexer: true } ? CSharpFeaturesResources.indexer_getter : CSharpFeaturesResources.property_getter, MethodKind.PropertySet => symbol.AssociatedSymbol is IPropertySymbol { IsIndexer: true } ? CSharpFeaturesResources.indexer_setter : CSharpFeaturesResources.property_setter, MethodKind.StaticConstructor => FeaturesResources.static_constructor, MethodKind.Destructor => CSharpFeaturesResources.destructor, MethodKind.Conversion => CSharpFeaturesResources.conversion_operator, MethodKind.LocalFunction => FeaturesResources.local_function, _ => base.GetDisplayName(symbol) }; protected override string? TryGetDisplayName(SyntaxNode node, EditKind editKind) => TryGetDisplayNameImpl(node, editKind); internal static new string? GetDisplayName(SyntaxNode node, EditKind editKind) => TryGetDisplayNameImpl(node, editKind) ?? throw ExceptionUtilities.UnexpectedValue(node.Kind()); internal static string? TryGetDisplayNameImpl(SyntaxNode node, EditKind editKind) { switch (node.Kind()) { // top-level case SyntaxKind.CompilationUnit: case SyntaxKind.GlobalStatement: return CSharpFeaturesResources.global_statement; case SyntaxKind.ExternAliasDirective: return CSharpFeaturesResources.extern_alias; case SyntaxKind.UsingDirective: // Dev12 distinguishes using alias from using namespace and reports different errors for removing alias. // None of these changes are allowed anyways, so let's keep it simple. return CSharpFeaturesResources.using_directive; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return FeaturesResources.namespace_; case SyntaxKind.ClassDeclaration: return FeaturesResources.class_; case SyntaxKind.StructDeclaration: return CSharpFeaturesResources.struct_; case SyntaxKind.InterfaceDeclaration: return FeaturesResources.interface_; case SyntaxKind.RecordDeclaration: return CSharpFeaturesResources.record_; case SyntaxKind.RecordStructDeclaration: return CSharpFeaturesResources.record_struct; case SyntaxKind.EnumDeclaration: return FeaturesResources.enum_; case SyntaxKind.DelegateDeclaration: return FeaturesResources.delegate_; case SyntaxKind.FieldDeclaration: var declaration = (FieldDeclarationSyntax)node; return declaration.Modifiers.Any(SyntaxKind.ConstKeyword) ? FeaturesResources.const_field : FeaturesResources.field; case SyntaxKind.EventFieldDeclaration: return CSharpFeaturesResources.event_field; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: return TryGetDisplayNameImpl(node.Parent!, editKind); case SyntaxKind.MethodDeclaration: return FeaturesResources.method; case SyntaxKind.ConversionOperatorDeclaration: return CSharpFeaturesResources.conversion_operator; case SyntaxKind.OperatorDeclaration: return FeaturesResources.operator_; case SyntaxKind.ConstructorDeclaration: var ctor = (ConstructorDeclarationSyntax)node; return ctor.Modifiers.Any(SyntaxKind.StaticKeyword) ? FeaturesResources.static_constructor : FeaturesResources.constructor; case SyntaxKind.DestructorDeclaration: return CSharpFeaturesResources.destructor; case SyntaxKind.PropertyDeclaration: return SyntaxUtilities.HasBackingField((PropertyDeclarationSyntax)node) ? FeaturesResources.auto_property : FeaturesResources.property_; case SyntaxKind.IndexerDeclaration: return CSharpFeaturesResources.indexer; case SyntaxKind.EventDeclaration: return FeaturesResources.event_; case SyntaxKind.EnumMemberDeclaration: return FeaturesResources.enum_value; case SyntaxKind.GetAccessorDeclaration: if (node.Parent!.Parent!.IsKind(SyntaxKind.PropertyDeclaration)) { return CSharpFeaturesResources.property_getter; } else { RoslynDebug.Assert(node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration)); return CSharpFeaturesResources.indexer_getter; } case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: if (node.Parent!.Parent!.IsKind(SyntaxKind.PropertyDeclaration)) { return CSharpFeaturesResources.property_setter; } else { RoslynDebug.Assert(node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration)); return CSharpFeaturesResources.indexer_setter; } case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return FeaturesResources.event_accessor; case SyntaxKind.ArrowExpressionClause: return node.Parent!.Kind() switch { SyntaxKind.PropertyDeclaration => CSharpFeaturesResources.property_getter, SyntaxKind.IndexerDeclaration => CSharpFeaturesResources.indexer_getter, _ => null }; case SyntaxKind.TypeParameterConstraintClause: return FeaturesResources.type_constraint; case SyntaxKind.TypeParameterList: case SyntaxKind.TypeParameter: return FeaturesResources.type_parameter; case SyntaxKind.Parameter: return FeaturesResources.parameter; case SyntaxKind.AttributeList: return FeaturesResources.attribute; case SyntaxKind.Attribute: return FeaturesResources.attribute; case SyntaxKind.AttributeTargetSpecifier: return CSharpFeaturesResources.attribute_target; // statement: case SyntaxKind.TryStatement: return CSharpFeaturesResources.try_block; case SyntaxKind.CatchClause: case SyntaxKind.CatchDeclaration: return CSharpFeaturesResources.catch_clause; case SyntaxKind.CatchFilterClause: return CSharpFeaturesResources.filter_clause; case SyntaxKind.FinallyClause: return CSharpFeaturesResources.finally_clause; case SyntaxKind.FixedStatement: return CSharpFeaturesResources.fixed_statement; case SyntaxKind.UsingStatement: return CSharpFeaturesResources.using_statement; case SyntaxKind.LockStatement: return CSharpFeaturesResources.lock_statement; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return CSharpFeaturesResources.foreach_statement; case SyntaxKind.CheckedStatement: return CSharpFeaturesResources.checked_statement; case SyntaxKind.UncheckedStatement: return CSharpFeaturesResources.unchecked_statement; case SyntaxKind.YieldBreakStatement: return CSharpFeaturesResources.yield_break_statement; case SyntaxKind.YieldReturnStatement: return CSharpFeaturesResources.yield_return_statement; case SyntaxKind.AwaitExpression: return CSharpFeaturesResources.await_expression; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return CSharpFeaturesResources.lambda; case SyntaxKind.AnonymousMethodExpression: return CSharpFeaturesResources.anonymous_method; case SyntaxKind.FromClause: return CSharpFeaturesResources.from_clause; case SyntaxKind.JoinClause: case SyntaxKind.JoinIntoClause: return CSharpFeaturesResources.join_clause; case SyntaxKind.LetClause: return CSharpFeaturesResources.let_clause; case SyntaxKind.WhereClause: return CSharpFeaturesResources.where_clause; case SyntaxKind.OrderByClause: case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return CSharpFeaturesResources.orderby_clause; case SyntaxKind.SelectClause: return CSharpFeaturesResources.select_clause; case SyntaxKind.GroupClause: return CSharpFeaturesResources.groupby_clause; case SyntaxKind.QueryBody: return CSharpFeaturesResources.query_body; case SyntaxKind.QueryContinuation: return CSharpFeaturesResources.into_clause; case SyntaxKind.IsPatternExpression: return CSharpFeaturesResources.is_pattern; case SyntaxKind.SimpleAssignmentExpression: if (((AssignmentExpressionSyntax)node).IsDeconstruction()) { return CSharpFeaturesResources.deconstruction; } else { throw ExceptionUtilities.UnexpectedValue(node.Kind()); } case SyntaxKind.TupleType: case SyntaxKind.TupleExpression: return CSharpFeaturesResources.tuple; case SyntaxKind.LocalFunctionStatement: return CSharpFeaturesResources.local_function; case SyntaxKind.DeclarationExpression: return CSharpFeaturesResources.out_var; case SyntaxKind.RefType: case SyntaxKind.RefExpression: return CSharpFeaturesResources.ref_local_or_expression; case SyntaxKind.SwitchStatement: return CSharpFeaturesResources.switch_statement; case SyntaxKind.LocalDeclarationStatement: if (((LocalDeclarationStatementSyntax)node).UsingKeyword.IsKind(SyntaxKind.UsingKeyword)) { return CSharpFeaturesResources.using_declaration; } return CSharpFeaturesResources.local_variable_declaration; default: return null; } } protected override string GetSuspensionPointDisplayName(SyntaxNode node, EditKind editKind) { switch (node.Kind()) { case SyntaxKind.ForEachStatement: Debug.Assert(((CommonForEachStatementSyntax)node).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)); return CSharpFeaturesResources.asynchronous_foreach_statement; case SyntaxKind.VariableDeclarator: RoslynDebug.Assert(((LocalDeclarationStatementSyntax)node.Parent!.Parent!).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)); return CSharpFeaturesResources.asynchronous_using_declaration; default: return base.GetSuspensionPointDisplayName(node, editKind); } } #endregion #region Top-Level Syntactic Rude Edits private readonly struct EditClassifier { private readonly CSharpEditAndContinueAnalyzer _analyzer; private readonly ArrayBuilder<RudeEditDiagnostic> _diagnostics; private readonly Match<SyntaxNode>? _match; private readonly SyntaxNode? _oldNode; private readonly SyntaxNode? _newNode; private readonly EditKind _kind; private readonly TextSpan? _span; public EditClassifier( CSharpEditAndContinueAnalyzer analyzer, ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode? oldNode, SyntaxNode? newNode, EditKind kind, Match<SyntaxNode>? match = null, TextSpan? span = null) { RoslynDebug.Assert(oldNode != null || newNode != null); // if the node is deleted we have map that can be used to closest new ancestor RoslynDebug.Assert(newNode != null || match != null); _analyzer = analyzer; _diagnostics = diagnostics; _oldNode = oldNode; _newNode = newNode; _kind = kind; _span = span; _match = match; } private void ReportError(RudeEditKind kind, SyntaxNode? spanNode = null, SyntaxNode? displayNode = null) { var span = (spanNode != null) ? GetDiagnosticSpan(spanNode, _kind) : GetSpan(); var node = displayNode ?? _newNode ?? _oldNode; var displayName = GetDisplayName(node!, _kind); _diagnostics.Add(new RudeEditDiagnostic(kind, span, node, arguments: new[] { displayName })); } private TextSpan GetSpan() { if (_span.HasValue) { return _span.Value; } if (_newNode == null) { return _analyzer.GetDeletedNodeDiagnosticSpan(_match!.Matches, _oldNode!); } return GetDiagnosticSpan(_newNode, _kind); } public void ClassifyEdit() { switch (_kind) { case EditKind.Delete: ClassifyDelete(_oldNode!); return; case EditKind.Update: ClassifyUpdate(_oldNode!, _newNode!); return; case EditKind.Move: ClassifyMove(_newNode!); return; case EditKind.Insert: ClassifyInsert(_newNode!); return; case EditKind.Reorder: ClassifyReorder(_newNode!); return; default: throw ExceptionUtilities.UnexpectedValue(_kind); } } private void ClassifyMove(SyntaxNode newNode) { if (newNode.IsKind(SyntaxKind.LocalFunctionStatement)) { return; } // We could perhaps allow moving a type declaration to a different namespace syntax node // as long as it represents semantically the same namespace as the one of the original type declaration. ReportError(RudeEditKind.Move); } private void ClassifyReorder(SyntaxNode newNode) { if (_newNode.IsKind(SyntaxKind.LocalFunctionStatement)) { return; } switch (newNode.Kind()) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.VariableDeclarator: // Maybe we could allow changing order of field declarations unless the containing type layout is sequential. ReportError(RudeEditKind.Move); return; case SyntaxKind.EnumMemberDeclaration: // To allow this change we would need to check that values of all fields of the enum // are preserved, or make sure we can update all method bodies that accessed those that changed. ReportError(RudeEditKind.Move); return; case SyntaxKind.TypeParameter: case SyntaxKind.Parameter: ReportError(RudeEditKind.Move); return; } } private void ClassifyInsert(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.ExternAliasDirective: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: ReportError(RudeEditKind.Insert); return; case SyntaxKind.Attribute: case SyntaxKind.AttributeList: // To allow inserting of attributes we need to check if the inserted attribute // is a pseudo-custom attribute that CLR allows us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (node.IsParentKind(SyntaxKind.CompilationUnit) || node.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Insert); } return; } } private void ClassifyDelete(SyntaxNode oldNode) { switch (oldNode.Kind()) { case SyntaxKind.ExternAliasDirective: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: // To allow removal of declarations we would need to update method bodies that // were previously binding to them but now are binding to another symbol that was previously hidden. ReportError(RudeEditKind.Delete); return; case SyntaxKind.AttributeList: case SyntaxKind.Attribute: // To allow removal of attributes we need to check if the removed attribute // is a pseudo-custom attribute that CLR does not allow us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (oldNode.IsParentKind(SyntaxKind.CompilationUnit) || oldNode.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Delete); } return; } } private void ClassifyUpdate(SyntaxNode oldNode, SyntaxNode newNode) { switch (newNode.Kind()) { case SyntaxKind.ExternAliasDirective: ReportError(RudeEditKind.Update); return; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: ClassifyUpdate((BaseNamespaceDeclarationSyntax)oldNode, (BaseNamespaceDeclarationSyntax)newNode); return; case SyntaxKind.Attribute: // To allow update of attributes we need to check if the updated attribute // is a pseudo-custom attribute that CLR allows us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (newNode.IsParentKind(SyntaxKind.CompilationUnit) || newNode.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Update); } return; } } private void ClassifyUpdate(BaseNamespaceDeclarationSyntax oldNode, BaseNamespaceDeclarationSyntax newNode) { Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Name, newNode.Name)); ReportError(RudeEditKind.Renamed); } public void ClassifyDeclarationBodyRudeUpdates(SyntaxNode newDeclarationOrBody) { foreach (var node in newDeclarationOrBody.DescendantNodesAndSelf(LambdaUtilities.IsNotLambda)) { switch (node.Kind()) { case SyntaxKind.StackAllocArrayCreationExpression: case SyntaxKind.ImplicitStackAllocArrayCreationExpression: ReportError(RudeEditKind.StackAllocUpdate, node, _newNode); return; } } } } internal override void ReportTopLevelSyntacticRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap) { if (HasParentEdit(editMap, edit)) { return; } var classifier = new EditClassifier(this, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, match); classifier.ClassifyEdit(); } internal override void ReportMemberBodyUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span) { var classifier = new EditClassifier(this, diagnostics, oldNode: null, newMember, EditKind.Update, span: span); classifier.ClassifyDeclarationBodyRudeUpdates(newMember); } #endregion #region Semantic Rude Edits internal override void ReportInsertedMemberSymbolRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newNode, bool insertingIntoExistingContainingType) { var rudeEditKind = newSymbol switch { // Inserting extern member into a new or existing type is not allowed. { IsExtern: true } => RudeEditKind.InsertExtern, // All rude edits below only apply when inserting into an existing type (not when the type itself is inserted): _ when !insertingIntoExistingContainingType => RudeEditKind.None, // Inserting a member into an existing generic type is not allowed. { ContainingType: { Arity: > 0 } } and not INamedTypeSymbol => RudeEditKind.InsertIntoGenericType, // Inserting virtual or interface member into an existing type is not allowed. { IsVirtual: true } or { IsOverride: true } or { IsAbstract: true } and not INamedTypeSymbol => RudeEditKind.InsertVirtual, // Inserting generic method into an existing type is not allowed. IMethodSymbol { Arity: > 0 } => RudeEditKind.InsertGenericMethod, // Inserting destructor to an existing type is not allowed. IMethodSymbol { MethodKind: MethodKind.Destructor } => RudeEditKind.Insert, // Inserting operator to an existing type is not allowed. IMethodSymbol { MethodKind: MethodKind.Conversion or MethodKind.UserDefinedOperator } => RudeEditKind.InsertOperator, // Inserting a method that explictly implements an interface method into an existing type is not allowed. IMethodSymbol { ExplicitInterfaceImplementations: { IsEmpty: false } } => RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, // TODO: Inserting non-virtual member to an interface (https://github.com/dotnet/roslyn/issues/37128) { ContainingType: { TypeKind: TypeKind.Interface } } and not INamedTypeSymbol => RudeEditKind.InsertIntoInterface, // Inserting a field into an enum: #pragma warning disable format // https://github.com/dotnet/roslyn/issues/54759 IFieldSymbol { ContainingType.TypeKind: TypeKind.Enum } => RudeEditKind.Insert, #pragma warning restore format _ => RudeEditKind.None }; if (rudeEditKind != RudeEditKind.None) { diagnostics.Add(new RudeEditDiagnostic( rudeEditKind, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, arguments: new[] { GetDisplayName(newNode, EditKind.Insert) })); } } #endregion #region Exception Handling Rude Edits /// <summary> /// Return nodes that represent exception handlers encompassing the given active statement node. /// </summary> protected override List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isNonLeaf) { var result = new List<SyntaxNode>(); var current = node; while (current != null) { var kind = current.Kind(); switch (kind) { case SyntaxKind.TryStatement: if (isNonLeaf) { result.Add(current); } break; case SyntaxKind.CatchClause: case SyntaxKind.FinallyClause: result.Add(current); // skip try: RoslynDebug.Assert(current.Parent is object); RoslynDebug.Assert(current.Parent.Kind() == SyntaxKind.TryStatement); current = current.Parent; break; // stop at type declaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return result; } // stop at lambda: if (LambdaUtilities.IsLambda(current)) { return result; } current = current.Parent; } return result; } internal override void ReportEnclosingExceptionHandlingRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits, SyntaxNode oldStatement, TextSpan newStatementSpan) { foreach (var edit in exceptionHandlingEdits) { // try/catch/finally have distinct labels so only the nodes of the same kind may match: Debug.Assert(edit.Kind != EditKind.Update || edit.OldNode.RawKind == edit.NewNode.RawKind); if (edit.Kind != EditKind.Update || !AreExceptionClausesEquivalent(edit.OldNode, edit.NewNode)) { AddAroundActiveStatementRudeDiagnostic(diagnostics, edit.OldNode, edit.NewNode, newStatementSpan); } } } private static bool AreExceptionClausesEquivalent(SyntaxNode oldNode, SyntaxNode newNode) { switch (oldNode.Kind()) { case SyntaxKind.TryStatement: var oldTryStatement = (TryStatementSyntax)oldNode; var newTryStatement = (TryStatementSyntax)newNode; return SyntaxFactory.AreEquivalent(oldTryStatement.Finally, newTryStatement.Finally) && SyntaxFactory.AreEquivalent(oldTryStatement.Catches, newTryStatement.Catches); case SyntaxKind.CatchClause: case SyntaxKind.FinallyClause: return SyntaxFactory.AreEquivalent(oldNode, newNode); default: throw ExceptionUtilities.UnexpectedValue(oldNode.Kind()); } } /// <summary> /// An active statement (leaf or not) inside a "catch" makes the catch block read-only. /// An active statement (leaf or not) inside a "finally" makes the whole try/catch/finally block read-only. /// An active statement (non leaf) inside a "try" makes the catch/finally block read-only. /// </summary> /// <remarks> /// Exception handling regions are only needed to be tracked if they contain user code. /// <see cref="UsingStatementSyntax"/> and using <see cref="LocalDeclarationStatementSyntax"/> generate finally blocks, /// but they do not contain non-hidden sequence points. /// </remarks> /// <param name="node">An exception handling ancestor of an active statement node.</param> /// <param name="coversAllChildren"> /// True if all child nodes of the <paramref name="node"/> are contained in the exception region represented by the <paramref name="node"/>. /// </param> protected override TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren) { TryStatementSyntax tryStatement; switch (node.Kind()) { case SyntaxKind.TryStatement: tryStatement = (TryStatementSyntax)node; coversAllChildren = false; if (tryStatement.Catches.Count == 0) { RoslynDebug.Assert(tryStatement.Finally != null); return tryStatement.Finally.Span; } return TextSpan.FromBounds( tryStatement.Catches.First().SpanStart, (tryStatement.Finally != null) ? tryStatement.Finally.Span.End : tryStatement.Catches.Last().Span.End); case SyntaxKind.CatchClause: coversAllChildren = true; return node.Span; case SyntaxKind.FinallyClause: coversAllChildren = true; tryStatement = (TryStatementSyntax)node.Parent!; return tryStatement.Span; default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } #endregion #region State Machines internal override bool IsStateMachineMethod(SyntaxNode declaration) => SyntaxUtilities.IsAsyncDeclaration(declaration) || SyntaxUtilities.GetSuspensionPoints(declaration).Any(); protected override void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKinds kinds) { suspensionPoints = SyntaxUtilities.GetSuspensionPoints(body).ToImmutableArray(); kinds = StateMachineKinds.None; if (suspensionPoints.Any(n => n.IsKind(SyntaxKind.YieldBreakStatement) || n.IsKind(SyntaxKind.YieldReturnStatement))) { kinds |= StateMachineKinds.Iterator; } if (SyntaxUtilities.IsAsyncDeclaration(body.Parent)) { kinds |= StateMachineKinds.Async; } } internal override void ReportStateMachineSuspensionPointRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode) { // TODO: changes around suspension points (foreach, lock, using, etc.) if (newNode.IsKind(SyntaxKind.AwaitExpression)) { var oldContainingStatementPart = FindContainingStatementPart(oldNode); var newContainingStatementPart = FindContainingStatementPart(newNode); // If the old statement has spilled state and the new doesn't the edit is ok. We'll just not use the spilled state. if (!SyntaxFactory.AreEquivalent(oldContainingStatementPart, newContainingStatementPart) && !HasNoSpilledState(newNode, newContainingStatementPart)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.AwaitStatementUpdate, newContainingStatementPart.Span)); } } } internal override void ReportStateMachineSuspensionPointDeletedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode deletedSuspensionPoint) { // Handle deletion of await keyword from await foreach statement. if (deletedSuspensionPoint is CommonForEachStatementSyntax deletedForeachStatement && match.Matches.TryGetValue(deletedSuspensionPoint, out var newForEachStatement) && newForEachStatement is CommonForEachStatementSyntax && deletedForeachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetDiagnosticSpan(newForEachStatement, EditKind.Update), newForEachStatement, new[] { GetDisplayName(newForEachStatement, EditKind.Update) })); return; } // Handle deletion of await keyword from await using declaration. if (deletedSuspensionPoint.IsKind(SyntaxKind.VariableDeclarator) && match.Matches.TryGetValue(deletedSuspensionPoint.Parent!.Parent!, out var newLocalDeclaration) && !((LocalDeclarationStatementSyntax)newLocalDeclaration).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetDiagnosticSpan(newLocalDeclaration, EditKind.Update), newLocalDeclaration, new[] { GetDisplayName(newLocalDeclaration, EditKind.Update) })); return; } base.ReportStateMachineSuspensionPointDeletedRudeEdit(diagnostics, match, deletedSuspensionPoint); } internal override void ReportStateMachineSuspensionPointInsertedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode insertedSuspensionPoint, bool aroundActiveStatement) { // Handle addition of await keyword to foreach statement. if (insertedSuspensionPoint is CommonForEachStatementSyntax insertedForEachStatement && match.ReverseMatches.TryGetValue(insertedSuspensionPoint, out var oldNode) && oldNode is CommonForEachStatementSyntax oldForEachStatement && !oldForEachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, insertedForEachStatement.AwaitKeyword.Span, insertedForEachStatement, new[] { insertedForEachStatement.AwaitKeyword.ToString() })); return; } // Handle addition of using keyword to using declaration. if (insertedSuspensionPoint.IsKind(SyntaxKind.VariableDeclarator) && match.ReverseMatches.TryGetValue(insertedSuspensionPoint.Parent!.Parent!, out var oldLocalDeclaration) && !((LocalDeclarationStatementSyntax)oldLocalDeclaration).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { var newLocalDeclaration = (LocalDeclarationStatementSyntax)insertedSuspensionPoint!.Parent!.Parent!; diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, newLocalDeclaration.AwaitKeyword.Span, newLocalDeclaration, new[] { newLocalDeclaration.AwaitKeyword.ToString() })); return; } base.ReportStateMachineSuspensionPointInsertedRudeEdit(diagnostics, match, insertedSuspensionPoint, aroundActiveStatement); } private static SyntaxNode FindContainingStatementPart(SyntaxNode node) { while (true) { if (node is StatementSyntax statement) { return statement; } RoslynDebug.Assert(node is object); RoslynDebug.Assert(node.Parent is object); switch (node.Parent.Kind()) { case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.IfStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.LockStatement: case SyntaxKind.UsingStatement: case SyntaxKind.ArrowExpressionClause: return node; } if (LambdaUtilities.IsLambdaBodyStatementOrExpression(node)) { return node; } node = node.Parent; } } private static bool HasNoSpilledState(SyntaxNode awaitExpression, SyntaxNode containingStatementPart) { Debug.Assert(awaitExpression.IsKind(SyntaxKind.AwaitExpression)); // There is nothing within the statement part surrounding the await expression. if (containingStatementPart == awaitExpression) { return true; } switch (containingStatementPart.Kind()) { case SyntaxKind.ExpressionStatement: case SyntaxKind.ReturnStatement: var expression = GetExpressionFromStatementPart(containingStatementPart); // await expr; // return await expr; if (expression == awaitExpression) { return true; } // identifier = await expr; // return identifier = await expr; return IsSimpleAwaitAssignment(expression, awaitExpression); case SyntaxKind.VariableDeclaration: // var idf = await expr in using, for, etc. // EqualsValueClause -> VariableDeclarator -> VariableDeclaration return awaitExpression.Parent!.Parent!.Parent == containingStatementPart; case SyntaxKind.LocalDeclarationStatement: // var idf = await expr; // EqualsValueClause -> VariableDeclarator -> VariableDeclaration -> LocalDeclarationStatement return awaitExpression.Parent!.Parent!.Parent!.Parent == containingStatementPart; } return IsSimpleAwaitAssignment(containingStatementPart, awaitExpression); } private static ExpressionSyntax GetExpressionFromStatementPart(SyntaxNode statement) { switch (statement.Kind()) { case SyntaxKind.ExpressionStatement: return ((ExpressionStatementSyntax)statement).Expression; case SyntaxKind.ReturnStatement: // Must have an expression since we are only inspecting at statements that contain an expression. return ((ReturnStatementSyntax)statement).Expression!; default: throw ExceptionUtilities.UnexpectedValue(statement.Kind()); } } private static bool IsSimpleAwaitAssignment(SyntaxNode node, SyntaxNode awaitExpression) { if (node.IsKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment)) { return assignment.Left.IsKind(SyntaxKind.IdentifierName) && assignment.Right == awaitExpression; } return false; } #endregion #region Rude Edits around Active Statement internal override void ReportOtherRudeEditsAroundActiveStatement( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, bool isNonLeaf) { ReportRudeEditsForSwitchWhenClauses(diagnostics, oldActiveStatement, newActiveStatement); ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics, match, oldActiveStatement, newActiveStatement); ReportRudeEditsForCheckedStatements(diagnostics, oldActiveStatement, newActiveStatement, isNonLeaf); } /// <summary> /// Reports rude edits when an active statement is a when clause in a switch statement and any of the switch cases or the switch value changed. /// This is necessary since the switch emits long-lived synthesized variables to store results of pattern evaluations. /// These synthesized variables are mapped to the slots of the new methods via ordinals. The mapping preserves the values of these variables as long as /// exactly the same variables are emitted for the new switch as they were for the old one and their order didn't change either. /// This is guaranteed if none of the case clauses have changed. /// </summary> private void ReportRudeEditsForSwitchWhenClauses(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement) { if (!oldActiveStatement.IsKind(SyntaxKind.WhenClause)) { return; } // switch expression does not have sequence points (active statements): if (!(oldActiveStatement.Parent!.Parent!.Parent is SwitchStatementSyntax oldSwitch)) { return; } // switch statement does not match switch expression, so it must be part of a switch statement as well. var newSwitch = (SwitchStatementSyntax)newActiveStatement.Parent!.Parent!.Parent!; // when clauses can only match other when clauses: Debug.Assert(newActiveStatement.IsKind(SyntaxKind.WhenClause)); if (!AreEquivalentIgnoringLambdaBodies(oldSwitch.Expression, newSwitch.Expression)) { AddRudeUpdateAroundActiveStatement(diagnostics, newSwitch); } if (!AreEquivalentSwitchStatementDecisionTrees(oldSwitch, newSwitch)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, GetDiagnosticSpan(newSwitch, EditKind.Update), newSwitch, new[] { CSharpFeaturesResources.switch_statement_case_clause })); } } private static bool AreEquivalentSwitchStatementDecisionTrees(SwitchStatementSyntax oldSwitch, SwitchStatementSyntax newSwitch) => oldSwitch.Sections.SequenceEqual(newSwitch.Sections, AreSwitchSectionsEquivalent); private static bool AreSwitchSectionsEquivalent(SwitchSectionSyntax oldSection, SwitchSectionSyntax newSection) => oldSection.Labels.SequenceEqual(newSection.Labels, AreLabelsEquivalent); private static bool AreLabelsEquivalent(SwitchLabelSyntax oldLabel, SwitchLabelSyntax newLabel) { if (oldLabel.IsKind(SyntaxKind.CasePatternSwitchLabel, out CasePatternSwitchLabelSyntax? oldCasePatternLabel) && newLabel.IsKind(SyntaxKind.CasePatternSwitchLabel, out CasePatternSwitchLabelSyntax? newCasePatternLabel)) { // ignore the actual when expressions: return SyntaxFactory.AreEquivalent(oldCasePatternLabel.Pattern, newCasePatternLabel.Pattern) && (oldCasePatternLabel.WhenClause != null) == (newCasePatternLabel.WhenClause != null); } else { return SyntaxFactory.AreEquivalent(oldLabel, newLabel); } } private void ReportRudeEditsForCheckedStatements( ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, bool isNonLeaf) { // checked context can't be changed around non-leaf active statement: if (!isNonLeaf) { return; } // Changing checked context around an internal active statement may change the instructions // executed after method calls in the active statement but before the next sequence point. // Since the debugger remaps the IP at the first sequence point following a call instruction // allowing overflow context to be changed may lead to execution of code with old semantics. var oldCheckedStatement = TryGetCheckedStatementAncestor(oldActiveStatement); var newCheckedStatement = TryGetCheckedStatementAncestor(newActiveStatement); bool isRude; if (oldCheckedStatement == null || newCheckedStatement == null) { isRude = oldCheckedStatement != newCheckedStatement; } else { isRude = oldCheckedStatement.Kind() != newCheckedStatement.Kind(); } if (isRude) { AddAroundActiveStatementRudeDiagnostic(diagnostics, oldCheckedStatement, newCheckedStatement, newActiveStatement.Span); } } private static CheckedStatementSyntax? TryGetCheckedStatementAncestor(SyntaxNode? node) { // Ignoring lambda boundaries since checked context flows through. while (node != null) { switch (node.Kind()) { case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return (CheckedStatementSyntax)node; } node = node.Parent; } return null; } private void ReportRudeEditsForAncestorsDeclaringInterStatementTemps( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement) { // Rude Edits for fixed/using/lock/foreach statements that are added/updated around an active statement. // Although such changes are technically possible, they might lead to confusion since // the temporary variables these statements generate won't be properly initialized. // // We use a simple algorithm to match each new node with its old counterpart. // If all nodes match this algorithm is linear, otherwise it's quadratic. // // Unlike exception regions matching where we use LCS, we allow reordering of the statements. ReportUnmatchedStatements<LockStatementSyntax>(diagnostics, match, n => n.IsKind(SyntaxKind.LockStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: null); ReportUnmatchedStatements<FixedStatementSyntax>(diagnostics, match, n => n.IsKind(SyntaxKind.FixedStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: (n1, n2) => DeclareSameIdentifiers(n1.Declaration.Variables, n2.Declaration.Variables)); // Using statements with declaration do not introduce compiler generated temporary. ReportUnmatchedStatements<UsingStatementSyntax>( diagnostics, match, n => n.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? usingStatement) && usingStatement.Declaration is null, oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: null); ReportUnmatchedStatements<CommonForEachStatementSyntax>( diagnostics, match, n => n.IsKind(SyntaxKind.ForEachStatement) || n.IsKind(SyntaxKind.ForEachVariableStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: AreSimilarActiveStatements); } private static bool DeclareSameIdentifiers(SeparatedSyntaxList<VariableDeclaratorSyntax> oldVariables, SeparatedSyntaxList<VariableDeclaratorSyntax> newVariables) => DeclareSameIdentifiers(oldVariables.Select(v => v.Identifier).ToArray(), newVariables.Select(v => v.Identifier).ToArray()); private static bool DeclareSameIdentifiers(SyntaxToken[] oldVariables, SyntaxToken[] newVariables) { if (oldVariables.Length != newVariables.Length) { return false; } for (var i = 0; i < oldVariables.Length; i++) { if (!SyntaxFactory.AreEquivalent(oldVariables[i], newVariables[i])) { return false; } } return true; } #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.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue { internal sealed class CSharpEditAndContinueAnalyzer : AbstractEditAndContinueAnalyzer { [ExportLanguageServiceFactory(typeof(IEditAndContinueAnalyzer), LanguageNames.CSharp), Shared] internal sealed class Factory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Factory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) { return new CSharpEditAndContinueAnalyzer(testFaultInjector: null); } } // Public for testing purposes public CSharpEditAndContinueAnalyzer(Action<SyntaxNode>? testFaultInjector = null) : base(testFaultInjector) { } #region Syntax Analysis private enum BlockPart { OpenBrace = DefaultStatementPart, CloseBrace = 1, } private enum ForEachPart { ForEach = DefaultStatementPart, VariableDeclaration = 1, In = 2, Expression = 3, } private enum SwitchExpressionPart { WholeExpression = DefaultStatementPart, // An active statement that covers IL generated for the decision tree: // <governing-expression> [|switch { <arm>, ..., <arm> }|] // This active statement is never a leaf active statement (does not correspond to a breakpoint span). SwitchBody = 1, } /// <returns> /// <see cref="BaseMethodDeclarationSyntax"/> for methods, operators, constructors, destructors and accessors. /// <see cref="VariableDeclaratorSyntax"/> for field initializers. /// <see cref="PropertyDeclarationSyntax"/> for property initializers and expression bodies. /// <see cref="IndexerDeclarationSyntax"/> for indexer expression bodies. /// <see cref="ArrowExpressionClauseSyntax"/> for getter of an expression-bodied property/indexer. /// </returns> internal override bool TryFindMemberDeclaration(SyntaxNode? root, SyntaxNode node, out OneOrMany<SyntaxNode> declarations) { var current = node; while (current != null && current != root) { switch (current.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: declarations = new(current); return true; case SyntaxKind.PropertyDeclaration: // int P { get; } = [|initializer|]; RoslynDebug.Assert(((PropertyDeclarationSyntax)current).Initializer != null); declarations = new(current); return true; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: // Active statements encompassing modifiers or type correspond to the first initialized field. // [|public static int F = 1|], G = 2; declarations = new(((BaseFieldDeclarationSyntax)current).Declaration.Variables.First()); return true; case SyntaxKind.VariableDeclarator: // public static int F = 1, [|G = 2|]; RoslynDebug.Assert(current.Parent.IsKind(SyntaxKind.VariableDeclaration)); switch (current.Parent.Parent!.Kind()) { case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: declarations = new(current); return true; } current = current.Parent; break; case SyntaxKind.ArrowExpressionClause: // represents getter symbol declaration node of a property/indexer with expression body if (current.Parent.IsKind(SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration)) { declarations = new(current); return true; } break; } current = current.Parent; } declarations = default; return false; } /// <returns> /// Given a node representing a declaration or a top-level match node returns: /// - <see cref="BlockSyntax"/> for method-like member declarations with block bodies (methods, operators, constructors, destructors, accessors). /// - <see cref="ExpressionSyntax"/> for variable declarators of fields, properties with an initializer expression, or /// for method-like member declarations with expression bodies (methods, properties, indexers, operators) /// - <see cref="CompilationUnitSyntax"/> for top level statements /// /// A null reference otherwise. /// </returns> internal override SyntaxNode? TryGetDeclarationBody(SyntaxNode node) { if (node.IsKind(SyntaxKind.VariableDeclarator, out VariableDeclaratorSyntax? variableDeclarator)) { return variableDeclarator.Initializer?.Value; } if (node is CompilationUnitSyntax unit && unit.ContainsTopLevelStatements()) { // For top level statements, where there is no syntax node to represent the entire body of the synthesized // main method we just use the compilation unit itself return node; } return SyntaxUtilities.TryGetMethodDeclarationBody(node); } internal override bool IsDeclarationWithSharedBody(SyntaxNode declaration) => false; protected override ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody) { if (memberBody is CompilationUnitSyntax unit && unit.ContainsTopLevelStatements()) { return model.AnalyzeDataFlow(((GlobalStatementSyntax)unit.Members[0]).Statement, unit.Members.OfType<GlobalStatementSyntax>().Last().Statement)!.Captured; } Debug.Assert(memberBody.IsKind(SyntaxKind.Block) || memberBody is ExpressionSyntax); return model.AnalyzeDataFlow(memberBody).Captured; } protected override bool AreHandledEventsEqual(IMethodSymbol oldMethod, IMethodSymbol newMethod) => true; internal override bool HasParameterClosureScope(ISymbol member) { // in instance constructor parameters are lifted to a closure different from method body return (member as IMethodSymbol)?.MethodKind == MethodKind.Constructor; } protected override IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken) { Debug.Assert(localOrParameter is IParameterSymbol || localOrParameter is ILocalSymbol || localOrParameter is IRangeVariableSymbol); // not supported (it's non trivial to find all places where "this" is used): Debug.Assert(!localOrParameter.IsThisParameter()); return from root in roots from node in root.DescendantNodesAndSelf() where node.IsKind(SyntaxKind.IdentifierName) let nameSyntax = (IdentifierNameSyntax)node where (string?)nameSyntax.Identifier.Value == localOrParameter.Name && (model.GetSymbolInfo(nameSyntax, cancellationToken).Symbol?.Equals(localOrParameter) ?? false) select node; } /// <returns> /// If <paramref name="node"/> is a method, accessor, operator, destructor, or constructor without an initializer, /// tokens of its block body, or tokens of the expression body. /// /// If <paramref name="node"/> is an indexer declaration the tokens of its expression body. /// /// If <paramref name="node"/> is a property declaration the tokens of its expression body or initializer. /// /// If <paramref name="node"/> is a constructor with an initializer, /// tokens of the initializer concatenated with tokens of the constructor body. /// /// If <paramref name="node"/> is a variable declarator of a field with an initializer, /// subset of the tokens of the field declaration depending on which variable declarator it is. /// /// Null reference otherwise. /// </returns> internal override IEnumerable<SyntaxToken>? TryGetActiveTokens(SyntaxNode node) { if (node.IsKind(SyntaxKind.VariableDeclarator)) { // TODO: The logic is similar to BreakpointSpans.TryCreateSpanForVariableDeclaration. Can we abstract it? var declarator = node; var fieldDeclaration = (BaseFieldDeclarationSyntax)declarator.Parent!.Parent!; var variableDeclaration = fieldDeclaration.Declaration; if (fieldDeclaration.Modifiers.Any(SyntaxKind.ConstKeyword)) { return null; } if (variableDeclaration.Variables.Count == 1) { if (variableDeclaration.Variables[0].Initializer == null) { return null; } return fieldDeclaration.Modifiers.Concat(variableDeclaration.DescendantTokens()).Concat(fieldDeclaration.SemicolonToken); } if (declarator == variableDeclaration.Variables[0]) { return fieldDeclaration.Modifiers.Concat(variableDeclaration.Type.DescendantTokens()).Concat(node.DescendantTokens()); } return declarator.DescendantTokens(); } if (node is PropertyDeclarationSyntax { ExpressionBody: var propertyExpressionBody and not null }) { return propertyExpressionBody.Expression.DescendantTokens(); } if (node is IndexerDeclarationSyntax { ExpressionBody: var indexerExpressionBody and not null }) { return indexerExpressionBody.Expression.DescendantTokens(); } var bodyTokens = SyntaxUtilities.TryGetMethodDeclarationBody(node)?.DescendantTokens(); if (node.IsKind(SyntaxKind.ConstructorDeclaration, out ConstructorDeclarationSyntax? ctor)) { if (ctor.Initializer != null) { bodyTokens = ctor.Initializer.DescendantTokens().Concat(bodyTokens ?? Enumerable.Empty<SyntaxToken>()); } } return bodyTokens; } internal override (TextSpan envelope, TextSpan hole) GetActiveSpanEnvelope(SyntaxNode declaration) => (BreakpointSpans.GetEnvelope(declaration), default); protected override SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot) { // Constructor may contain active nodes outside of its body (constructor initializer), // but within the body of the member declaration (the parent). if (bodyOrMatchRoot.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { return bodyOrMatchRoot.Parent; } // Field initializer match root -- an active statement may include the modifiers // and type specification of the field declaration. if (bodyOrMatchRoot.IsKind(SyntaxKind.EqualsValueClause) && bodyOrMatchRoot.Parent.IsKind(SyntaxKind.VariableDeclarator) && bodyOrMatchRoot.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) { return bodyOrMatchRoot.Parent.Parent; } // Field initializer body -- an active statement may include the modifiers // and type specification of the field declaration. if (bodyOrMatchRoot.Parent.IsKind(SyntaxKind.EqualsValueClause) && bodyOrMatchRoot.Parent.Parent.IsKind(SyntaxKind.VariableDeclarator) && bodyOrMatchRoot.Parent.Parent.Parent.IsKind(SyntaxKind.FieldDeclaration)) { return bodyOrMatchRoot.Parent.Parent.Parent; } // otherwise all active statements are covered by the body/match root itself: return bodyOrMatchRoot; } protected override SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, TextSpan span, SyntaxNode? partnerDeclarationBody, out SyntaxNode? partner, out int statementPart) { var position = span.Start; SyntaxUtilities.AssertIsBody(declarationBody, allowLambda: false); if (position < declarationBody.SpanStart) { // Only constructors and the field initializers may have an [|active statement|] starting outside of the <<body>>. // Constructor: [|public C()|] <<{ }>> // Constructor initializer: public C() : [|base(expr)|] <<{ }>> // Constructor initializer with lambda: public C() : base(() => { [|...|] }) <<{ }>> // Field initializers: [|public int a = <<expr>>|], [|b = <<expr>>|]; // No need to special case property initializers here, the active statement always spans the initializer expression. if (declarationBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { var constructor = (ConstructorDeclarationSyntax)declarationBody.Parent; var partnerConstructor = (ConstructorDeclarationSyntax?)partnerDeclarationBody?.Parent; if (constructor.Initializer == null || position < constructor.Initializer.ColonToken.SpanStart) { statementPart = DefaultStatementPart; partner = partnerConstructor; return constructor; } declarationBody = constructor.Initializer; partnerDeclarationBody = partnerConstructor?.Initializer; } } if (!declarationBody.FullSpan.Contains(position)) { // invalid position, let's find a labeled node that encompasses the body: position = declarationBody.SpanStart; } SyntaxNode node; if (partnerDeclarationBody != null) { SyntaxUtilities.FindLeafNodeAndPartner(declarationBody, position, partnerDeclarationBody, out node, out partner); } else { node = declarationBody.FindToken(position).Parent!; partner = null; } while (true) { var isBody = node == declarationBody || LambdaUtilities.IsLambdaBodyStatementOrExpression(node); if (isBody || SyntaxComparer.Statement.HasLabel(node)) { switch (node.Kind()) { case SyntaxKind.Block: statementPart = (int)GetStatementPart((BlockSyntax)node, position); return node; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: Debug.Assert(!isBody); statementPart = (int)GetStatementPart((CommonForEachStatementSyntax)node, position); return node; case SyntaxKind.DoStatement: // The active statement of DoStatement node is the while condition, // which is lexically not the closest breakpoint span (the body is). // do { ... } [|while (condition);|] Debug.Assert(position == ((DoStatementSyntax)node).WhileKeyword.SpanStart); Debug.Assert(!isBody); goto default; case SyntaxKind.PropertyDeclaration: // The active span corresponding to a property declaration is the span corresponding to its initializer (if any), // not the span corresponding to the accessor. // int P { [|get;|] } = [|<initializer>|]; Debug.Assert(position == ((PropertyDeclarationSyntax)node).Initializer!.SpanStart); goto default; case SyntaxKind.VariableDeclaration: // VariableDeclaration ::= TypeSyntax CommaSeparatedList(VariableDeclarator) // // The compiler places sequence points after each local variable initialization. // The TypeSyntax is considered to be part of the first sequence span. Debug.Assert(!isBody); node = ((VariableDeclarationSyntax)node).Variables.First(); if (partner != null) { partner = ((VariableDeclarationSyntax)partner).Variables.First(); } statementPart = DefaultStatementPart; return node; case SyntaxKind.SwitchExpression: // An active statement that covers IL generated for the decision tree: // <governing-expression> [|switch { <arm>, ..., <arm> }|] // This active statement is never a leaf active statement (does not correspond to a breakpoint span). var switchExpression = (SwitchExpressionSyntax)node; if (position == switchExpression.SwitchKeyword.SpanStart) { Debug.Assert(span.End == switchExpression.CloseBraceToken.Span.End); statementPart = (int)SwitchExpressionPart.SwitchBody; return node; } // The switch expression itself can be (a part of) an active statement associated with the containing node // For example, when it is used as a switch arm expression like so: // <expr> switch { <pattern> [|when <expr> switch { ... }|] ... } Debug.Assert(position == switchExpression.Span.Start); if (isBody) { goto default; } // ascend to parent node: break; case SyntaxKind.SwitchExpressionArm: // An active statement may occur in the when clause and in the arm expression: // <constant-pattern> [|when <condition>|] => [|<expression>|] // The former is covered by when-clause node - it's a labeled node. // The latter isn't enclosed in a distinct labeled syntax node and thus needs to be covered // by the arm node itself. Debug.Assert(position == ((SwitchExpressionArmSyntax)node).Expression.SpanStart); Debug.Assert(!isBody); goto default; default: statementPart = DefaultStatementPart; return node; } } node = node.Parent!; if (partner != null) { partner = partner.Parent; } } } private static BlockPart GetStatementPart(BlockSyntax node, int position) => position < node.OpenBraceToken.Span.End ? BlockPart.OpenBrace : BlockPart.CloseBrace; private static TextSpan GetActiveSpan(BlockSyntax node, BlockPart part) => part switch { BlockPart.OpenBrace => node.OpenBraceToken.Span, BlockPart.CloseBrace => node.CloseBraceToken.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static ForEachPart GetStatementPart(CommonForEachStatementSyntax node, int position) => position < node.OpenParenToken.SpanStart ? ForEachPart.ForEach : position < node.InKeyword.SpanStart ? ForEachPart.VariableDeclaration : position < node.Expression.SpanStart ? ForEachPart.In : ForEachPart.Expression; private static TextSpan GetActiveSpan(ForEachStatementSyntax node, ForEachPart part) => part switch { ForEachPart.ForEach => node.ForEachKeyword.Span, ForEachPart.VariableDeclaration => TextSpan.FromBounds(node.Type.SpanStart, node.Identifier.Span.End), ForEachPart.In => node.InKeyword.Span, ForEachPart.Expression => node.Expression.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static TextSpan GetActiveSpan(ForEachVariableStatementSyntax node, ForEachPart part) => part switch { ForEachPart.ForEach => node.ForEachKeyword.Span, ForEachPart.VariableDeclaration => TextSpan.FromBounds(node.Variable.SpanStart, node.Variable.Span.End), ForEachPart.In => node.InKeyword.Span, ForEachPart.Expression => node.Expression.Span, _ => throw ExceptionUtilities.UnexpectedValue(part), }; private static TextSpan GetActiveSpan(SwitchExpressionSyntax node, SwitchExpressionPart part) => part switch { SwitchExpressionPart.WholeExpression => node.Span, SwitchExpressionPart.SwitchBody => TextSpan.FromBounds(node.SwitchKeyword.SpanStart, node.CloseBraceToken.Span.End), _ => throw ExceptionUtilities.UnexpectedValue(part), }; protected override bool AreEquivalent(SyntaxNode left, SyntaxNode right) => SyntaxFactory.AreEquivalent(left, right); private static bool AreEquivalentIgnoringLambdaBodies(SyntaxNode left, SyntaxNode right) { // usual case: if (SyntaxFactory.AreEquivalent(left, right)) { return true; } return LambdaUtilities.AreEquivalentIgnoringLambdaBodies(left, right); } internal override SyntaxNode FindDeclarationBodyPartner(SyntaxNode leftRoot, SyntaxNode rightRoot, SyntaxNode leftNode) => SyntaxUtilities.FindPartner(leftRoot, rightRoot, leftNode); internal override bool IsClosureScope(SyntaxNode node) => LambdaUtilities.IsClosureScope(node); protected override SyntaxNode? FindEnclosingLambdaBody(SyntaxNode? container, SyntaxNode node) { var root = GetEncompassingAncestor(container); var current = node; while (current != root && current != null) { if (LambdaUtilities.IsLambdaBodyStatementOrExpression(current, out var body)) { return body; } current = current.Parent; } return null; } protected override IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody) => SpecializedCollections.SingletonEnumerable(lambdaBody); protected override SyntaxNode? TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda) => LambdaUtilities.TryGetCorrespondingLambdaBody(oldBody, newLambda); protected override Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit) => SyntaxComparer.TopLevel.ComputeMatch(oldCompilationUnit, newCompilationUnit); protected override Match<SyntaxNode> ComputeTopLevelDeclarationMatch(SyntaxNode oldDeclaration, SyntaxNode newDeclaration) { Contract.ThrowIfNull(oldDeclaration.Parent); Contract.ThrowIfNull(newDeclaration.Parent); var comparer = new SyntaxComparer(oldDeclaration.Parent, newDeclaration.Parent, new[] { oldDeclaration }, new[] { newDeclaration }, compareStatementSyntax: false); return comparer.ComputeMatch(oldDeclaration.Parent, newDeclaration.Parent); } protected override Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>>? knownMatches) { SyntaxUtilities.AssertIsBody(oldBody, allowLambda: true); SyntaxUtilities.AssertIsBody(newBody, allowLambda: true); if (oldBody is ExpressionSyntax || newBody is ExpressionSyntax || (oldBody.Parent.IsKind(SyntaxKind.LocalFunctionStatement) && newBody.Parent.IsKind(SyntaxKind.LocalFunctionStatement))) { Debug.Assert(oldBody is ExpressionSyntax || oldBody is BlockSyntax); Debug.Assert(newBody is ExpressionSyntax || newBody is BlockSyntax); // The matching algorithm requires the roots to match each other. // Lambda bodies, field/property initializers, and method/property/indexer/operator expression-bodies may also be lambda expressions. // Say we have oldBody 'x => x' and newBody 'F(x => x + 1)', then // the algorithm would match 'x => x' to 'F(x => x + 1)' instead of // matching 'x => x' to 'x => x + 1'. // We use the parent node as a root: // - for field/property initializers the root is EqualsValueClause. // - for member expression-bodies the root is ArrowExpressionClauseSyntax. // - for block bodies the root is a method/operator/accessor declaration (only happens when matching expression body with a block body) // - for lambdas the root is a LambdaExpression. // - for query lambdas the root is the query clause containing the lambda (e.g. where). // - for local functions the root is LocalFunctionStatement. static SyntaxNode GetMatchingRoot(SyntaxNode body) { var parent = body.Parent!; // We could apply this change across all ArrowExpressionClause consistently not just for ones with LocalFunctionStatement parents // but it would require an essential refactoring. return parent.IsKind(SyntaxKind.ArrowExpressionClause) && parent.Parent.IsKind(SyntaxKind.LocalFunctionStatement) ? parent.Parent : parent; } var oldRoot = GetMatchingRoot(oldBody); var newRoot = GetMatchingRoot(newBody); return new SyntaxComparer(oldRoot, newRoot, GetChildNodes(oldRoot, oldBody), GetChildNodes(newRoot, newBody), compareStatementSyntax: true).ComputeMatch(oldRoot, newRoot, knownMatches); } if (oldBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)) { // We need to include constructor initializer in the match, since it may contain lambdas. // Use the constructor declaration as a root. RoslynDebug.Assert(oldBody.IsKind(SyntaxKind.Block)); RoslynDebug.Assert(newBody.IsKind(SyntaxKind.Block)); RoslynDebug.Assert(newBody.Parent.IsKind(SyntaxKind.ConstructorDeclaration)); RoslynDebug.Assert(newBody.Parent is object); return SyntaxComparer.Statement.ComputeMatch(oldBody.Parent, newBody.Parent, knownMatches); } return SyntaxComparer.Statement.ComputeMatch(oldBody, newBody, knownMatches); } private static IEnumerable<SyntaxNode> GetChildNodes(SyntaxNode root, SyntaxNode body) { if (root is LocalFunctionStatementSyntax localFunc) { // local functions have multiple children we need to process for matches, but we won't automatically // descend into them, assuming they're nested, so we override the default behaviour and return // multiple children foreach (var attributeList in localFunc.AttributeLists) { yield return attributeList; } yield return localFunc.ReturnType; if (localFunc.TypeParameterList is not null) { yield return localFunc.TypeParameterList; } yield return localFunc.ParameterList; if (localFunc.Body is not null) { yield return localFunc.Body; } else if (localFunc.ExpressionBody is not null) { // Skip the ArrowExpressionClause that is ExressionBody and just return the expression itself yield return localFunc.ExpressionBody.Expression; } } else { yield return body; } } internal override void ReportDeclarationInsertDeleteRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode, ISymbol oldSymbol, ISymbol newSymbol, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { // Global statements have a declaring syntax reference to the compilation unit itself, which we can just ignore // for the purposes of declaration rude edits if (oldNode.IsKind(SyntaxKind.CompilationUnit) || newNode.IsKind(SyntaxKind.CompilationUnit)) { return; } // Compiler generated methods of records have a declaring syntax reference to the record declaration itself // but their explicitly implemented counterparts reference the actual member. Compiler generated properties // of records reference the parameter that names them. // // Since there is no useful "old" syntax node for these members, we can't compute declaration or body edits // using the standard tree comparison code. // // Based on this, we can detect a new explicit implementation of a record member by checking if the // declaration kind has changed. If it hasn't changed, then our standard code will handle it. if (oldNode.RawKind == newNode.RawKind) { base.ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldNode, newNode, oldSymbol, newSymbol, capabilities, cancellationToken); return; } // When explicitly implementing a property that is represented by a positional parameter // what looks like an edit could actually be a rude delete, or something else if (oldNode is ParameterSyntax && newNode is PropertyDeclarationSyntax property) { if (property.AccessorList!.Accessors.Count == 1) { // Explicitly implementing a property with only one accessor is a delete of the init accessor, so a rude edit. // Not implementing the get accessor would be a compile error diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ImplementRecordParameterAsReadOnly, GetDiagnosticSpan(newNode, EditKind.Delete), oldNode, new[] { property.Identifier.ToString() })); } else if (property.AccessorList.Accessors.Any(a => a.IsKind(SyntaxKind.SetAccessorDeclaration))) { // The compiler implements the properties with an init accessor so explicitly implementing // it with a set accessor is a rude accessor change edit diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ImplementRecordParameterWithSet, GetDiagnosticSpan(newNode, EditKind.Delete), oldNode, new[] { property.Identifier.ToString() })); } } else if (oldNode is RecordDeclarationSyntax && newNode is MethodDeclarationSyntax && !capabilities.HasFlag(EditAndContinueCapabilities.UpdateParameters) && !oldSymbol.GetParameters().Select(p => p.Name).SequenceEqual(newSymbol.GetParameters().Select(p => p.Name))) { // Explicitly implemented methods must have parameter names that match the compiler generated versions // exactly if the runtime doesn't support updating parameters, otherwise the debugger would show incorrect // parameter names. // We don't need to worry about parameter types, because if they were different then we wouldn't get here // as this wouldn't be the explicit implementation of a known method. // We don't need to worry about access modifiers because the symbol matching still works, and most of the // time changing access modifiers for these known methods is a compile error anyway. diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, GetDiagnosticSpan(newNode, EditKind.Update), oldNode, new[] { oldSymbol.ToDisplayString(SymbolDisplayFormats.NameFormat) })); } } protected override void ReportLocalFunctionsDeclarationRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> bodyMatch) { var bodyEditsForLambda = bodyMatch.GetTreeEdits(); var editMap = BuildEditMap(bodyEditsForLambda); foreach (var edit in bodyEditsForLambda.Edits) { if (HasParentEdit(editMap, edit)) { return; } var classifier = new EditClassifier(this, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, bodyMatch); classifier.ClassifyEdit(); } } protected override bool TryMatchActiveStatement( SyntaxNode oldStatement, int statementPart, SyntaxNode oldBody, SyntaxNode newBody, [NotNullWhen(true)] out SyntaxNode? newStatement) { SyntaxUtilities.AssertIsBody(oldBody, allowLambda: true); SyntaxUtilities.AssertIsBody(newBody, allowLambda: true); switch (oldStatement.Kind()) { case SyntaxKind.ThisConstructorInitializer: case SyntaxKind.BaseConstructorInitializer: case SyntaxKind.ConstructorDeclaration: var newConstructor = (ConstructorDeclarationSyntax)(newBody.Parent.IsKind(SyntaxKind.ArrowExpressionClause) ? newBody.Parent.Parent : newBody.Parent)!; newStatement = (SyntaxNode?)newConstructor.Initializer ?? newConstructor; return true; default: // TODO: Consider mapping an expression body to an equivalent statement expression or return statement and vice versa. // It would benefit transformations of expression bodies to block bodies of lambdas, methods, operators and properties. // See https://github.com/dotnet/roslyn/issues/22696 // field initializer, lambda and query expressions: if (oldStatement == oldBody && !newBody.IsKind(SyntaxKind.Block)) { newStatement = newBody; return true; } newStatement = null; return false; } } #endregion #region Syntax and Semantic Utils protected override TextSpan GetGlobalStatementDiagnosticSpan(SyntaxNode node) { if (node is CompilationUnitSyntax unit) { // When deleting something from a compilation unit we just report diagnostics for the last global statement return unit.Members.OfType<GlobalStatementSyntax>().LastOrDefault()?.Span ?? default; } return GetDiagnosticSpan(node, EditKind.Delete); } protected override string LineDirectiveKeyword => "line"; protected override ushort LineDirectiveSyntaxKind => (ushort)SyntaxKind.LineDirectiveTrivia; protected override IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes) => SyntaxComparer.GetSequenceEdits(oldNodes, newNodes); internal override SyntaxNode EmptyCompilationUnit => SyntaxFactory.CompilationUnit(); // there are no experimental features at this time. internal override bool ExperimentalFeaturesEnabled(SyntaxTree tree) => false; protected override bool StateMachineSuspensionPointKindEquals(SyntaxNode suspensionPoint1, SyntaxNode suspensionPoint2) => (suspensionPoint1 is CommonForEachStatementSyntax) ? suspensionPoint2 is CommonForEachStatementSyntax : suspensionPoint1.RawKind == suspensionPoint2.RawKind; protected override bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2) => SyntaxComparer.Statement.GetLabel(node1) == SyntaxComparer.Statement.GetLabel(node2); protected override bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span) => BreakpointSpans.TryGetClosestBreakpointSpan(root, position, out span); protected override bool TryGetActiveSpan(SyntaxNode node, int statementPart, int minLength, out TextSpan span) { switch (node.Kind()) { case SyntaxKind.Block: span = GetActiveSpan((BlockSyntax)node, (BlockPart)statementPart); return true; case SyntaxKind.ForEachStatement: span = GetActiveSpan((ForEachStatementSyntax)node, (ForEachPart)statementPart); return true; case SyntaxKind.ForEachVariableStatement: span = GetActiveSpan((ForEachVariableStatementSyntax)node, (ForEachPart)statementPart); return true; case SyntaxKind.DoStatement: // The active statement of DoStatement node is the while condition, // which is lexically not the closest breakpoint span (the body is). // do { ... } [|while (condition);|] Debug.Assert(statementPart == DefaultStatementPart); var doStatement = (DoStatementSyntax)node; return BreakpointSpans.TryGetClosestBreakpointSpan(node, doStatement.WhileKeyword.SpanStart, out span); case SyntaxKind.PropertyDeclaration: // The active span corresponding to a property declaration is the span corresponding to its initializer (if any), // not the span corresponding to the accessor. // int P { [|get;|] } = [|<initializer>|]; Debug.Assert(statementPart == DefaultStatementPart); var propertyDeclaration = (PropertyDeclarationSyntax)node; if (propertyDeclaration.Initializer != null && BreakpointSpans.TryGetClosestBreakpointSpan(node, propertyDeclaration.Initializer.SpanStart, out span)) { return true; } span = default; return false; case SyntaxKind.SwitchExpression: span = GetActiveSpan((SwitchExpressionSyntax)node, (SwitchExpressionPart)statementPart); return true; case SyntaxKind.SwitchExpressionArm: // An active statement may occur in the when clause and in the arm expression: // <constant-pattern> [|when <condition>|] => [|<expression>|] // The former is covered by when-clause node - it's a labeled node. // The latter isn't enclosed in a distinct labeled syntax node and thus needs to be covered // by the arm node itself. Debug.Assert(statementPart == DefaultStatementPart); span = ((SwitchExpressionArmSyntax)node).Expression.Span; return true; default: // make sure all nodes that use statement parts are handled above: Debug.Assert(statementPart == DefaultStatementPart); return BreakpointSpans.TryGetClosestBreakpointSpan(node, node.SpanStart, out span); } } protected override IEnumerable<(SyntaxNode statement, int statementPart)> EnumerateNearStatements(SyntaxNode statement) { var direction = +1; SyntaxNodeOrToken nodeOrToken = statement; var fieldOrPropertyModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(statement); while (true) { nodeOrToken = (direction < 0) ? nodeOrToken.GetPreviousSibling() : nodeOrToken.GetNextSibling(); if (nodeOrToken.RawKind == 0) { var parent = statement.Parent; if (parent == null) { yield break; } switch (parent.Kind()) { case SyntaxKind.Block: // The next sequence point hit after the last statement of a block is the closing brace: yield return (parent, (int)(direction > 0 ? BlockPart.CloseBrace : BlockPart.OpenBrace)); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // The next sequence point hit after the body is the in keyword: // [|foreach|] ([|variable-declaration|] [|in|] [|expression|]) [|<body>|] yield return (parent, (int)ForEachPart.In); break; } if (direction > 0) { nodeOrToken = statement; direction = -1; continue; } if (fieldOrPropertyModifiers.HasValue) { // We enumerated all members and none of them has an initializer. // We don't have any better place where to place the span than the initial field. // Consider: in non-partial classes we could find a single constructor. // Otherwise, it would be confusing to select one arbitrarily. yield return (statement, -1); } nodeOrToken = statement = parent; fieldOrPropertyModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(statement); direction = +1; yield return (nodeOrToken.AsNode()!, DefaultStatementPart); } else { var node = nodeOrToken.AsNode(); if (node == null) { continue; } if (fieldOrPropertyModifiers.HasValue) { var nodeModifiers = SyntaxUtilities.TryGetFieldOrPropertyModifiers(node); if (!nodeModifiers.HasValue || nodeModifiers.Value.Any(SyntaxKind.StaticKeyword) != fieldOrPropertyModifiers.Value.Any(SyntaxKind.StaticKeyword)) { continue; } } switch (node.Kind()) { case SyntaxKind.Block: yield return (node, (int)(direction > 0 ? BlockPart.OpenBrace : BlockPart.CloseBrace)); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: yield return (node, (int)ForEachPart.ForEach); break; } yield return (node, DefaultStatementPart); } } } protected override bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart) { if (oldStatement.Kind() != newStatement.Kind()) { return false; } switch (oldStatement.Kind()) { case SyntaxKind.Block: // closing brace of a using statement or a block that contains using local declarations: if (statementPart == (int)BlockPart.CloseBrace) { if (oldStatement.Parent.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? oldUsing)) { return newStatement.Parent.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? newUsing) && AreEquivalentActiveStatements(oldUsing, newUsing); } return HasEquivalentUsingDeclarations((BlockSyntax)oldStatement, (BlockSyntax)newStatement); } return true; case SyntaxKind.ConstructorDeclaration: // The call could only change if the base type of the containing class changed. return true; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: // only check the expression, edits in the body and the variable declaration are allowed: return AreEquivalentActiveStatements((CommonForEachStatementSyntax)oldStatement, (CommonForEachStatementSyntax)newStatement); case SyntaxKind.IfStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((IfStatementSyntax)oldStatement, (IfStatementSyntax)newStatement); case SyntaxKind.WhileStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((WhileStatementSyntax)oldStatement, (WhileStatementSyntax)newStatement); case SyntaxKind.DoStatement: // only check the condition, edits in the body are allowed: return AreEquivalentActiveStatements((DoStatementSyntax)oldStatement, (DoStatementSyntax)newStatement); case SyntaxKind.SwitchStatement: return AreEquivalentActiveStatements((SwitchStatementSyntax)oldStatement, (SwitchStatementSyntax)newStatement); case SyntaxKind.LockStatement: return AreEquivalentActiveStatements((LockStatementSyntax)oldStatement, (LockStatementSyntax)newStatement); case SyntaxKind.UsingStatement: return AreEquivalentActiveStatements((UsingStatementSyntax)oldStatement, (UsingStatementSyntax)newStatement); // fixed and for statements don't need special handling since the active statement is a variable declaration default: return AreEquivalentIgnoringLambdaBodies(oldStatement, newStatement); } } private static bool HasEquivalentUsingDeclarations(BlockSyntax oldBlock, BlockSyntax newBlock) { var oldUsingDeclarations = oldBlock.Statements.Where(s => s is LocalDeclarationStatementSyntax l && l.UsingKeyword != default); var newUsingDeclarations = newBlock.Statements.Where(s => s is LocalDeclarationStatementSyntax l && l.UsingKeyword != default); return oldUsingDeclarations.SequenceEqual(newUsingDeclarations, AreEquivalentIgnoringLambdaBodies); } private static bool AreEquivalentActiveStatements(IfStatementSyntax oldNode, IfStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(WhileStatementSyntax oldNode, WhileStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(DoStatementSyntax oldNode, DoStatementSyntax newNode) { // only check the condition, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Condition, newNode.Condition); } private static bool AreEquivalentActiveStatements(SwitchStatementSyntax oldNode, SwitchStatementSyntax newNode) { // only check the expression, edits in the body are allowed, unless the switch expression contains patterns: if (!AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression)) { return false; } // Check that switch statement decision tree has not changed. var hasDecitionTree = oldNode.Sections.Any(s => s.Labels.Any(l => l is CasePatternSwitchLabelSyntax)); return !hasDecitionTree || AreEquivalentSwitchStatementDecisionTrees(oldNode, newNode); } private static bool AreEquivalentActiveStatements(LockStatementSyntax oldNode, LockStatementSyntax newNode) { // only check the expression, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression); } private static bool AreEquivalentActiveStatements(FixedStatementSyntax oldNode, FixedStatementSyntax newNode) => AreEquivalentIgnoringLambdaBodies(oldNode.Declaration, newNode.Declaration); private static bool AreEquivalentActiveStatements(UsingStatementSyntax oldNode, UsingStatementSyntax newNode) { // only check the expression/declaration, edits in the body are allowed: return AreEquivalentIgnoringLambdaBodies( (SyntaxNode?)oldNode.Declaration ?? oldNode.Expression!, (SyntaxNode?)newNode.Declaration ?? newNode.Expression!); } private static bool AreEquivalentActiveStatements(CommonForEachStatementSyntax oldNode, CommonForEachStatementSyntax newNode) { if (oldNode.Kind() != newNode.Kind() || !AreEquivalentIgnoringLambdaBodies(oldNode.Expression, newNode.Expression)) { return false; } switch (oldNode.Kind()) { case SyntaxKind.ForEachStatement: return AreEquivalentIgnoringLambdaBodies(((ForEachStatementSyntax)oldNode).Type, ((ForEachStatementSyntax)newNode).Type); case SyntaxKind.ForEachVariableStatement: return AreEquivalentIgnoringLambdaBodies(((ForEachVariableStatementSyntax)oldNode).Variable, ((ForEachVariableStatementSyntax)newNode).Variable); default: throw ExceptionUtilities.UnexpectedValue(oldNode.Kind()); } } private static bool AreSimilarActiveStatements(CommonForEachStatementSyntax oldNode, CommonForEachStatementSyntax newNode) { List<SyntaxToken>? oldTokens = null; List<SyntaxToken>? newTokens = null; SyntaxComparer.GetLocalNames(oldNode, ref oldTokens); SyntaxComparer.GetLocalNames(newNode, ref newTokens); // A valid foreach statement declares at least one variable. RoslynDebug.Assert(oldTokens != null); RoslynDebug.Assert(newTokens != null); return DeclareSameIdentifiers(oldTokens.ToArray(), newTokens.ToArray()); } internal override bool IsInterfaceDeclaration(SyntaxNode node) => node.IsKind(SyntaxKind.InterfaceDeclaration); internal override bool IsRecordDeclaration(SyntaxNode node) => node.IsKind(SyntaxKind.RecordDeclaration, SyntaxKind.RecordStructDeclaration); internal override SyntaxNode? TryGetContainingTypeDeclaration(SyntaxNode node) => node is CompilationUnitSyntax ? null : node.Parent!.FirstAncestorOrSelf<BaseTypeDeclarationSyntax>(); internal override bool HasBackingField(SyntaxNode propertyOrIndexerDeclaration) => propertyOrIndexerDeclaration.IsKind(SyntaxKind.PropertyDeclaration, out PropertyDeclarationSyntax? propertyDecl) && SyntaxUtilities.HasBackingField(propertyDecl); internal override bool TryGetAssociatedMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? declaration) { if (node.IsKind(SyntaxKind.Parameter, SyntaxKind.TypeParameter)) { Contract.ThrowIfFalse(node.IsParentKind(SyntaxKind.ParameterList, SyntaxKind.TypeParameterList, SyntaxKind.BracketedParameterList)); declaration = node.Parent!.Parent!; return true; } if (node.Parent.IsParentKind(SyntaxKind.PropertyDeclaration, SyntaxKind.IndexerDeclaration, SyntaxKind.EventDeclaration)) { declaration = node.Parent.Parent!; return true; } declaration = null; return false; } internal override bool IsDeclarationWithInitializer(SyntaxNode declaration) => declaration is VariableDeclaratorSyntax { Initializer: not null } || declaration is PropertyDeclarationSyntax { Initializer: not null }; internal override bool IsRecordPrimaryConstructorParameter(SyntaxNode declaration) => declaration is ParameterSyntax { Parent: ParameterListSyntax { Parent: RecordDeclarationSyntax } }; private static bool IsPropertyDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType) { if (newContainingType.IsRecord && declaration is PropertyDeclarationSyntax { Identifier: { ValueText: var name } }) { // We need to use symbol information to find the primary constructor, because it could be in another file if the type is partial foreach (var reference in newContainingType.DeclaringSyntaxReferences) { // Since users can define as many constructors as they like, going back to syntax to find the parameter list // in the record declaration is the simplest way to check if there is a matching parameter if (reference.GetSyntax() is RecordDeclarationSyntax record && record.ParameterList is not null && record.ParameterList.Parameters.Any(p => p.Identifier.ValueText.Equals(name))) { return true; } } } return false; } internal override bool IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType, out bool isFirstAccessor) { isFirstAccessor = false; if (declaration is AccessorDeclarationSyntax { Parent: AccessorListSyntax { Parent: PropertyDeclarationSyntax property } list } && IsPropertyDeclarationMatchingPrimaryConstructorParameter(property, newContainingType)) { isFirstAccessor = list.Accessors[0] == declaration; return true; } return false; } internal override bool IsConstructorWithMemberInitializers(SyntaxNode constructorDeclaration) => constructorDeclaration is ConstructorDeclarationSyntax ctor && (ctor.Initializer == null || ctor.Initializer.IsKind(SyntaxKind.BaseConstructorInitializer)); internal override bool IsPartial(INamedTypeSymbol type) { var syntaxRefs = type.DeclaringSyntaxReferences; return syntaxRefs.Length > 1 || ((BaseTypeDeclarationSyntax)syntaxRefs.Single().GetSyntax()).Modifiers.Any(SyntaxKind.PartialKeyword); } protected override SyntaxNode GetSymbolDeclarationSyntax(SyntaxReference reference, CancellationToken cancellationToken) => reference.GetSyntax(cancellationToken); protected override OneOrMany<(ISymbol? oldSymbol, ISymbol? newSymbol, EditKind editKind)> GetSymbolEdits( EditKind editKind, SyntaxNode? oldNode, SyntaxNode? newNode, SemanticModel? oldModel, SemanticModel newModel, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken) { var oldSymbol = (oldNode != null) ? GetSymbolForEdit(oldNode, oldModel!, cancellationToken) : null; var newSymbol = (newNode != null) ? GetSymbolForEdit(newNode, newModel, cancellationToken) : null; switch (editKind) { case EditKind.Update: Contract.ThrowIfNull(oldNode); Contract.ThrowIfNull(newNode); Contract.ThrowIfNull(oldModel); // Certain updates of a property/indexer node affects its accessors. // Return all affected symbols for these updates. // 1) Old or new property/indexer has an expression body: // int this[...] => expr; // int this[...] { get => expr; } // int P => expr; // int P { get => expr; } = init if (oldNode is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null } || newNode is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null }) { Debug.Assert(oldSymbol is IPropertySymbol); Debug.Assert(newSymbol is IPropertySymbol); var oldGetterSymbol = ((IPropertySymbol)oldSymbol).GetMethod; var newGetterSymbol = ((IPropertySymbol)newSymbol).GetMethod; return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, editKind), (oldGetterSymbol, newGetterSymbol, editKind))); } // 2) Property/indexer declarations differ in readonly keyword. if (oldNode is PropertyDeclarationSyntax oldProperty && newNode is PropertyDeclarationSyntax newProperty && DiffersInReadOnlyModifier(oldProperty.Modifiers, newProperty.Modifiers) || oldNode is IndexerDeclarationSyntax oldIndexer && newNode is IndexerDeclarationSyntax newIndexer && DiffersInReadOnlyModifier(oldIndexer.Modifiers, newIndexer.Modifiers)) { Debug.Assert(oldSymbol is IPropertySymbol); Debug.Assert(newSymbol is IPropertySymbol); var oldPropertySymbol = (IPropertySymbol)oldSymbol; var newPropertySymbol = (IPropertySymbol)newSymbol; using var _ = ArrayBuilder<(ISymbol?, ISymbol?, EditKind)>.GetInstance(out var builder); builder.Add((oldPropertySymbol, newPropertySymbol, editKind)); if (oldPropertySymbol.GetMethod != null && newPropertySymbol.GetMethod != null && oldPropertySymbol.GetMethod.IsReadOnly != newPropertySymbol.GetMethod.IsReadOnly) { builder.Add((oldPropertySymbol.GetMethod, newPropertySymbol.GetMethod, editKind)); } if (oldPropertySymbol.SetMethod != null && newPropertySymbol.SetMethod != null && oldPropertySymbol.SetMethod.IsReadOnly != newPropertySymbol.SetMethod.IsReadOnly) { builder.Add((oldPropertySymbol.SetMethod, newPropertySymbol.SetMethod, editKind)); } return OneOrMany.Create(builder.ToImmutable()); } static bool DiffersInReadOnlyModifier(SyntaxTokenList oldModifiers, SyntaxTokenList newModifiers) => (oldModifiers.IndexOf(SyntaxKind.ReadOnlyKeyword) >= 0) != (newModifiers.IndexOf(SyntaxKind.ReadOnlyKeyword) >= 0); // Change in attributes or modifiers of a field affects all its variable declarations. if (oldNode is BaseFieldDeclarationSyntax oldField && newNode is BaseFieldDeclarationSyntax newField) { return GetFieldSymbolUpdates(oldField.Declaration.Variables, newField.Declaration.Variables); } // Chnage in type of a field affects all its variable declarations. if (oldNode is VariableDeclarationSyntax oldVariableDeclaration && newNode is VariableDeclarationSyntax newVariableDeclaration) { return GetFieldSymbolUpdates(oldVariableDeclaration.Variables, newVariableDeclaration.Variables); } OneOrMany<(ISymbol?, ISymbol?, EditKind)> GetFieldSymbolUpdates(SeparatedSyntaxList<VariableDeclaratorSyntax> oldVariables, SeparatedSyntaxList<VariableDeclaratorSyntax> newVariables) { if (oldVariables.Count == 1 && newVariables.Count == 1) { return OneOrMany.Create((oldModel.GetDeclaredSymbol(oldVariables[0], cancellationToken), newModel.GetDeclaredSymbol(newVariables[0], cancellationToken), EditKind.Update)); } var result = from oldVariable in oldVariables join newVariable in newVariables on oldVariable.Identifier.Text equals newVariable.Identifier.Text select (oldModel.GetDeclaredSymbol(oldVariable, cancellationToken), newModel.GetDeclaredSymbol(newVariable, cancellationToken), EditKind.Update); return OneOrMany.Create(result.ToImmutableArray()); } break; case EditKind.Delete: case EditKind.Insert: var node = oldNode ?? newNode; // If the entire block-bodied property/indexer is deleted/inserted (accessors and the list they are contained in), // ignore this edit. We will have a semantic edit for the property/indexer itself. if (node.IsKind(SyntaxKind.GetAccessorDeclaration)) { Debug.Assert(node.Parent.IsKind(SyntaxKind.AccessorList)); if (HasEdit(editMap, node.Parent, editKind) && !HasEdit(editMap, node.Parent.Parent, editKind)) { return OneOrMany<(ISymbol?, ISymbol?, EditKind)>.Empty; } } // Inserting/deleting an expression-bodied property/indexer affects two symbols: // the property/indexer itself and the getter. // int this[...] => expr; // int P => expr; if (node is PropertyDeclarationSyntax { ExpressionBody: not null } or IndexerDeclarationSyntax { ExpressionBody: not null }) { var oldGetterSymbol = ((IPropertySymbol?)oldSymbol)?.GetMethod; var newGetterSymbol = ((IPropertySymbol?)newSymbol)?.GetMethod; return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, editKind), (oldGetterSymbol, newGetterSymbol, editKind))); } // Inserting/deleting a type parameter constraint should result in an update of the corresponding type parameter symbol: if (node.IsKind(SyntaxKind.TypeParameterConstraintClause)) { return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, EditKind.Update))); } // Inserting/deleting a global statement should result in an update of the implicit main method: if (node.IsKind(SyntaxKind.GlobalStatement)) { return OneOrMany.Create(ImmutableArray.Create((oldSymbol, newSymbol, EditKind.Update))); } break; } return (editKind == EditKind.Delete ? oldSymbol : newSymbol) is null ? OneOrMany<(ISymbol?, ISymbol?, EditKind)>.Empty : new OneOrMany<(ISymbol?, ISymbol?, EditKind)>((oldSymbol, newSymbol, editKind)); } private static ISymbol? GetSymbolForEdit( SyntaxNode node, SemanticModel model, CancellationToken cancellationToken) { if (node.IsKind(SyntaxKind.UsingDirective, SyntaxKind.NamespaceDeclaration, SyntaxKind.FileScopedNamespaceDeclaration)) { return null; } if (node.IsKind(SyntaxKind.TypeParameterConstraintClause)) { var constraintClause = (TypeParameterConstraintClauseSyntax)node; var symbolInfo = model.GetSymbolInfo(constraintClause.Name, cancellationToken); return symbolInfo.Symbol; } // Top level code always lives in a synthesized Main method if (node.IsKind(SyntaxKind.GlobalStatement)) { return model.GetEnclosingSymbol(node.SpanStart, cancellationToken); } var symbol = model.GetDeclaredSymbol(node, cancellationToken); // TODO: this is incorrect (https://github.com/dotnet/roslyn/issues/54800) // Ignore partial method definition parts. // Partial method that does not have implementation part is not emitted to metadata. // Partial method without a definition part is a compilation error. if (symbol is IMethodSymbol { IsPartialDefinition: true }) { return null; } return symbol; } internal override bool ContainsLambda(SyntaxNode declaration) => declaration.DescendantNodes().Any(LambdaUtilities.IsLambda); internal override bool IsLambda(SyntaxNode node) => LambdaUtilities.IsLambda(node); internal override bool IsLocalFunction(SyntaxNode node) => node.IsKind(SyntaxKind.LocalFunctionStatement); internal override bool IsNestedFunction(SyntaxNode node) => node is AnonymousFunctionExpressionSyntax or LocalFunctionStatementSyntax; internal override bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? body1, out SyntaxNode? body2) => LambdaUtilities.TryGetLambdaBodies(node, out body1, out body2); internal override SyntaxNode GetLambda(SyntaxNode lambdaBody) => LambdaUtilities.GetLambda(lambdaBody); internal override IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken) { var bodyExpression = LambdaUtilities.GetNestedFunctionBody(lambdaExpression); return (IMethodSymbol)model.GetRequiredEnclosingSymbol(bodyExpression.SpanStart, cancellationToken); } internal override SyntaxNode? GetContainingQueryExpression(SyntaxNode node) => node.FirstAncestorOrSelf<QueryExpressionSyntax>(); internal override bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken) { switch (oldNode.Kind()) { case SyntaxKind.FromClause: case SyntaxKind.LetClause: case SyntaxKind.WhereClause: case SyntaxKind.OrderByClause: case SyntaxKind.JoinClause: var oldQueryClauseInfo = oldModel.GetQueryClauseInfo((QueryClauseSyntax)oldNode, cancellationToken); var newQueryClauseInfo = newModel.GetQueryClauseInfo((QueryClauseSyntax)newNode, cancellationToken); return MemberSignaturesEquivalent(oldQueryClauseInfo.CastInfo.Symbol, newQueryClauseInfo.CastInfo.Symbol) && MemberSignaturesEquivalent(oldQueryClauseInfo.OperationInfo.Symbol, newQueryClauseInfo.OperationInfo.Symbol); case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: var oldOrderingInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newOrderingInfo = newModel.GetSymbolInfo(newNode, cancellationToken); return MemberSignaturesEquivalent(oldOrderingInfo.Symbol, newOrderingInfo.Symbol); case SyntaxKind.SelectClause: var oldSelectInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newSelectInfo = newModel.GetSymbolInfo(newNode, cancellationToken); // Changing reduced select clause to a non-reduced form or vice versa // adds/removes a call to Select method, which is a supported change. return oldSelectInfo.Symbol == null || newSelectInfo.Symbol == null || MemberSignaturesEquivalent(oldSelectInfo.Symbol, newSelectInfo.Symbol); case SyntaxKind.GroupClause: var oldGroupByInfo = oldModel.GetSymbolInfo(oldNode, cancellationToken); var newGroupByInfo = newModel.GetSymbolInfo(newNode, cancellationToken); return MemberSignaturesEquivalent(oldGroupByInfo.Symbol, newGroupByInfo.Symbol, GroupBySignatureComparer); default: return true; } } private static bool GroupBySignatureComparer(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType) { // C# spec paragraph 7.16.2.6 "Groupby clauses": // // A query expression of the form // from x in e group v by k // is translated into // (e).GroupBy(x => k, x => v) // except when v is the identifier x, the translation is // (e).GroupBy(x => k) // // Possible signatures: // C<G<K, T>> GroupBy<K>(Func<T, K> keySelector); // C<G<K, E>> GroupBy<K, E>(Func<T, K> keySelector, Func<T, E> elementSelector); if (!TypesEquivalent(oldReturnType, newReturnType, exact: false)) { return false; } Debug.Assert(oldParameters.Length == 1 || oldParameters.Length == 2); Debug.Assert(newParameters.Length == 1 || newParameters.Length == 2); // The types of the lambdas have to be the same if present. // The element selector may be added/removed. if (!ParameterTypesEquivalent(oldParameters[0], newParameters[0], exact: false)) { return false; } if (oldParameters.Length == newParameters.Length && newParameters.Length == 2) { return ParameterTypesEquivalent(oldParameters[1], newParameters[1], exact: false); } return true; } #endregion #region Diagnostic Info protected override SymbolDisplayFormat ErrorDisplayFormat => SymbolDisplayFormat.CSharpErrorMessageFormat; protected override TextSpan? TryGetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node, editKind); internal static new TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node, editKind) ?? node.Span; private static TextSpan? TryGetDiagnosticSpanImpl(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpanImpl(node.Kind(), node, editKind); // internal for testing; kind is passed explicitly for testing as well internal static TextSpan? TryGetDiagnosticSpanImpl(SyntaxKind kind, SyntaxNode node, EditKind editKind) { switch (kind) { case SyntaxKind.CompilationUnit: return default(TextSpan); case SyntaxKind.GlobalStatement: return node.Span; case SyntaxKind.ExternAliasDirective: case SyntaxKind.UsingDirective: return node.Span; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: var ns = (BaseNamespaceDeclarationSyntax)node; return TextSpan.FromBounds(ns.NamespaceKeyword.SpanStart, ns.Name.Span.End); case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: var typeDeclaration = (TypeDeclarationSyntax)node; return GetDiagnosticSpan(typeDeclaration.Modifiers, typeDeclaration.Keyword, typeDeclaration.TypeParameterList ?? (SyntaxNodeOrToken)typeDeclaration.Identifier); case SyntaxKind.EnumDeclaration: var enumDeclaration = (EnumDeclarationSyntax)node; return GetDiagnosticSpan(enumDeclaration.Modifiers, enumDeclaration.EnumKeyword, enumDeclaration.Identifier); case SyntaxKind.DelegateDeclaration: var delegateDeclaration = (DelegateDeclarationSyntax)node; return GetDiagnosticSpan(delegateDeclaration.Modifiers, delegateDeclaration.DelegateKeyword, delegateDeclaration.ParameterList); case SyntaxKind.FieldDeclaration: var fieldDeclaration = (BaseFieldDeclarationSyntax)node; return GetDiagnosticSpan(fieldDeclaration.Modifiers, fieldDeclaration.Declaration, fieldDeclaration.Declaration); case SyntaxKind.EventFieldDeclaration: var eventFieldDeclaration = (EventFieldDeclarationSyntax)node; return GetDiagnosticSpan(eventFieldDeclaration.Modifiers, eventFieldDeclaration.EventKeyword, eventFieldDeclaration.Declaration); case SyntaxKind.VariableDeclaration: return TryGetDiagnosticSpanImpl(node.Parent!, editKind); case SyntaxKind.VariableDeclarator: return node.Span; case SyntaxKind.MethodDeclaration: var methodDeclaration = (MethodDeclarationSyntax)node; return GetDiagnosticSpan(methodDeclaration.Modifiers, methodDeclaration.ReturnType, methodDeclaration.ParameterList); case SyntaxKind.ConversionOperatorDeclaration: var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node; return GetDiagnosticSpan(conversionOperatorDeclaration.Modifiers, conversionOperatorDeclaration.ImplicitOrExplicitKeyword, conversionOperatorDeclaration.ParameterList); case SyntaxKind.OperatorDeclaration: var operatorDeclaration = (OperatorDeclarationSyntax)node; return GetDiagnosticSpan(operatorDeclaration.Modifiers, operatorDeclaration.ReturnType, operatorDeclaration.ParameterList); case SyntaxKind.ConstructorDeclaration: var constructorDeclaration = (ConstructorDeclarationSyntax)node; return GetDiagnosticSpan(constructorDeclaration.Modifiers, constructorDeclaration.Identifier, constructorDeclaration.ParameterList); case SyntaxKind.DestructorDeclaration: var destructorDeclaration = (DestructorDeclarationSyntax)node; return GetDiagnosticSpan(destructorDeclaration.Modifiers, destructorDeclaration.TildeToken, destructorDeclaration.ParameterList); case SyntaxKind.PropertyDeclaration: var propertyDeclaration = (PropertyDeclarationSyntax)node; return GetDiagnosticSpan(propertyDeclaration.Modifiers, propertyDeclaration.Type, propertyDeclaration.Identifier); case SyntaxKind.IndexerDeclaration: var indexerDeclaration = (IndexerDeclarationSyntax)node; return GetDiagnosticSpan(indexerDeclaration.Modifiers, indexerDeclaration.Type, indexerDeclaration.ParameterList); case SyntaxKind.EventDeclaration: var eventDeclaration = (EventDeclarationSyntax)node; return GetDiagnosticSpan(eventDeclaration.Modifiers, eventDeclaration.EventKeyword, eventDeclaration.Identifier); case SyntaxKind.EnumMemberDeclaration: return node.Span; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.UnknownAccessorDeclaration: var accessorDeclaration = (AccessorDeclarationSyntax)node; return GetDiagnosticSpan(accessorDeclaration.Modifiers, accessorDeclaration.Keyword, accessorDeclaration.Keyword); case SyntaxKind.TypeParameterConstraintClause: var constraint = (TypeParameterConstraintClauseSyntax)node; return TextSpan.FromBounds(constraint.WhereKeyword.SpanStart, constraint.Constraints.Last().Span.End); case SyntaxKind.TypeParameter: var typeParameter = (TypeParameterSyntax)node; return typeParameter.Identifier.Span; case SyntaxKind.AccessorList: case SyntaxKind.TypeParameterList: case SyntaxKind.ParameterList: case SyntaxKind.BracketedParameterList: if (editKind == EditKind.Delete) { return TryGetDiagnosticSpanImpl(node.Parent!, editKind); } else { return node.Span; } case SyntaxKind.Parameter: var parameter = (ParameterSyntax)node; // Lambda parameters don't have types or modifiers, so the parameter is the only node var startNode = parameter.Type ?? (SyntaxNode)parameter; return GetDiagnosticSpan(parameter.Modifiers, startNode, parameter); case SyntaxKind.AttributeList: var attributeList = (AttributeListSyntax)node; return attributeList.Span; case SyntaxKind.Attribute: return node.Span; case SyntaxKind.ArrowExpressionClause: return TryGetDiagnosticSpanImpl(node.Parent!, editKind); // We only need a diagnostic span if reporting an error for a child statement. // The following statements may have child statements. case SyntaxKind.Block: return ((BlockSyntax)node).OpenBraceToken.Span; case SyntaxKind.UsingStatement: var usingStatement = (UsingStatementSyntax)node; return TextSpan.FromBounds(usingStatement.UsingKeyword.SpanStart, usingStatement.CloseParenToken.Span.End); case SyntaxKind.FixedStatement: var fixedStatement = (FixedStatementSyntax)node; return TextSpan.FromBounds(fixedStatement.FixedKeyword.SpanStart, fixedStatement.CloseParenToken.Span.End); case SyntaxKind.LockStatement: var lockStatement = (LockStatementSyntax)node; return TextSpan.FromBounds(lockStatement.LockKeyword.SpanStart, lockStatement.CloseParenToken.Span.End); case SyntaxKind.StackAllocArrayCreationExpression: return ((StackAllocArrayCreationExpressionSyntax)node).StackAllocKeyword.Span; case SyntaxKind.ImplicitStackAllocArrayCreationExpression: return ((ImplicitStackAllocArrayCreationExpressionSyntax)node).StackAllocKeyword.Span; case SyntaxKind.TryStatement: return ((TryStatementSyntax)node).TryKeyword.Span; case SyntaxKind.CatchClause: return ((CatchClauseSyntax)node).CatchKeyword.Span; case SyntaxKind.CatchDeclaration: case SyntaxKind.CatchFilterClause: return node.Span; case SyntaxKind.FinallyClause: return ((FinallyClauseSyntax)node).FinallyKeyword.Span; case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)node; return TextSpan.FromBounds(ifStatement.IfKeyword.SpanStart, ifStatement.CloseParenToken.Span.End); case SyntaxKind.ElseClause: return ((ElseClauseSyntax)node).ElseKeyword.Span; case SyntaxKind.SwitchStatement: var switchStatement = (SwitchStatementSyntax)node; return TextSpan.FromBounds(switchStatement.SwitchKeyword.SpanStart, (switchStatement.CloseParenToken != default) ? switchStatement.CloseParenToken.Span.End : switchStatement.Expression.Span.End); case SyntaxKind.SwitchSection: return ((SwitchSectionSyntax)node).Labels.Last().Span; case SyntaxKind.WhileStatement: var whileStatement = (WhileStatementSyntax)node; return TextSpan.FromBounds(whileStatement.WhileKeyword.SpanStart, whileStatement.CloseParenToken.Span.End); case SyntaxKind.DoStatement: return ((DoStatementSyntax)node).DoKeyword.Span; case SyntaxKind.ForStatement: var forStatement = (ForStatementSyntax)node; return TextSpan.FromBounds(forStatement.ForKeyword.SpanStart, forStatement.CloseParenToken.Span.End); case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: var commonForEachStatement = (CommonForEachStatementSyntax)node; return TextSpan.FromBounds( (commonForEachStatement.AwaitKeyword.Span.Length > 0) ? commonForEachStatement.AwaitKeyword.SpanStart : commonForEachStatement.ForEachKeyword.SpanStart, commonForEachStatement.CloseParenToken.Span.End); case SyntaxKind.LabeledStatement: return ((LabeledStatementSyntax)node).Identifier.Span; case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return ((CheckedStatementSyntax)node).Keyword.Span; case SyntaxKind.UnsafeStatement: return ((UnsafeStatementSyntax)node).UnsafeKeyword.Span; case SyntaxKind.LocalFunctionStatement: var lfd = (LocalFunctionStatementSyntax)node; return lfd.Identifier.Span; case SyntaxKind.YieldBreakStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.ExpressionStatement: case SyntaxKind.EmptyStatement: case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: case SyntaxKind.BreakStatement: case SyntaxKind.ContinueStatement: return node.Span; case SyntaxKind.LocalDeclarationStatement: var localDeclarationStatement = (LocalDeclarationStatementSyntax)node; return CombineSpans(localDeclarationStatement.AwaitKeyword.Span, localDeclarationStatement.UsingKeyword.Span, node.Span); case SyntaxKind.AwaitExpression: return ((AwaitExpressionSyntax)node).AwaitKeyword.Span; case SyntaxKind.AnonymousObjectCreationExpression: return ((AnonymousObjectCreationExpressionSyntax)node).NewKeyword.Span; case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)node).ParameterList.Span; case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)node).Parameter.Span; case SyntaxKind.AnonymousMethodExpression: return ((AnonymousMethodExpressionSyntax)node).DelegateKeyword.Span; case SyntaxKind.QueryExpression: return ((QueryExpressionSyntax)node).FromClause.FromKeyword.Span; case SyntaxKind.QueryBody: var queryBody = (QueryBodySyntax)node; return TryGetDiagnosticSpanImpl(queryBody.Clauses.FirstOrDefault() ?? queryBody.Parent!, editKind); case SyntaxKind.QueryContinuation: return ((QueryContinuationSyntax)node).IntoKeyword.Span; case SyntaxKind.FromClause: return ((FromClauseSyntax)node).FromKeyword.Span; case SyntaxKind.JoinClause: return ((JoinClauseSyntax)node).JoinKeyword.Span; case SyntaxKind.JoinIntoClause: return ((JoinIntoClauseSyntax)node).IntoKeyword.Span; case SyntaxKind.LetClause: return ((LetClauseSyntax)node).LetKeyword.Span; case SyntaxKind.WhereClause: return ((WhereClauseSyntax)node).WhereKeyword.Span; case SyntaxKind.OrderByClause: return ((OrderByClauseSyntax)node).OrderByKeyword.Span; case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return node.Span; case SyntaxKind.SelectClause: return ((SelectClauseSyntax)node).SelectKeyword.Span; case SyntaxKind.GroupClause: return ((GroupClauseSyntax)node).GroupKeyword.Span; case SyntaxKind.IsPatternExpression: case SyntaxKind.TupleType: case SyntaxKind.TupleExpression: case SyntaxKind.DeclarationExpression: case SyntaxKind.RefType: case SyntaxKind.RefExpression: case SyntaxKind.DeclarationPattern: case SyntaxKind.SimpleAssignmentExpression: case SyntaxKind.WhenClause: case SyntaxKind.SingleVariableDesignation: case SyntaxKind.CasePatternSwitchLabel: return node.Span; case SyntaxKind.SwitchExpression: return ((SwitchExpressionSyntax)node).SwitchKeyword.Span; case SyntaxKind.SwitchExpressionArm: return ((SwitchExpressionArmSyntax)node).EqualsGreaterThanToken.Span; default: return null; } } private static TextSpan GetDiagnosticSpan(SyntaxTokenList modifiers, SyntaxNodeOrToken start, SyntaxNodeOrToken end) => TextSpan.FromBounds((modifiers.Count != 0) ? modifiers.First().SpanStart : start.SpanStart, end.Span.End); private static TextSpan CombineSpans(TextSpan first, TextSpan second, TextSpan defaultSpan) => (first.Length > 0 && second.Length > 0) ? TextSpan.FromBounds(first.Start, second.End) : (first.Length > 0) ? first : (second.Length > 0) ? second : defaultSpan; internal override TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal) { Debug.Assert(ordinal >= 0); switch (lambda.Kind()) { case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)lambda).ParameterList.Parameters[ordinal].Identifier.Span; case SyntaxKind.SimpleLambdaExpression: Debug.Assert(ordinal == 0); return ((SimpleLambdaExpressionSyntax)lambda).Parameter.Identifier.Span; case SyntaxKind.AnonymousMethodExpression: // since we are given a parameter ordinal there has to be a parameter list: return ((AnonymousMethodExpressionSyntax)lambda).ParameterList!.Parameters[ordinal].Identifier.Span; default: return lambda.Span; } } internal override string GetDisplayName(INamedTypeSymbol symbol) => symbol.TypeKind switch { TypeKind.Struct => symbol.IsRecord ? CSharpFeaturesResources.record_struct : CSharpFeaturesResources.struct_, TypeKind.Class => symbol.IsRecord ? CSharpFeaturesResources.record_ : FeaturesResources.class_, _ => base.GetDisplayName(symbol) }; internal override string GetDisplayName(IPropertySymbol symbol) => symbol.IsIndexer ? CSharpFeaturesResources.indexer : base.GetDisplayName(symbol); internal override string GetDisplayName(IMethodSymbol symbol) => symbol.MethodKind switch { MethodKind.PropertyGet => symbol.AssociatedSymbol is IPropertySymbol { IsIndexer: true } ? CSharpFeaturesResources.indexer_getter : CSharpFeaturesResources.property_getter, MethodKind.PropertySet => symbol.AssociatedSymbol is IPropertySymbol { IsIndexer: true } ? CSharpFeaturesResources.indexer_setter : CSharpFeaturesResources.property_setter, MethodKind.StaticConstructor => FeaturesResources.static_constructor, MethodKind.Destructor => CSharpFeaturesResources.destructor, MethodKind.Conversion => CSharpFeaturesResources.conversion_operator, MethodKind.LocalFunction => FeaturesResources.local_function, _ => base.GetDisplayName(symbol) }; protected override string? TryGetDisplayName(SyntaxNode node, EditKind editKind) => TryGetDisplayNameImpl(node, editKind); internal static new string? GetDisplayName(SyntaxNode node, EditKind editKind) => TryGetDisplayNameImpl(node, editKind) ?? throw ExceptionUtilities.UnexpectedValue(node.Kind()); internal static string? TryGetDisplayNameImpl(SyntaxNode node, EditKind editKind) { switch (node.Kind()) { // top-level case SyntaxKind.CompilationUnit: case SyntaxKind.GlobalStatement: return CSharpFeaturesResources.global_statement; case SyntaxKind.ExternAliasDirective: return CSharpFeaturesResources.extern_alias; case SyntaxKind.UsingDirective: // Dev12 distinguishes using alias from using namespace and reports different errors for removing alias. // None of these changes are allowed anyways, so let's keep it simple. return CSharpFeaturesResources.using_directive; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return FeaturesResources.namespace_; case SyntaxKind.ClassDeclaration: return FeaturesResources.class_; case SyntaxKind.StructDeclaration: return CSharpFeaturesResources.struct_; case SyntaxKind.InterfaceDeclaration: return FeaturesResources.interface_; case SyntaxKind.RecordDeclaration: return CSharpFeaturesResources.record_; case SyntaxKind.RecordStructDeclaration: return CSharpFeaturesResources.record_struct; case SyntaxKind.EnumDeclaration: return FeaturesResources.enum_; case SyntaxKind.DelegateDeclaration: return FeaturesResources.delegate_; case SyntaxKind.FieldDeclaration: var declaration = (FieldDeclarationSyntax)node; return declaration.Modifiers.Any(SyntaxKind.ConstKeyword) ? FeaturesResources.const_field : FeaturesResources.field; case SyntaxKind.EventFieldDeclaration: return CSharpFeaturesResources.event_field; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: return TryGetDisplayNameImpl(node.Parent!, editKind); case SyntaxKind.MethodDeclaration: return FeaturesResources.method; case SyntaxKind.ConversionOperatorDeclaration: return CSharpFeaturesResources.conversion_operator; case SyntaxKind.OperatorDeclaration: return FeaturesResources.operator_; case SyntaxKind.ConstructorDeclaration: var ctor = (ConstructorDeclarationSyntax)node; return ctor.Modifiers.Any(SyntaxKind.StaticKeyword) ? FeaturesResources.static_constructor : FeaturesResources.constructor; case SyntaxKind.DestructorDeclaration: return CSharpFeaturesResources.destructor; case SyntaxKind.PropertyDeclaration: return SyntaxUtilities.HasBackingField((PropertyDeclarationSyntax)node) ? FeaturesResources.auto_property : FeaturesResources.property_; case SyntaxKind.IndexerDeclaration: return CSharpFeaturesResources.indexer; case SyntaxKind.EventDeclaration: return FeaturesResources.event_; case SyntaxKind.EnumMemberDeclaration: return FeaturesResources.enum_value; case SyntaxKind.GetAccessorDeclaration: if (node.Parent!.Parent!.IsKind(SyntaxKind.PropertyDeclaration)) { return CSharpFeaturesResources.property_getter; } else { RoslynDebug.Assert(node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration)); return CSharpFeaturesResources.indexer_getter; } case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: if (node.Parent!.Parent!.IsKind(SyntaxKind.PropertyDeclaration)) { return CSharpFeaturesResources.property_setter; } else { RoslynDebug.Assert(node.Parent.Parent.IsKind(SyntaxKind.IndexerDeclaration)); return CSharpFeaturesResources.indexer_setter; } case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return FeaturesResources.event_accessor; case SyntaxKind.ArrowExpressionClause: return node.Parent!.Kind() switch { SyntaxKind.PropertyDeclaration => CSharpFeaturesResources.property_getter, SyntaxKind.IndexerDeclaration => CSharpFeaturesResources.indexer_getter, _ => null }; case SyntaxKind.TypeParameterConstraintClause: return FeaturesResources.type_constraint; case SyntaxKind.TypeParameterList: case SyntaxKind.TypeParameter: return FeaturesResources.type_parameter; case SyntaxKind.Parameter: return FeaturesResources.parameter; case SyntaxKind.AttributeList: return FeaturesResources.attribute; case SyntaxKind.Attribute: return FeaturesResources.attribute; case SyntaxKind.AttributeTargetSpecifier: return CSharpFeaturesResources.attribute_target; // statement: case SyntaxKind.TryStatement: return CSharpFeaturesResources.try_block; case SyntaxKind.CatchClause: case SyntaxKind.CatchDeclaration: return CSharpFeaturesResources.catch_clause; case SyntaxKind.CatchFilterClause: return CSharpFeaturesResources.filter_clause; case SyntaxKind.FinallyClause: return CSharpFeaturesResources.finally_clause; case SyntaxKind.FixedStatement: return CSharpFeaturesResources.fixed_statement; case SyntaxKind.UsingStatement: return CSharpFeaturesResources.using_statement; case SyntaxKind.LockStatement: return CSharpFeaturesResources.lock_statement; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: return CSharpFeaturesResources.foreach_statement; case SyntaxKind.CheckedStatement: return CSharpFeaturesResources.checked_statement; case SyntaxKind.UncheckedStatement: return CSharpFeaturesResources.unchecked_statement; case SyntaxKind.YieldBreakStatement: return CSharpFeaturesResources.yield_break_statement; case SyntaxKind.YieldReturnStatement: return CSharpFeaturesResources.yield_return_statement; case SyntaxKind.AwaitExpression: return CSharpFeaturesResources.await_expression; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return CSharpFeaturesResources.lambda; case SyntaxKind.AnonymousMethodExpression: return CSharpFeaturesResources.anonymous_method; case SyntaxKind.FromClause: return CSharpFeaturesResources.from_clause; case SyntaxKind.JoinClause: case SyntaxKind.JoinIntoClause: return CSharpFeaturesResources.join_clause; case SyntaxKind.LetClause: return CSharpFeaturesResources.let_clause; case SyntaxKind.WhereClause: return CSharpFeaturesResources.where_clause; case SyntaxKind.OrderByClause: case SyntaxKind.AscendingOrdering: case SyntaxKind.DescendingOrdering: return CSharpFeaturesResources.orderby_clause; case SyntaxKind.SelectClause: return CSharpFeaturesResources.select_clause; case SyntaxKind.GroupClause: return CSharpFeaturesResources.groupby_clause; case SyntaxKind.QueryBody: return CSharpFeaturesResources.query_body; case SyntaxKind.QueryContinuation: return CSharpFeaturesResources.into_clause; case SyntaxKind.IsPatternExpression: return CSharpFeaturesResources.is_pattern; case SyntaxKind.SimpleAssignmentExpression: if (((AssignmentExpressionSyntax)node).IsDeconstruction()) { return CSharpFeaturesResources.deconstruction; } else { throw ExceptionUtilities.UnexpectedValue(node.Kind()); } case SyntaxKind.TupleType: case SyntaxKind.TupleExpression: return CSharpFeaturesResources.tuple; case SyntaxKind.LocalFunctionStatement: return CSharpFeaturesResources.local_function; case SyntaxKind.DeclarationExpression: return CSharpFeaturesResources.out_var; case SyntaxKind.RefType: case SyntaxKind.RefExpression: return CSharpFeaturesResources.ref_local_or_expression; case SyntaxKind.SwitchStatement: return CSharpFeaturesResources.switch_statement; case SyntaxKind.LocalDeclarationStatement: if (((LocalDeclarationStatementSyntax)node).UsingKeyword.IsKind(SyntaxKind.UsingKeyword)) { return CSharpFeaturesResources.using_declaration; } return CSharpFeaturesResources.local_variable_declaration; default: return null; } } protected override string GetSuspensionPointDisplayName(SyntaxNode node, EditKind editKind) { switch (node.Kind()) { case SyntaxKind.ForEachStatement: Debug.Assert(((CommonForEachStatementSyntax)node).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)); return CSharpFeaturesResources.asynchronous_foreach_statement; case SyntaxKind.VariableDeclarator: RoslynDebug.Assert(((LocalDeclarationStatementSyntax)node.Parent!.Parent!).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)); return CSharpFeaturesResources.asynchronous_using_declaration; default: return base.GetSuspensionPointDisplayName(node, editKind); } } #endregion #region Top-Level Syntactic Rude Edits private readonly struct EditClassifier { private readonly CSharpEditAndContinueAnalyzer _analyzer; private readonly ArrayBuilder<RudeEditDiagnostic> _diagnostics; private readonly Match<SyntaxNode>? _match; private readonly SyntaxNode? _oldNode; private readonly SyntaxNode? _newNode; private readonly EditKind _kind; private readonly TextSpan? _span; public EditClassifier( CSharpEditAndContinueAnalyzer analyzer, ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode? oldNode, SyntaxNode? newNode, EditKind kind, Match<SyntaxNode>? match = null, TextSpan? span = null) { RoslynDebug.Assert(oldNode != null || newNode != null); // if the node is deleted we have map that can be used to closest new ancestor RoslynDebug.Assert(newNode != null || match != null); _analyzer = analyzer; _diagnostics = diagnostics; _oldNode = oldNode; _newNode = newNode; _kind = kind; _span = span; _match = match; } private void ReportError(RudeEditKind kind, SyntaxNode? spanNode = null, SyntaxNode? displayNode = null) { var span = (spanNode != null) ? GetDiagnosticSpan(spanNode, _kind) : GetSpan(); var node = displayNode ?? _newNode ?? _oldNode; var displayName = GetDisplayName(node!, _kind); _diagnostics.Add(new RudeEditDiagnostic(kind, span, node, arguments: new[] { displayName })); } private TextSpan GetSpan() { if (_span.HasValue) { return _span.Value; } if (_newNode == null) { return _analyzer.GetDeletedNodeDiagnosticSpan(_match!.Matches, _oldNode!); } return GetDiagnosticSpan(_newNode, _kind); } public void ClassifyEdit() { switch (_kind) { case EditKind.Delete: ClassifyDelete(_oldNode!); return; case EditKind.Update: ClassifyUpdate(_oldNode!, _newNode!); return; case EditKind.Move: ClassifyMove(_newNode!); return; case EditKind.Insert: ClassifyInsert(_newNode!); return; case EditKind.Reorder: ClassifyReorder(_newNode!); return; default: throw ExceptionUtilities.UnexpectedValue(_kind); } } private void ClassifyMove(SyntaxNode newNode) { if (newNode.IsKind(SyntaxKind.LocalFunctionStatement)) { return; } // We could perhaps allow moving a type declaration to a different namespace syntax node // as long as it represents semantically the same namespace as the one of the original type declaration. ReportError(RudeEditKind.Move); } private void ClassifyReorder(SyntaxNode newNode) { if (_newNode.IsKind(SyntaxKind.LocalFunctionStatement)) { return; } switch (newNode.Kind()) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.VariableDeclarator: // Maybe we could allow changing order of field declarations unless the containing type layout is sequential. ReportError(RudeEditKind.Move); return; case SyntaxKind.EnumMemberDeclaration: // To allow this change we would need to check that values of all fields of the enum // are preserved, or make sure we can update all method bodies that accessed those that changed. ReportError(RudeEditKind.Move); return; case SyntaxKind.TypeParameter: case SyntaxKind.Parameter: ReportError(RudeEditKind.Move); return; } } private void ClassifyInsert(SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.ExternAliasDirective: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: ReportError(RudeEditKind.Insert); return; case SyntaxKind.Attribute: case SyntaxKind.AttributeList: // To allow inserting of attributes we need to check if the inserted attribute // is a pseudo-custom attribute that CLR allows us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (node.IsParentKind(SyntaxKind.CompilationUnit) || node.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Insert); } return; } } private void ClassifyDelete(SyntaxNode oldNode) { switch (oldNode.Kind()) { case SyntaxKind.ExternAliasDirective: case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: // To allow removal of declarations we would need to update method bodies that // were previously binding to them but now are binding to another symbol that was previously hidden. ReportError(RudeEditKind.Delete); return; case SyntaxKind.AttributeList: case SyntaxKind.Attribute: // To allow removal of attributes we need to check if the removed attribute // is a pseudo-custom attribute that CLR does not allow us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (oldNode.IsParentKind(SyntaxKind.CompilationUnit) || oldNode.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Delete); } return; } } private void ClassifyUpdate(SyntaxNode oldNode, SyntaxNode newNode) { switch (newNode.Kind()) { case SyntaxKind.ExternAliasDirective: ReportError(RudeEditKind.Update); return; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: ClassifyUpdate((BaseNamespaceDeclarationSyntax)oldNode, (BaseNamespaceDeclarationSyntax)newNode); return; case SyntaxKind.Attribute: // To allow update of attributes we need to check if the updated attribute // is a pseudo-custom attribute that CLR allows us to change, or if it is a compiler well-know attribute // that affects the generated IL, so we defer those checks until semantic analysis. // Unless the attribute is a module/assembly attribute if (newNode.IsParentKind(SyntaxKind.CompilationUnit) || newNode.Parent.IsParentKind(SyntaxKind.CompilationUnit)) { ReportError(RudeEditKind.Update); } return; } } private void ClassifyUpdate(BaseNamespaceDeclarationSyntax oldNode, BaseNamespaceDeclarationSyntax newNode) { Debug.Assert(!SyntaxFactory.AreEquivalent(oldNode.Name, newNode.Name)); ReportError(RudeEditKind.Renamed); } public void ClassifyDeclarationBodyRudeUpdates(SyntaxNode newDeclarationOrBody) { foreach (var node in newDeclarationOrBody.DescendantNodesAndSelf(LambdaUtilities.IsNotLambda)) { switch (node.Kind()) { case SyntaxKind.StackAllocArrayCreationExpression: case SyntaxKind.ImplicitStackAllocArrayCreationExpression: ReportError(RudeEditKind.StackAllocUpdate, node, _newNode); return; } } } } internal override void ReportTopLevelSyntacticRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap) { if (HasParentEdit(editMap, edit)) { return; } var classifier = new EditClassifier(this, diagnostics, edit.OldNode, edit.NewNode, edit.Kind, match); classifier.ClassifyEdit(); } internal override void ReportMemberBodyUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span) { var classifier = new EditClassifier(this, diagnostics, oldNode: null, newMember, EditKind.Update, span: span); classifier.ClassifyDeclarationBodyRudeUpdates(newMember); } #endregion #region Semantic Rude Edits internal override void ReportInsertedMemberSymbolRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newNode, bool insertingIntoExistingContainingType) { var rudeEditKind = newSymbol switch { // Inserting extern member into a new or existing type is not allowed. { IsExtern: true } => RudeEditKind.InsertExtern, // All rude edits below only apply when inserting into an existing type (not when the type itself is inserted): _ when !insertingIntoExistingContainingType => RudeEditKind.None, // Inserting a member into an existing generic type is not allowed. { ContainingType: { Arity: > 0 } } and not INamedTypeSymbol => RudeEditKind.InsertIntoGenericType, // Inserting virtual or interface member into an existing type is not allowed. { IsVirtual: true } or { IsOverride: true } or { IsAbstract: true } and not INamedTypeSymbol => RudeEditKind.InsertVirtual, // Inserting generic method into an existing type is not allowed. IMethodSymbol { Arity: > 0 } => RudeEditKind.InsertGenericMethod, // Inserting destructor to an existing type is not allowed. IMethodSymbol { MethodKind: MethodKind.Destructor } => RudeEditKind.Insert, // Inserting operator to an existing type is not allowed. IMethodSymbol { MethodKind: MethodKind.Conversion or MethodKind.UserDefinedOperator } => RudeEditKind.InsertOperator, // Inserting a method that explictly implements an interface method into an existing type is not allowed. IMethodSymbol { ExplicitInterfaceImplementations: { IsEmpty: false } } => RudeEditKind.InsertMethodWithExplicitInterfaceSpecifier, // TODO: Inserting non-virtual member to an interface (https://github.com/dotnet/roslyn/issues/37128) { ContainingType: { TypeKind: TypeKind.Interface } } and not INamedTypeSymbol => RudeEditKind.InsertIntoInterface, // Inserting a field into an enum: #pragma warning disable format // https://github.com/dotnet/roslyn/issues/54759 IFieldSymbol { ContainingType.TypeKind: TypeKind.Enum } => RudeEditKind.Insert, #pragma warning restore format _ => RudeEditKind.None }; if (rudeEditKind != RudeEditKind.None) { diagnostics.Add(new RudeEditDiagnostic( rudeEditKind, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, arguments: new[] { GetDisplayName(newNode, EditKind.Insert) })); } } #endregion #region Exception Handling Rude Edits /// <summary> /// Return nodes that represent exception handlers encompassing the given active statement node. /// </summary> protected override List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isNonLeaf) { var result = new List<SyntaxNode>(); var current = node; while (current != null) { var kind = current.Kind(); switch (kind) { case SyntaxKind.TryStatement: if (isNonLeaf) { result.Add(current); } break; case SyntaxKind.CatchClause: case SyntaxKind.FinallyClause: result.Add(current); // skip try: RoslynDebug.Assert(current.Parent is object); RoslynDebug.Assert(current.Parent.Kind() == SyntaxKind.TryStatement); current = current.Parent; break; // stop at type declaration: case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return result; } // stop at lambda: if (LambdaUtilities.IsLambda(current)) { return result; } current = current.Parent; } return result; } internal override void ReportEnclosingExceptionHandlingRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits, SyntaxNode oldStatement, TextSpan newStatementSpan) { foreach (var edit in exceptionHandlingEdits) { // try/catch/finally have distinct labels so only the nodes of the same kind may match: Debug.Assert(edit.Kind != EditKind.Update || edit.OldNode.RawKind == edit.NewNode.RawKind); if (edit.Kind != EditKind.Update || !AreExceptionClausesEquivalent(edit.OldNode, edit.NewNode)) { AddAroundActiveStatementRudeDiagnostic(diagnostics, edit.OldNode, edit.NewNode, newStatementSpan); } } } private static bool AreExceptionClausesEquivalent(SyntaxNode oldNode, SyntaxNode newNode) { switch (oldNode.Kind()) { case SyntaxKind.TryStatement: var oldTryStatement = (TryStatementSyntax)oldNode; var newTryStatement = (TryStatementSyntax)newNode; return SyntaxFactory.AreEquivalent(oldTryStatement.Finally, newTryStatement.Finally) && SyntaxFactory.AreEquivalent(oldTryStatement.Catches, newTryStatement.Catches); case SyntaxKind.CatchClause: case SyntaxKind.FinallyClause: return SyntaxFactory.AreEquivalent(oldNode, newNode); default: throw ExceptionUtilities.UnexpectedValue(oldNode.Kind()); } } /// <summary> /// An active statement (leaf or not) inside a "catch" makes the catch block read-only. /// An active statement (leaf or not) inside a "finally" makes the whole try/catch/finally block read-only. /// An active statement (non leaf) inside a "try" makes the catch/finally block read-only. /// </summary> /// <remarks> /// Exception handling regions are only needed to be tracked if they contain user code. /// <see cref="UsingStatementSyntax"/> and using <see cref="LocalDeclarationStatementSyntax"/> generate finally blocks, /// but they do not contain non-hidden sequence points. /// </remarks> /// <param name="node">An exception handling ancestor of an active statement node.</param> /// <param name="coversAllChildren"> /// True if all child nodes of the <paramref name="node"/> are contained in the exception region represented by the <paramref name="node"/>. /// </param> protected override TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren) { TryStatementSyntax tryStatement; switch (node.Kind()) { case SyntaxKind.TryStatement: tryStatement = (TryStatementSyntax)node; coversAllChildren = false; if (tryStatement.Catches.Count == 0) { RoslynDebug.Assert(tryStatement.Finally != null); return tryStatement.Finally.Span; } return TextSpan.FromBounds( tryStatement.Catches.First().SpanStart, (tryStatement.Finally != null) ? tryStatement.Finally.Span.End : tryStatement.Catches.Last().Span.End); case SyntaxKind.CatchClause: coversAllChildren = true; return node.Span; case SyntaxKind.FinallyClause: coversAllChildren = true; tryStatement = (TryStatementSyntax)node.Parent!; return tryStatement.Span; default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } #endregion #region State Machines internal override bool IsStateMachineMethod(SyntaxNode declaration) => SyntaxUtilities.IsAsyncDeclaration(declaration) || SyntaxUtilities.GetSuspensionPoints(declaration).Any(); protected override void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKinds kinds) { suspensionPoints = SyntaxUtilities.GetSuspensionPoints(body).ToImmutableArray(); kinds = StateMachineKinds.None; if (suspensionPoints.Any(n => n.IsKind(SyntaxKind.YieldBreakStatement) || n.IsKind(SyntaxKind.YieldReturnStatement))) { kinds |= StateMachineKinds.Iterator; } if (SyntaxUtilities.IsAsyncDeclaration(body.Parent)) { kinds |= StateMachineKinds.Async; } } internal override void ReportStateMachineSuspensionPointRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode) { // TODO: changes around suspension points (foreach, lock, using, etc.) if (newNode.IsKind(SyntaxKind.AwaitExpression)) { var oldContainingStatementPart = FindContainingStatementPart(oldNode); var newContainingStatementPart = FindContainingStatementPart(newNode); // If the old statement has spilled state and the new doesn't the edit is ok. We'll just not use the spilled state. if (!SyntaxFactory.AreEquivalent(oldContainingStatementPart, newContainingStatementPart) && !HasNoSpilledState(newNode, newContainingStatementPart)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.AwaitStatementUpdate, newContainingStatementPart.Span)); } } } internal override void ReportStateMachineSuspensionPointDeletedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode deletedSuspensionPoint) { // Handle deletion of await keyword from await foreach statement. if (deletedSuspensionPoint is CommonForEachStatementSyntax deletedForeachStatement && match.Matches.TryGetValue(deletedSuspensionPoint, out var newForEachStatement) && newForEachStatement is CommonForEachStatementSyntax && deletedForeachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetDiagnosticSpan(newForEachStatement, EditKind.Update), newForEachStatement, new[] { GetDisplayName(newForEachStatement, EditKind.Update) })); return; } // Handle deletion of await keyword from await using declaration. if (deletedSuspensionPoint.IsKind(SyntaxKind.VariableDeclarator) && match.Matches.TryGetValue(deletedSuspensionPoint.Parent!.Parent!, out var newLocalDeclaration) && !((LocalDeclarationStatementSyntax)newLocalDeclaration).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetDiagnosticSpan(newLocalDeclaration, EditKind.Update), newLocalDeclaration, new[] { GetDisplayName(newLocalDeclaration, EditKind.Update) })); return; } base.ReportStateMachineSuspensionPointDeletedRudeEdit(diagnostics, match, deletedSuspensionPoint); } internal override void ReportStateMachineSuspensionPointInsertedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode insertedSuspensionPoint, bool aroundActiveStatement) { // Handle addition of await keyword to foreach statement. if (insertedSuspensionPoint is CommonForEachStatementSyntax insertedForEachStatement && match.ReverseMatches.TryGetValue(insertedSuspensionPoint, out var oldNode) && oldNode is CommonForEachStatementSyntax oldForEachStatement && !oldForEachStatement.AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, insertedForEachStatement.AwaitKeyword.Span, insertedForEachStatement, new[] { insertedForEachStatement.AwaitKeyword.ToString() })); return; } // Handle addition of using keyword to using declaration. if (insertedSuspensionPoint.IsKind(SyntaxKind.VariableDeclarator) && match.ReverseMatches.TryGetValue(insertedSuspensionPoint.Parent!.Parent!, out var oldLocalDeclaration) && !((LocalDeclarationStatementSyntax)oldLocalDeclaration).AwaitKeyword.IsKind(SyntaxKind.AwaitKeyword)) { var newLocalDeclaration = (LocalDeclarationStatementSyntax)insertedSuspensionPoint!.Parent!.Parent!; diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, newLocalDeclaration.AwaitKeyword.Span, newLocalDeclaration, new[] { newLocalDeclaration.AwaitKeyword.ToString() })); return; } base.ReportStateMachineSuspensionPointInsertedRudeEdit(diagnostics, match, insertedSuspensionPoint, aroundActiveStatement); } private static SyntaxNode FindContainingStatementPart(SyntaxNode node) { while (true) { if (node is StatementSyntax statement) { return statement; } RoslynDebug.Assert(node is object); RoslynDebug.Assert(node.Parent is object); switch (node.Parent.Kind()) { case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.IfStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.LockStatement: case SyntaxKind.UsingStatement: case SyntaxKind.ArrowExpressionClause: return node; } if (LambdaUtilities.IsLambdaBodyStatementOrExpression(node)) { return node; } node = node.Parent; } } private static bool HasNoSpilledState(SyntaxNode awaitExpression, SyntaxNode containingStatementPart) { Debug.Assert(awaitExpression.IsKind(SyntaxKind.AwaitExpression)); // There is nothing within the statement part surrounding the await expression. if (containingStatementPart == awaitExpression) { return true; } switch (containingStatementPart.Kind()) { case SyntaxKind.ExpressionStatement: case SyntaxKind.ReturnStatement: var expression = GetExpressionFromStatementPart(containingStatementPart); // await expr; // return await expr; if (expression == awaitExpression) { return true; } // identifier = await expr; // return identifier = await expr; return IsSimpleAwaitAssignment(expression, awaitExpression); case SyntaxKind.VariableDeclaration: // var idf = await expr in using, for, etc. // EqualsValueClause -> VariableDeclarator -> VariableDeclaration return awaitExpression.Parent!.Parent!.Parent == containingStatementPart; case SyntaxKind.LocalDeclarationStatement: // var idf = await expr; // EqualsValueClause -> VariableDeclarator -> VariableDeclaration -> LocalDeclarationStatement return awaitExpression.Parent!.Parent!.Parent!.Parent == containingStatementPart; } return IsSimpleAwaitAssignment(containingStatementPart, awaitExpression); } private static ExpressionSyntax GetExpressionFromStatementPart(SyntaxNode statement) { switch (statement.Kind()) { case SyntaxKind.ExpressionStatement: return ((ExpressionStatementSyntax)statement).Expression; case SyntaxKind.ReturnStatement: // Must have an expression since we are only inspecting at statements that contain an expression. return ((ReturnStatementSyntax)statement).Expression!; default: throw ExceptionUtilities.UnexpectedValue(statement.Kind()); } } private static bool IsSimpleAwaitAssignment(SyntaxNode node, SyntaxNode awaitExpression) { if (node.IsKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment)) { return assignment.Left.IsKind(SyntaxKind.IdentifierName) && assignment.Right == awaitExpression; } return false; } #endregion #region Rude Edits around Active Statement internal override void ReportOtherRudeEditsAroundActiveStatement( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, bool isNonLeaf) { ReportRudeEditsForSwitchWhenClauses(diagnostics, oldActiveStatement, newActiveStatement); ReportRudeEditsForAncestorsDeclaringInterStatementTemps(diagnostics, match, oldActiveStatement, newActiveStatement); ReportRudeEditsForCheckedStatements(diagnostics, oldActiveStatement, newActiveStatement, isNonLeaf); } /// <summary> /// Reports rude edits when an active statement is a when clause in a switch statement and any of the switch cases or the switch value changed. /// This is necessary since the switch emits long-lived synthesized variables to store results of pattern evaluations. /// These synthesized variables are mapped to the slots of the new methods via ordinals. The mapping preserves the values of these variables as long as /// exactly the same variables are emitted for the new switch as they were for the old one and their order didn't change either. /// This is guaranteed if none of the case clauses have changed. /// </summary> private void ReportRudeEditsForSwitchWhenClauses(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement) { if (!oldActiveStatement.IsKind(SyntaxKind.WhenClause)) { return; } // switch expression does not have sequence points (active statements): if (!(oldActiveStatement.Parent!.Parent!.Parent is SwitchStatementSyntax oldSwitch)) { return; } // switch statement does not match switch expression, so it must be part of a switch statement as well. var newSwitch = (SwitchStatementSyntax)newActiveStatement.Parent!.Parent!.Parent!; // when clauses can only match other when clauses: Debug.Assert(newActiveStatement.IsKind(SyntaxKind.WhenClause)); if (!AreEquivalentIgnoringLambdaBodies(oldSwitch.Expression, newSwitch.Expression)) { AddRudeUpdateAroundActiveStatement(diagnostics, newSwitch); } if (!AreEquivalentSwitchStatementDecisionTrees(oldSwitch, newSwitch)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, GetDiagnosticSpan(newSwitch, EditKind.Update), newSwitch, new[] { CSharpFeaturesResources.switch_statement_case_clause })); } } private static bool AreEquivalentSwitchStatementDecisionTrees(SwitchStatementSyntax oldSwitch, SwitchStatementSyntax newSwitch) => oldSwitch.Sections.SequenceEqual(newSwitch.Sections, AreSwitchSectionsEquivalent); private static bool AreSwitchSectionsEquivalent(SwitchSectionSyntax oldSection, SwitchSectionSyntax newSection) => oldSection.Labels.SequenceEqual(newSection.Labels, AreLabelsEquivalent); private static bool AreLabelsEquivalent(SwitchLabelSyntax oldLabel, SwitchLabelSyntax newLabel) { if (oldLabel.IsKind(SyntaxKind.CasePatternSwitchLabel, out CasePatternSwitchLabelSyntax? oldCasePatternLabel) && newLabel.IsKind(SyntaxKind.CasePatternSwitchLabel, out CasePatternSwitchLabelSyntax? newCasePatternLabel)) { // ignore the actual when expressions: return SyntaxFactory.AreEquivalent(oldCasePatternLabel.Pattern, newCasePatternLabel.Pattern) && (oldCasePatternLabel.WhenClause != null) == (newCasePatternLabel.WhenClause != null); } else { return SyntaxFactory.AreEquivalent(oldLabel, newLabel); } } private void ReportRudeEditsForCheckedStatements( ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, bool isNonLeaf) { // checked context can't be changed around non-leaf active statement: if (!isNonLeaf) { return; } // Changing checked context around an internal active statement may change the instructions // executed after method calls in the active statement but before the next sequence point. // Since the debugger remaps the IP at the first sequence point following a call instruction // allowing overflow context to be changed may lead to execution of code with old semantics. var oldCheckedStatement = TryGetCheckedStatementAncestor(oldActiveStatement); var newCheckedStatement = TryGetCheckedStatementAncestor(newActiveStatement); bool isRude; if (oldCheckedStatement == null || newCheckedStatement == null) { isRude = oldCheckedStatement != newCheckedStatement; } else { isRude = oldCheckedStatement.Kind() != newCheckedStatement.Kind(); } if (isRude) { AddAroundActiveStatementRudeDiagnostic(diagnostics, oldCheckedStatement, newCheckedStatement, newActiveStatement.Span); } } private static CheckedStatementSyntax? TryGetCheckedStatementAncestor(SyntaxNode? node) { // Ignoring lambda boundaries since checked context flows through. while (node != null) { switch (node.Kind()) { case SyntaxKind.CheckedStatement: case SyntaxKind.UncheckedStatement: return (CheckedStatementSyntax)node; } node = node.Parent; } return null; } private void ReportRudeEditsForAncestorsDeclaringInterStatementTemps( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement) { // Rude Edits for fixed/using/lock/foreach statements that are added/updated around an active statement. // Although such changes are technically possible, they might lead to confusion since // the temporary variables these statements generate won't be properly initialized. // // We use a simple algorithm to match each new node with its old counterpart. // If all nodes match this algorithm is linear, otherwise it's quadratic. // // Unlike exception regions matching where we use LCS, we allow reordering of the statements. ReportUnmatchedStatements<LockStatementSyntax>(diagnostics, match, n => n.IsKind(SyntaxKind.LockStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: null); ReportUnmatchedStatements<FixedStatementSyntax>(diagnostics, match, n => n.IsKind(SyntaxKind.FixedStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: (n1, n2) => DeclareSameIdentifiers(n1.Declaration.Variables, n2.Declaration.Variables)); // Using statements with declaration do not introduce compiler generated temporary. ReportUnmatchedStatements<UsingStatementSyntax>( diagnostics, match, n => n.IsKind(SyntaxKind.UsingStatement, out UsingStatementSyntax? usingStatement) && usingStatement.Declaration is null, oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: null); ReportUnmatchedStatements<CommonForEachStatementSyntax>( diagnostics, match, n => n.IsKind(SyntaxKind.ForEachStatement) || n.IsKind(SyntaxKind.ForEachVariableStatement), oldActiveStatement, newActiveStatement, areEquivalent: AreEquivalentActiveStatements, areSimilar: AreSimilarActiveStatements); } private static bool DeclareSameIdentifiers(SeparatedSyntaxList<VariableDeclaratorSyntax> oldVariables, SeparatedSyntaxList<VariableDeclaratorSyntax> newVariables) => DeclareSameIdentifiers(oldVariables.Select(v => v.Identifier).ToArray(), newVariables.Select(v => v.Identifier).ToArray()); private static bool DeclareSameIdentifiers(SyntaxToken[] oldVariables, SyntaxToken[] newVariables) { if (oldVariables.Length != newVariables.Length) { return false; } for (var i = 0; i < oldVariables.Length; i++) { if (!SyntaxFactory.AreEquivalent(oldVariables[i], newVariables[i])) { return false; } } return true; } #endregion } }
1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Features/Core/Portable/EditAndContinue/AbstractEditAndContinueAnalyzer.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.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal abstract class AbstractEditAndContinueAnalyzer : IEditAndContinueAnalyzer { internal const int DefaultStatementPart = 0; private const string CreateNewOnMetadataUpdateAttributeName = "CreateNewOnMetadataUpdateAttribute"; /// <summary> /// Contains enough information to determine whether two symbols have the same signature. /// </summary> private static readonly SymbolDisplayFormat s_unqualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private static readonly SymbolDisplayFormat s_fullyQualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); // used by tests to validate correct handlign of unexpected exceptions private readonly Action<SyntaxNode>? _testFaultInjector; protected AbstractEditAndContinueAnalyzer(Action<SyntaxNode>? testFaultInjector) { _testFaultInjector = testFaultInjector; } internal abstract bool ExperimentalFeaturesEnabled(SyntaxTree tree); /// <summary> /// Finds member declaration node(s) containing given <paramref name="node"/>. /// Specified <paramref name="node"/> may be either a node of the declaration body or an active node that belongs to the declaration. /// </summary> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// Note that in some cases the set of nodes of the declaration body may differ from the set of active nodes that /// belong to the declaration. For example, in <c>Dim a, b As New T</c> the sets for member <c>a</c> are /// { <c>New</c>, <c>T</c> } and { <c>a</c> }, respectively. /// /// May return multiple declarations if the specified <paramref name="node"/> belongs to multiple declarations, /// such as in VB <c>Dim a, b As New T</c> case when <paramref name="node"/> is e.g. <c>T</c>. /// </remarks> internal abstract bool TryFindMemberDeclaration(SyntaxNode? root, SyntaxNode node, out OneOrMany<SyntaxNode> declarations); /// <summary> /// If the specified node represents a member declaration returns a node that represents its body, /// i.e. a node used as the root of statement-level match. /// </summary> /// <param name="node">A node representing a declaration or a top-level edit node.</param> /// /// <returns> /// Returns null for nodes that don't represent declarations. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// If a member doesn't have a body (null is returned) it can't have associated active statements. /// /// Body does not need to cover all active statements that may be associated with the member. /// E.g. Body of a C# constructor is the method body block. Active statements may be placed on the base constructor call. /// Body of a VB field declaration with shared AsNew initializer is the New expression. Active statements might be placed on the field variables. /// <see cref="FindStatementAndPartner"/> has to account for such cases. /// </remarks> internal abstract SyntaxNode? TryGetDeclarationBody(SyntaxNode node); /// <summary> /// True if the specified <paramref name="declaration"/> node shares body with another declaration. /// </summary> internal abstract bool IsDeclarationWithSharedBody(SyntaxNode declaration); /// <summary> /// If the specified node represents a member declaration returns all tokens of the member declaration /// that might be covered by an active statement. /// </summary> /// <returns> /// Tokens covering all possible breakpoint spans associated with the member, /// or null if the specified node doesn't represent a member declaration or /// doesn't have a body that can contain active statements. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// TODO: consider implementing this via <see cref="GetActiveSpanEnvelope"/>. /// </remarks> internal abstract IEnumerable<SyntaxToken>? TryGetActiveTokens(SyntaxNode node); /// <summary> /// Returns a span that contains all possible breakpoint spans of the <paramref name="declaration"/> /// and no breakpoint spans that do not belong to the <paramref name="declaration"/>. /// /// Returns default if the declaration does not have any breakpoint spans. /// </summary> internal abstract (TextSpan envelope, TextSpan hole) GetActiveSpanEnvelope(SyntaxNode declaration); /// <summary> /// Returns an ancestor that encompasses all active and statement level /// nodes that belong to the member represented by <paramref name="bodyOrMatchRoot"/>. /// </summary> protected SyntaxNode? GetEncompassingAncestor(SyntaxNode? bodyOrMatchRoot) { if (bodyOrMatchRoot == null) { return null; } var root = GetEncompassingAncestorImpl(bodyOrMatchRoot); Debug.Assert(root.Span.Contains(bodyOrMatchRoot.Span)); return root; } protected abstract SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot); /// <summary> /// Finds a statement at given span and a declaration body. /// Also returns the corresponding partner statement in <paramref name="partnerDeclarationBody"/>, if specified. /// </summary> /// <remarks> /// The declaration body node may not contain the <paramref name="span"/>. /// This happens when an active statement associated with the member is outside of its body /// (e.g. C# constructor, or VB <c>Dim a,b As New T</c>). /// If the position doesn't correspond to any statement uses the start of the <paramref name="declarationBody"/>. /// </remarks> protected abstract SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, TextSpan span, SyntaxNode? partnerDeclarationBody, out SyntaxNode? partner, out int statementPart); private SyntaxNode FindStatement(SyntaxNode declarationBody, TextSpan span, out int statementPart) => FindStatementAndPartner(declarationBody, span, null, out _, out statementPart); /// <summary> /// Maps <paramref name="leftNode"/> of a body of <paramref name="leftDeclaration"/> to corresponding body node /// of <paramref name="rightDeclaration"/>, assuming that the declaration bodies only differ in trivia. /// </summary> internal abstract SyntaxNode FindDeclarationBodyPartner(SyntaxNode leftDeclaration, SyntaxNode rightDeclaration, SyntaxNode leftNode); /// <summary> /// Returns a node that represents a body of a lambda containing specified <paramref name="node"/>, /// or null if the node isn't contained in a lambda. If a node is returned it must uniquely represent the lambda, /// i.e. be no two distinct nodes may represent the same lambda. /// </summary> protected abstract SyntaxNode? FindEnclosingLambdaBody(SyntaxNode? container, SyntaxNode node); /// <summary> /// Given a node that represents a lambda body returns all nodes of the body in a syntax list. /// </summary> /// <remarks> /// Note that VB lambda bodies are represented by a lambda header and that some lambda bodies share /// their parent nodes with other bodies (e.g. join clause expressions). /// </remarks> protected abstract IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody); protected abstract SyntaxNode? TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda); protected abstract Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit); protected abstract Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>>? knownMatches); protected abstract Match<SyntaxNode> ComputeTopLevelDeclarationMatch(SyntaxNode oldDeclaration, SyntaxNode newDeclaration); protected abstract IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes); /// <summary> /// Matches old active statement to new active statement without constructing full method body match. /// This is needed for active statements that are outside of method body, like constructor initializer. /// </summary> protected abstract bool TryMatchActiveStatement( SyntaxNode oldStatement, int statementPart, SyntaxNode oldBody, SyntaxNode newBody, [NotNullWhen(true)] out SyntaxNode? newStatement); protected abstract bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span); /// <summary> /// Get the active span that corresponds to specified node (or its part). /// </summary> /// <returns> /// True if the node has an active span associated with it, false otherwise. /// </returns> protected abstract bool TryGetActiveSpan(SyntaxNode node, int statementPart, int minLength, out TextSpan span); /// <summary> /// Yields potential active statements around the specified active statement /// starting with siblings following the statement, then preceding the statement, follows with its parent, its following siblings, etc. /// </summary> /// <returns> /// Pairs of (node, statement part), or (node, -1) indicating there is no logical following statement. /// The enumeration continues until the root is reached. /// </returns> protected abstract IEnumerable<(SyntaxNode statement, int statementPart)> EnumerateNearStatements(SyntaxNode statement); protected abstract bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2); /// <summary> /// True if both nodes represent the same kind of suspension point /// (await expression, await foreach statement, await using declarator, yield return, yield break). /// </summary> protected virtual bool StateMachineSuspensionPointKindEquals(SyntaxNode suspensionPoint1, SyntaxNode suspensionPoint2) => suspensionPoint1.RawKind == suspensionPoint2.RawKind; /// <summary> /// Determines if two syntax nodes are the same, disregarding trivia differences. /// </summary> protected abstract bool AreEquivalent(SyntaxNode left, SyntaxNode right); /// <summary> /// Returns true if the code emitted for the old active statement part (<paramref name="statementPart"/> of <paramref name="oldStatement"/>) /// is the same as the code emitted for the corresponding new active statement part (<paramref name="statementPart"/> of <paramref name="newStatement"/>). /// </summary> /// <remarks> /// A rude edit is reported if an active statement is changed and this method returns true. /// </remarks> protected abstract bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart); protected abstract TextSpan GetGlobalStatementDiagnosticSpan(SyntaxNode node); /// <summary> /// Returns all symbols associated with an edit and an actual edit kind, which may be different then the specified one. /// Returns an empty set if the edit is not associated with any symbols. /// </summary> protected abstract OneOrMany<(ISymbol? oldSymbol, ISymbol? newSymbol, EditKind editKind)> GetSymbolEdits( EditKind editKind, SyntaxNode? oldNode, SyntaxNode? newNode, SemanticModel? oldModel, SemanticModel newModel, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken); /// <summary> /// Analyzes data flow in the member body represented by the specified node and returns all captured variables and parameters (including "this"). /// If the body is a field/property initializer analyzes the initializer expression only. /// </summary> protected abstract ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody); /// <summary> /// Enumerates all use sites of a specified variable within the specified syntax subtrees. /// </summary> protected abstract IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken); protected abstract bool AreHandledEventsEqual(IMethodSymbol oldMethod, IMethodSymbol newMethod); // diagnostic spans: protected abstract TextSpan? TryGetDiagnosticSpan(SyntaxNode node, EditKind editKind); internal TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpan(node, editKind) ?? node.Span; protected virtual TextSpan GetBodyDiagnosticSpan(SyntaxNode node, EditKind editKind) { var current = node.Parent; while (true) { if (current == null) { return node.Span; } var span = TryGetDiagnosticSpan(current, editKind); if (span != null) { return span.Value; } current = current.Parent; } } internal abstract TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal); // display names: internal string GetDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) => TryGetDisplayName(node, editKind) ?? throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); internal string GetDisplayName(ISymbol symbol) => symbol.Kind switch { SymbolKind.Event => FeaturesResources.event_, SymbolKind.Field => GetDisplayName((IFieldSymbol)symbol), SymbolKind.Method => GetDisplayName((IMethodSymbol)symbol), SymbolKind.NamedType => GetDisplayName((INamedTypeSymbol)symbol), SymbolKind.Parameter => FeaturesResources.parameter, SymbolKind.Property => GetDisplayName((IPropertySymbol)symbol), SymbolKind.TypeParameter => FeaturesResources.type_parameter, _ => throw ExceptionUtilities.UnexpectedValue(symbol.Kind) }; internal virtual string GetDisplayName(IPropertySymbol symbol) => FeaturesResources.property_; internal virtual string GetDisplayName(INamedTypeSymbol symbol) => symbol.TypeKind switch { TypeKind.Class => FeaturesResources.class_, TypeKind.Interface => FeaturesResources.interface_, TypeKind.Delegate => FeaturesResources.delegate_, TypeKind.Enum => FeaturesResources.enum_, TypeKind.TypeParameter => FeaturesResources.type_parameter, _ => FeaturesResources.type, }; internal virtual string GetDisplayName(IFieldSymbol symbol) => symbol.IsConst ? ((symbol.ContainingType.TypeKind == TypeKind.Enum) ? FeaturesResources.enum_value : FeaturesResources.const_field) : FeaturesResources.field; internal virtual string GetDisplayName(IMethodSymbol symbol) => symbol.MethodKind switch { MethodKind.Constructor => FeaturesResources.constructor, MethodKind.PropertyGet or MethodKind.PropertySet => FeaturesResources.property_accessor, MethodKind.EventAdd or MethodKind.EventRaise or MethodKind.EventRemove => FeaturesResources.event_accessor, MethodKind.BuiltinOperator or MethodKind.UserDefinedOperator or MethodKind.Conversion => FeaturesResources.operator_, _ => FeaturesResources.method, }; /// <summary> /// Returns the display name of an ancestor node that contains the specified node and has a display name. /// </summary> protected virtual string GetBodyDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) { var current = node.Parent; while (true) { if (current == null) { throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); } var displayName = TryGetDisplayName(current, editKind); if (displayName != null) { return displayName; } current = current.Parent; } } protected abstract string? TryGetDisplayName(SyntaxNode node, EditKind editKind); protected virtual string GetSuspensionPointDisplayName(SyntaxNode node, EditKind editKind) => GetDisplayName(node, editKind); protected abstract string LineDirectiveKeyword { get; } protected abstract ushort LineDirectiveSyntaxKind { get; } protected abstract SymbolDisplayFormat ErrorDisplayFormat { get; } protected abstract List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isNonLeaf); protected abstract void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKinds kinds); protected abstract TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren); protected abstract void ReportLocalFunctionsDeclarationRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> bodyMatch); internal abstract void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap); internal abstract void ReportEnclosingExceptionHandlingRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits, SyntaxNode oldStatement, TextSpan newStatementSpan); internal abstract void ReportOtherRudeEditsAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldStatement, SyntaxNode newStatement, bool isNonLeaf); internal abstract void ReportMemberBodyUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span); internal abstract void ReportInsertedMemberSymbolRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newNode, bool insertingIntoExistingContainingType); internal abstract void ReportStateMachineSuspensionPointRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode); internal abstract bool IsLambda(SyntaxNode node); internal abstract bool IsInterfaceDeclaration(SyntaxNode node); internal abstract bool IsRecordDeclaration(SyntaxNode node); /// <summary> /// True if the node represents any form of a function definition nested in another function body (i.e. anonymous function, lambda, local function). /// </summary> internal abstract bool IsNestedFunction(SyntaxNode node); internal abstract bool IsLocalFunction(SyntaxNode node); internal abstract bool IsClosureScope(SyntaxNode node); internal abstract bool ContainsLambda(SyntaxNode declaration); internal abstract SyntaxNode GetLambda(SyntaxNode lambdaBody); internal abstract IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken); internal abstract SyntaxNode? GetContainingQueryExpression(SyntaxNode node); internal abstract bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken); /// <summary> /// Returns true if the parameters of the symbol are lifted into a scope that is different from the symbol's body. /// </summary> internal abstract bool HasParameterClosureScope(ISymbol member); /// <summary> /// Returns all lambda bodies of a node representing a lambda, /// or false if the node doesn't represent a lambda. /// </summary> /// <remarks> /// C# anonymous function expression and VB lambda expression both have a single body /// (in VB the body is the header of the lambda expression). /// /// Some lambda queries (group by, join by) have two bodies. /// </remarks> internal abstract bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? body1, out SyntaxNode? body2); internal abstract bool IsStateMachineMethod(SyntaxNode declaration); /// <summary> /// Returns the type declaration that contains a specified <paramref name="node"/>. /// This can be class, struct, interface, record or enum declaration. /// </summary> internal abstract SyntaxNode? TryGetContainingTypeDeclaration(SyntaxNode node); /// <summary> /// Returns the declaration of /// - a property, indexer or event declaration whose accessor is the specified <paramref name="node"/>, /// - a method, an indexer or a type (delegate) if the <paramref name="node"/> is a parameter, /// - a method or an type if the <paramref name="node"/> is a type parameter. /// </summary> internal abstract bool TryGetAssociatedMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? declaration); internal abstract bool HasBackingField(SyntaxNode propertyDeclaration); /// <summary> /// Return true if the declaration is a field/property declaration with an initializer. /// Shall return false for enum members. /// </summary> internal abstract bool IsDeclarationWithInitializer(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a parameter that is part of a records primary constructor. /// </summary> internal abstract bool IsRecordPrimaryConstructorParameter(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a property accessor for a property that represents one of the parameters in a records primary constructor. /// </summary> internal abstract bool IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType, out bool isFirstAccessor); /// <summary> /// Return true if the declaration is a constructor declaration to which field/property initializers are emitted. /// </summary> internal abstract bool IsConstructorWithMemberInitializers(SyntaxNode declaration); internal abstract bool IsPartial(INamedTypeSymbol type); internal abstract SyntaxNode EmptyCompilationUnit { get; } private static readonly SourceText s_emptySource = SourceText.From(""); #region Document Analysis public async Task<DocumentAnalysisResults> AnalyzeDocumentAsync( Project oldProject, AsyncLazy<ActiveStatementsMap> lazyOldActiveStatementMap, Document newDocument, ImmutableArray<LinePositionSpan> newActiveStatementSpans, AsyncLazy<EditAndContinueCapabilities> lazyCapabilities, CancellationToken cancellationToken) { DocumentAnalysisResults.Log.Write("Analyzing document {0}", newDocument.Name); Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newDocument.SupportsSyntaxTree); Debug.Assert(newDocument.SupportsSemanticModel); // assume changes until we determine there are none so that EnC is blocked on unexpected exception: var hasChanges = true; try { cancellationToken.ThrowIfCancellationRequested(); SyntaxTree? oldTree; SyntaxNode oldRoot; SourceText oldText; var oldDocument = await oldProject.GetDocumentAsync(newDocument.Id, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (oldDocument != null) { oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldTree); oldRoot = await oldTree.GetRootAsync(cancellationToken).ConfigureAwait(false); oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); } else { oldTree = null; oldRoot = EmptyCompilationUnit; oldText = s_emptySource; } var newTree = await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(newTree); // Changes in parse options might change the meaning of the code even if nothing else changed. // The IDE should disallow changing the options during debugging session. Debug.Assert(oldTree == null || oldTree.Options.Equals(newTree.Options)); var newRoot = await newTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); hasChanges = !oldText.ContentEquals(newText); _testFaultInjector?.Invoke(newRoot); cancellationToken.ThrowIfCancellationRequested(); // TODO: newTree.HasErrors? var syntaxDiagnostics = newRoot.GetDiagnostics(); var hasSyntaxError = syntaxDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error); if (hasSyntaxError) { // Bail, since we can't do syntax diffing on broken trees (it would not produce useful results anyways). // If we needed to do so for some reason, we'd need to harden the syntax tree comparers. DocumentAnalysisResults.Log.Write("{0}: syntax errors", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray<RudeEditDiagnostic>.Empty, hasChanges); } if (!hasChanges) { // The document might have been closed and reopened, which might have triggered analysis. // If the document is unchanged don't continue the analysis since // a) comparing texts is cheaper than diffing trees // b) we need to ignore errors in unchanged documents DocumentAnalysisResults.Log.Write("{0}: unchanged", newDocument.Name); return DocumentAnalysisResults.Unchanged(newDocument.Id); } // Disallow modification of a file with experimental features enabled. // These features may not be handled well by the analysis below. if (ExperimentalFeaturesEnabled(newTree)) { DocumentAnalysisResults.Log.Write("{0}: experimental features enabled", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.ExperimentalFeaturesEnabled, default)), hasChanges); } var capabilities = await lazyCapabilities.GetValueAsync(cancellationToken).ConfigureAwait(false); var oldActiveStatementMap = await lazyOldActiveStatementMap.GetValueAsync(cancellationToken).ConfigureAwait(false); // If the document has changed at all, lets make sure Edit and Continue is supported if (!capabilities.HasFlag(EditAndContinueCapabilities.Baseline)) { return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.NotSupportedByRuntime, default)), hasChanges); } // We are in break state when there are no active statements. var inBreakState = !oldActiveStatementMap.IsEmpty; // We do calculate diffs even if there are semantic errors for the following reasons: // 1) We need to be able to find active spans in the new document. // If we didn't calculate them we would only rely on tracking spans (might be ok). // 2) If there are syntactic rude edits we'll report them faster without waiting for semantic analysis. // The user may fix them before they address all the semantic errors. using var _2 = ArrayBuilder<RudeEditDiagnostic>.GetInstance(out var diagnostics); cancellationToken.ThrowIfCancellationRequested(); var topMatch = ComputeTopLevelMatch(oldRoot, newRoot); var syntacticEdits = topMatch.GetTreeEdits(); var editMap = BuildEditMap(syntacticEdits); var hasRudeEdits = false; ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0} syntactic rude edits, first: '{1}'", diagnostics.Count, newDocument.FilePath); hasRudeEdits = true; } cancellationToken.ThrowIfCancellationRequested(); using var _3 = ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)>.GetInstance(out var triviaEdits); using var _4 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var lineEdits); AnalyzeTrivia( topMatch, editMap, triviaEdits, lineEdits, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); var oldActiveStatements = (oldTree == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : oldActiveStatementMap.GetOldActiveStatements(this, oldTree, oldText, oldRoot, cancellationToken); var newActiveStatements = ImmutableArray.CreateBuilder<ActiveStatement>(oldActiveStatements.Length); newActiveStatements.Count = oldActiveStatements.Length; var newExceptionRegions = ImmutableArray.CreateBuilder<ImmutableArray<SourceFileSpan>>(oldActiveStatements.Length); newExceptionRegions.Count = oldActiveStatements.Length; var semanticEdits = await AnalyzeSemanticsAsync( syntacticEdits, editMap, oldActiveStatements, newActiveStatementSpans, triviaEdits, oldProject, oldDocument, newDocument, newText, diagnostics, newActiveStatements, newExceptionRegions, capabilities, inBreakState, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AnalyzeUnchangedActiveMemberBodies(diagnostics, syntacticEdits.Match, newText, oldActiveStatements, newActiveStatementSpans, newActiveStatements, newExceptionRegions, cancellationToken); Debug.Assert(newActiveStatements.All(a => a != null)); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0}@{1}: rude edit ({2} total)", newDocument.FilePath, diagnostics.First().Span.Start, diagnostics.Count); hasRudeEdits = true; } return new DocumentAnalysisResults( newDocument.Id, newActiveStatements.MoveToImmutable(), diagnostics.ToImmutable(), hasRudeEdits ? default : semanticEdits, hasRudeEdits ? default : newExceptionRegions.MoveToImmutable(), hasRudeEdits ? default : lineEdits.ToImmutable(), hasChanges: true, hasSyntaxErrors: false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // The same behavior as if there was a syntax error - we are unable to analyze the document. // We expect OOM to be thrown during the analysis if the number of top-level entities is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. var diagnostic = (e is OutOfMemoryException) ? new RudeEditDiagnostic(RudeEditKind.SourceFileTooBig, span: default, arguments: new[] { newDocument.FilePath }) : new RudeEditDiagnostic(RudeEditKind.InternalError, span: default, arguments: new[] { newDocument.FilePath, e.ToString() }); // Report as "syntax error" - we can't analyze the document return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create(diagnostic), hasChanges); } } private void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) { foreach (var edit in syntacticEdits.Edits) { ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits.Match, edit, editMap); } } /// <summary> /// Reports rude edits for a symbol that's been deleted in one location and inserted in another and the edit was not classified as /// <see cref="EditKind.Move"/> or <see cref="EditKind.Reorder"/>. /// The scenarios include moving a type declaration from one file to another and moving a member of a partial type from one partial declaration to another. /// </summary> internal virtual void ReportDeclarationInsertDeleteRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode, ISymbol oldSymbol, ISymbol newSymbol, CancellationToken cancellationToken) { // When a method is moved to a different declaration and its parameters are changed at the same time // the new method symbol key will not resolve to the old one since the parameters are different. // As a result we will report separate delete and insert rude edits. // // For delegates, however, the symbol key will resolve to the old type so we need to report // rude edits here. if (oldSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var oldDelegateInvoke } && newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newDelegateInvoke }) { if (!ParameterTypesEquivalent(oldDelegateInvoke.Parameters, newDelegateInvoke.Parameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingParameterTypes, newSymbol, newNode, cancellationToken); } } } internal static Dictionary<SyntaxNode, EditKind> BuildEditMap(EditScript<SyntaxNode> editScript) { var map = new Dictionary<SyntaxNode, EditKind>(editScript.Edits.Length); foreach (var edit in editScript.Edits) { // do not include reorder and move edits if (edit.Kind is EditKind.Delete or EditKind.Update) { map.Add(edit.OldNode, edit.Kind); } if (edit.Kind is EditKind.Insert or EditKind.Update) { map.Add(edit.NewNode, edit.Kind); } } return map; } #endregion #region Syntax Analysis private void AnalyzeUnchangedActiveMemberBodies( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> topMatch, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, [In, Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [In, Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Count); // Active statements in methods that were not updated // are not changed but their spans might have been. for (var i = 0; i < newActiveStatements.Count; i++) { if (newActiveStatements[i] == null) { Contract.ThrowIfFalse(newExceptionRegions[i].IsDefault); var oldStatementSpan = oldActiveStatements[i].UnmappedSpan; var node = TryGetNode(topMatch.OldRoot, oldStatementSpan.Start); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (node != null && TryFindMemberDeclaration(topMatch.OldRoot, node, out var oldMemberDeclarations)) { foreach (var oldMember in oldMemberDeclarations) { var hasPartner = topMatch.TryGetNewNode(oldMember, out var newMember); Contract.ThrowIfFalse(hasPartner); var oldBody = TryGetDeclarationBody(oldMember); var newBody = TryGetDeclarationBody(newMember); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (oldBody == null || newBody == null) { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); continue; } var statementPart = -1; SyntaxNode? newStatement = null; // We seed the method body matching algorithm with tracking spans (unless they were deleted) // to get precise matching. if (TryGetTrackedStatement(newActiveStatementSpans, i, newText, newMember, newBody, out var trackedStatement, out var trackedStatementPart)) { // Adjust for active statements that cover more than the old member span. // For example, C# variable declarators that represent field initializers: // [|public int <<F = Expr()>>;|] var adjustedOldStatementStart = oldMember.FullSpan.Contains(oldStatementSpan.Start) ? oldStatementSpan.Start : oldMember.SpanStart; // The tracking span might have been moved outside of lambda. // It is not an error to move the statement - we just ignore it. var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldMember.FindToken(adjustedOldStatementStart).Parent!); var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, trackedStatement); if (oldEnclosingLambdaBody == newEnclosingLambdaBody) { newStatement = trackedStatement; statementPart = trackedStatementPart; } } if (newStatement == null) { Contract.ThrowIfFalse(statementPart == -1); FindStatementAndPartner(oldBody, oldStatementSpan, newBody, out newStatement, out statementPart); Contract.ThrowIfNull(newStatement); } if (diagnostics.Count == 0) { var ancestors = GetExceptionHandlingAncestors(newStatement, oldActiveStatements[i].Statement.IsNonLeaf); newExceptionRegions[i] = GetExceptionRegions(ancestors, newStatement.SyntaxTree, cancellationToken).Spans; } // Even though the body of the declaration haven't changed, // changes to its header might have caused the active span to become unavailable. // (e.g. In C# "const" was added to modifiers of a field with an initializer). var newStatementSpan = FindClosestActiveSpan(newStatement, statementPart); newActiveStatements[i] = GetActiveStatementWithSpan(oldActiveStatements[i], newBody.SyntaxTree, newStatementSpan, diagnostics, cancellationToken); } } else { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); } // we were not able to determine the active statement location (PDB data might be invalid) if (newActiveStatements[i] == null) { newActiveStatements[i] = oldActiveStatements[i].Statement.WithSpan(default); newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } } } } internal readonly struct ActiveNode { public readonly int ActiveStatementIndex; public readonly SyntaxNode OldNode; public readonly SyntaxNode? NewTrackedNode; public readonly SyntaxNode? EnclosingLambdaBody; public readonly int StatementPart; public ActiveNode(int activeStatementIndex, SyntaxNode oldNode, SyntaxNode? enclosingLambdaBody, int statementPart, SyntaxNode? newTrackedNode) { ActiveStatementIndex = activeStatementIndex; OldNode = oldNode; NewTrackedNode = newTrackedNode; EnclosingLambdaBody = enclosingLambdaBody; StatementPart = statementPart; } } /// <summary> /// Information about an active and/or a matched lambda. /// </summary> internal readonly struct LambdaInfo { // non-null for an active lambda (lambda containing an active statement) public readonly List<int>? ActiveNodeIndices; // both fields are non-null for a matching lambda (lambda that exists in both old and new document): public readonly Match<SyntaxNode>? Match; public readonly SyntaxNode? NewBody; public LambdaInfo(List<int> activeNodeIndices) : this(activeNodeIndices, null, null) { } private LambdaInfo(List<int>? activeNodeIndices, Match<SyntaxNode>? match, SyntaxNode? newLambdaBody) { ActiveNodeIndices = activeNodeIndices; Match = match; NewBody = newLambdaBody; } public LambdaInfo WithMatch(Match<SyntaxNode> match, SyntaxNode newLambdaBody) => new(ActiveNodeIndices, match, newLambdaBody); } private void AnalyzeChangedMemberBody( SyntaxNode oldDeclaration, SyntaxNode newDeclaration, SyntaxNode oldBody, SyntaxNode? newBody, SemanticModel oldModel, SemanticModel newModel, ISymbol oldSymbol, ISymbol newSymbol, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, EditAndContinueCapabilities capabilities, [Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.IsEmpty || oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(newActiveStatements.Count == newExceptionRegions.Count); syntaxMap = null; var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); if (newBody == null) { // The body has been deleted. var newSpan = FindClosestActiveSpan(newDeclaration, DefaultStatementPart); Debug.Assert(newSpan != default); foreach (var activeStatementIndex in activeStatementIndices) { // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). if (newActiveStatements[activeStatementIndex] != null) { Debug.Assert(IsDeclarationWithSharedBody(newDeclaration)); continue; } newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; } return; } try { ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, GetDiagnosticSpan(newDeclaration, EditKind.Update)); _testFaultInjector?.Invoke(newBody); // Populated with active lambdas and matched lambdas. // Unmatched non-active lambdas are not included. // { old-lambda-body -> info } Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas = null; // finds leaf nodes that correspond to the old active statements: using var _ = ArrayBuilder<ActiveNode>.GetInstance(out var activeNodes); foreach (var activeStatementIndex in activeStatementIndices) { var oldStatementSpan = oldActiveStatements[activeStatementIndex].UnmappedSpan; var oldStatementSyntax = FindStatement(oldBody, oldStatementSpan, out var statementPart); Contract.ThrowIfNull(oldStatementSyntax); var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldStatementSyntax); if (oldEnclosingLambdaBody != null) { lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); if (!lazyActiveOrMatchedLambdas.TryGetValue(oldEnclosingLambdaBody, out var lambda)) { lambda = new LambdaInfo(new List<int>()); lazyActiveOrMatchedLambdas.Add(oldEnclosingLambdaBody, lambda); } lambda.ActiveNodeIndices!.Add(activeNodes.Count); } SyntaxNode? trackedNode = null; if (TryGetTrackedStatement(newActiveStatementSpans, activeStatementIndex, newText, newDeclaration, newBody, out var newStatementSyntax, out var _)) { var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, newStatementSyntax); // The tracking span might have been moved outside of the lambda span. // It is not an error to move the statement - we just ignore it. if (oldEnclosingLambdaBody == newEnclosingLambdaBody && StatementLabelEquals(oldStatementSyntax, newStatementSyntax)) { trackedNode = newStatementSyntax; } } activeNodes.Add(new ActiveNode(activeStatementIndex, oldStatementSyntax, oldEnclosingLambdaBody, statementPart, trackedNode)); } var bodyMatch = ComputeBodyMatch(oldBody, newBody, activeNodes.Where(n => n.EnclosingLambdaBody == null).ToArray(), diagnostics, out var oldHasStateMachineSuspensionPoint, out var newHasStateMachineSuspensionPoint); var map = ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); if (oldHasStateMachineSuspensionPoint) { ReportStateMachineRudeEdits(oldModel.Compilation, oldSymbol, newBody, diagnostics); } else if (newHasStateMachineSuspensionPoint && !capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { // Adding a state machine, either for async or iterator, will require creating a new helper class // so is a rude edit if the runtime doesn't support it if (newSymbol is IMethodSymbol { IsAsync: true }) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodAsync, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } else { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodIterator, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } } ReportLambdaAndClosureRudeEdits( oldModel, oldBody, newModel, newBody, newSymbol, lazyActiveOrMatchedLambdas, map, capabilities, diagnostics, out var newBodyHasLambdas, cancellationToken); // We need to provide syntax map to the compiler if // 1) The new member has a active statement // The values of local variables declared or synthesized in the method have to be preserved. // 2) The new member generates a state machine // In case the state machine is suspended we need to preserve variables. // 3) The new member contains lambdas // We need to map new lambdas in the method to the matching old ones. // If the old method has lambdas but the new one doesn't there is nothing to preserve. // 4) Constructor that emits initializers is updated. // We create syntax map even if it's not necessary: if any data member initializers are active/contain lambdas. // Since initializers are usually simple the map should not be large enough to make it worth optimizing it away. if (!activeNodes.IsEmpty() || newHasStateMachineSuspensionPoint || newBodyHasLambdas || IsConstructorWithMemberInitializers(newDeclaration) || IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration)) { syntaxMap = CreateSyntaxMap(map.Reverse); } foreach (var activeNode in activeNodes) { var activeStatementIndex = activeNode.ActiveStatementIndex; var hasMatching = false; var isNonLeaf = oldActiveStatements[activeStatementIndex].Statement.IsNonLeaf; var isPartiallyExecuted = (oldActiveStatements[activeStatementIndex].Statement.Flags & ActiveStatementFlags.PartiallyExecuted) != 0; var statementPart = activeNode.StatementPart; var oldStatementSyntax = activeNode.OldNode; var oldEnclosingLambdaBody = activeNode.EnclosingLambdaBody; newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; TextSpan newSpan; SyntaxNode? newStatementSyntax; Match<SyntaxNode>? match; if (oldEnclosingLambdaBody == null) { match = bodyMatch; hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldBody, newBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); var oldLambdaInfo = lazyActiveOrMatchedLambdas[oldEnclosingLambdaBody]; var newEnclosingLambdaBody = oldLambdaInfo.NewBody; match = oldLambdaInfo.Match; if (match != null) { RoslynDebug.Assert(newEnclosingLambdaBody != null); // matching lambda has body hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldEnclosingLambdaBody, newEnclosingLambdaBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { // Lambda match is null if lambdas can't be matched, // in such case we won't have active statement matched either. hasMatching = false; newStatementSyntax = null; } } if (hasMatching) { RoslynDebug.Assert(newStatementSyntax != null); RoslynDebug.Assert(match != null); // The matching node doesn't produce sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. newSpan = FindClosestActiveSpan(newStatementSyntax, statementPart); if ((isNonLeaf || isPartiallyExecuted) && !AreEquivalentActiveStatements(oldStatementSyntax, newStatementSyntax, statementPart)) { // rude edit: non-leaf active statement changed diagnostics.Add(new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.ActiveStatementUpdate : RudeEditKind.PartiallyExecutedActiveStatementUpdate, newSpan)); } // other statements around active statement: ReportOtherRudeEditsAroundActiveStatement(diagnostics, match, oldStatementSyntax, newStatementSyntax, isNonLeaf); } else if (match == null) { RoslynDebug.Assert(oldEnclosingLambdaBody != null); RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); newSpan = GetDeletedNodeDiagnosticSpan(oldEnclosingLambdaBody, bodyMatch, lazyActiveOrMatchedLambdas); // Lambda containing the active statement can't be found in the new source. var oldLambda = GetLambda(oldEnclosingLambdaBody); diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.ActiveStatementLambdaRemoved, newSpan, oldLambda, new[] { GetDisplayName(oldLambda) })); } else { newSpan = GetDeletedNodeActiveSpan(match.Matches, oldStatementSyntax); if (isNonLeaf || isPartiallyExecuted) { // rude edit: internal active statement deleted diagnostics.Add( new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.DeleteActiveStatement : RudeEditKind.PartiallyExecutedActiveStatementDelete, GetDeletedNodeDiagnosticSpan(match.Matches, oldStatementSyntax), arguments: new[] { FeaturesResources.code })); } } // exception handling around the statement: CalculateExceptionRegionsAroundActiveStatement( bodyMatch, oldStatementSyntax, newStatementSyntax, newSpan, activeStatementIndex, isNonLeaf, newExceptionRegions, diagnostics, cancellationToken); // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). Debug.Assert(IsDeclarationWithSharedBody(newDeclaration) || newActiveStatements[activeStatementIndex] == null); Debug.Assert(newSpan != default); newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // Set the new spans of active statements overlapping the method body to match the old spans. // Even though these might be now outside of the method body it's ok since we report a rude edit and don't allow to continue. foreach (var i in activeStatementIndices) { newActiveStatements[i] = oldActiveStatements[i].Statement; newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } // We expect OOM to be thrown during the analysis if the number of statements is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. diagnostics.Add(new RudeEditDiagnostic( (e is OutOfMemoryException) ? RudeEditKind.MemberBodyTooBig : RudeEditKind.MemberBodyInternalError, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, arguments: new[] { GetBodyDisplayName(newBody) })); } } private bool TryGetTrackedStatement(ImmutableArray<LinePositionSpan> activeStatementSpans, int index, SourceText text, SyntaxNode declaration, SyntaxNode body, [NotNullWhen(true)] out SyntaxNode? trackedStatement, out int trackedStatementPart) { trackedStatement = null; trackedStatementPart = -1; // Active statements are not tracked in this document (e.g. the file is closed). if (activeStatementSpans.IsEmpty) { return false; } var trackedLineSpan = activeStatementSpans[index]; if (trackedLineSpan == default) { return false; } var trackedSpan = text.Lines.GetTextSpan(trackedLineSpan); // The tracking span might have been deleted or moved outside of the member span. // It is not an error to move the statement - we just ignore it. // Consider: Instead of checking here, explicitly handle all cases when active statements can be outside of the body in FindStatement and // return false if the requested span is outside of the active envelope. var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (!envelope.Contains(trackedSpan) || hole.Contains(trackedSpan)) { return false; } trackedStatement = FindStatement(body, trackedSpan, out trackedStatementPart); return true; } private ActiveStatement GetActiveStatementWithSpan(UnmappedActiveStatement oldStatement, SyntaxTree newTree, TextSpan newSpan, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var mappedLineSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); if (mappedLineSpan.HasMappedPath && mappedLineSpan.Path != oldStatement.Statement.FileSpan.Path) { // changing the source file of an active statement diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, newSpan, LineDirectiveSyntaxKind, arguments: new[] { string.Format(FeaturesResources._0_directive, LineDirectiveKeyword) })); } return oldStatement.Statement.WithFileSpan(mappedLineSpan); } private void CalculateExceptionRegionsAroundActiveStatement( Match<SyntaxNode> bodyMatch, SyntaxNode oldStatementSyntax, SyntaxNode? newStatementSyntax, TextSpan newStatementSyntaxSpan, int ordinal, bool isNonLeaf, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { if (newStatementSyntax == null) { if (!bodyMatch.NewRoot.Span.Contains(newStatementSyntaxSpan.Start)) { return; } newStatementSyntax = bodyMatch.NewRoot.FindToken(newStatementSyntaxSpan.Start).Parent; Contract.ThrowIfNull(newStatementSyntax); } var oldAncestors = GetExceptionHandlingAncestors(oldStatementSyntax, isNonLeaf); var newAncestors = GetExceptionHandlingAncestors(newStatementSyntax, isNonLeaf); if (oldAncestors.Count > 0 || newAncestors.Count > 0) { var edits = bodyMatch.GetSequenceEdits(oldAncestors, newAncestors); ReportEnclosingExceptionHandlingRudeEdits(diagnostics, edits, oldStatementSyntax, newStatementSyntaxSpan); // Exception regions are not needed in presence of errors. if (diagnostics.Count == 0) { Debug.Assert(oldAncestors.Count == newAncestors.Count); newExceptionRegions[ordinal] = GetExceptionRegions(newAncestors, newStatementSyntax.SyntaxTree, cancellationToken).Spans; } } } /// <summary> /// Calculates a syntax map of the entire method body including all lambda bodies it contains (recursively). /// </summary> private BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { ArrayBuilder<Match<SyntaxNode>>? lambdaBodyMatches = null; var currentLambdaBodyMatch = -1; var currentBodyMatch = bodyMatch; while (true) { foreach (var (oldNode, newNode) in currentBodyMatch.Matches) { // Skip root, only enumerate body matches. if (oldNode == currentBodyMatch.OldRoot) { Debug.Assert(newNode == currentBodyMatch.NewRoot); continue; } if (TryGetLambdaBodies(oldNode, out var oldLambdaBody1, out var oldLambdaBody2)) { lambdaBodyMatches ??= ArrayBuilder<Match<SyntaxNode>>.GetInstance(); lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); var newLambdaBody1 = TryGetPartnerLambdaBody(oldLambdaBody1, newNode); if (newLambdaBody1 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody1, newLambdaBody1, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } if (oldLambdaBody2 != null) { var newLambdaBody2 = TryGetPartnerLambdaBody(oldLambdaBody2, newNode); if (newLambdaBody2 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody2, newLambdaBody2, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } } } } currentLambdaBodyMatch++; if (lambdaBodyMatches == null || currentLambdaBodyMatch == lambdaBodyMatches.Count) { break; } currentBodyMatch = lambdaBodyMatches[currentLambdaBodyMatch]; } if (lambdaBodyMatches == null) { return BidirectionalMap<SyntaxNode>.FromMatch(bodyMatch); } var map = new Dictionary<SyntaxNode, SyntaxNode>(); var reverseMap = new Dictionary<SyntaxNode, SyntaxNode>(); // include all matches, including the root: map.AddRange(bodyMatch.Matches); reverseMap.AddRange(bodyMatch.ReverseMatches); foreach (var lambdaBodyMatch in lambdaBodyMatches) { foreach (var pair in lambdaBodyMatch.Matches) { if (!map.ContainsKey(pair.Key)) { map[pair.Key] = pair.Value; reverseMap[pair.Value] = pair.Key; } } } lambdaBodyMatches?.Free(); return new BidirectionalMap<SyntaxNode>(map, reverseMap); } private Match<SyntaxNode> ComputeLambdaBodyMatch( SyntaxNode oldLambdaBody, SyntaxNode newLambdaBody, IReadOnlyList<ActiveNode> activeNodes, [Out] Dictionary<SyntaxNode, LambdaInfo> activeOrMatchedLambdas, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics) { ActiveNode[]? activeNodesInLambda; if (activeOrMatchedLambdas.TryGetValue(oldLambdaBody, out var info)) { // Lambda may be matched but not be active. activeNodesInLambda = info.ActiveNodeIndices?.Select(i => activeNodes[i]).ToArray(); } else { // If the lambda body isn't in the map it doesn't have any active/tracked statements. activeNodesInLambda = null; info = new LambdaInfo(); } var lambdaBodyMatch = ComputeBodyMatch(oldLambdaBody, newLambdaBody, activeNodesInLambda ?? Array.Empty<ActiveNode>(), diagnostics, out _, out _); activeOrMatchedLambdas[oldLambdaBody] = info.WithMatch(lambdaBodyMatch, newLambdaBody); return lambdaBodyMatch; } private Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches = null; List<SequenceEdit>? lazyRudeEdits = null; GetStateMachineInfo(oldBody, out var oldStateMachineSuspensionPoints, out var oldStateMachineKinds); GetStateMachineInfo(newBody, out var newStateMachineSuspensionPoints, out var newStateMachineKinds); AddMatchingActiveNodes(ref lazyKnownMatches, activeNodes); // Consider following cases: // 1) Both old and new methods contain yields/awaits. // Map the old suspension points to new ones, report errors for added/deleted suspension points. // 2) The old method contains yields/awaits but the new doesn't. // Report rude edits for each deleted yield/await. // 3) The new method contains yields/awaits but the old doesn't. // a) If the method has active statements report rude edits for each inserted yield/await (insert "around" an active statement). // b) If the method has no active statements then the edit is valid, we don't need to calculate map. // 4) The old method is async/iterator, the new method is not and it contains an active statement. // Report rude edit since we can't remap IP from MoveNext to the kickoff method. // Note that iterators in VB don't need to contain yield, so this case is not covered by change in number of yields. var creatingStateMachineAroundActiveStatement = oldStateMachineSuspensionPoints.Length == 0 && newStateMachineSuspensionPoints.Length > 0 && activeNodes.Length > 0; oldHasStateMachineSuspensionPoint = oldStateMachineSuspensionPoints.Length > 0; newHasStateMachineSuspensionPoint = newStateMachineSuspensionPoints.Length > 0; if (oldStateMachineSuspensionPoints.Length > 0 || creatingStateMachineAroundActiveStatement) { AddMatchingStateMachineSuspensionPoints(ref lazyKnownMatches, ref lazyRudeEdits, oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); } var match = ComputeBodyMatch(oldBody, newBody, lazyKnownMatches); if (IsLocalFunction(match.OldRoot) && IsLocalFunction(match.NewRoot)) { ReportLocalFunctionsDeclarationRudeEdits(diagnostics, match); } if (lazyRudeEdits != null) { foreach (var rudeEdit in lazyRudeEdits) { if (rudeEdit.Kind == EditKind.Delete) { var deletedNode = oldStateMachineSuspensionPoints[rudeEdit.OldIndex]; ReportStateMachineSuspensionPointDeletedRudeEdit(diagnostics, match, deletedNode); } else { Debug.Assert(rudeEdit.Kind == EditKind.Insert); var insertedNode = newStateMachineSuspensionPoints[rudeEdit.NewIndex]; ReportStateMachineSuspensionPointInsertedRudeEdit(diagnostics, match, insertedNode, creatingStateMachineAroundActiveStatement); } } } else if (oldStateMachineSuspensionPoints.Length > 0) { Debug.Assert(oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length); for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { var oldNode = oldStateMachineSuspensionPoints[i]; var newNode = newStateMachineSuspensionPoints[i]; // changing yield return to yield break, await to await foreach, yield to await, etc. if (StateMachineSuspensionPointKindEquals(oldNode, newNode)) { Debug.Assert(StatementLabelEquals(oldNode, newNode)); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingStateMachineShape, newNode.Span, newNode, new[] { GetSuspensionPointDisplayName(oldNode, EditKind.Update), GetSuspensionPointDisplayName(newNode, EditKind.Update) })); } ReportStateMachineSuspensionPointRudeEdits(diagnostics, oldNode, newNode); } } else if (activeNodes.Length > 0) { // It is allowed to update a regular method to an async method or an iterator. // The only restriction is a presence of an active statement in the method body // since the debugger does not support remapping active statements to a different method. if (oldStateMachineKinds != newStateMachineKinds) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, GetBodyDiagnosticSpan(newBody, EditKind.Update))); } } // report removing async as rude: if (lazyRudeEdits == null) { if ((oldStateMachineKinds & StateMachineKinds.Async) != 0 && (newStateMachineKinds & StateMachineKinds.Async) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } // VB supports iterator lambdas/methods without yields if ((oldStateMachineKinds & StateMachineKinds.Iterator) != 0 && (newStateMachineKinds & StateMachineKinds.Iterator) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ModifiersUpdate, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } } return match; } internal virtual void ReportStateMachineSuspensionPointDeletedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode deletedSuspensionPoint) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, GetDeletedNodeDiagnosticSpan(match.Matches, deletedSuspensionPoint), deletedSuspensionPoint, new[] { GetSuspensionPointDisplayName(deletedSuspensionPoint, EditKind.Delete) })); } internal virtual void ReportStateMachineSuspensionPointInsertedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode insertedSuspensionPoint, bool aroundActiveStatement) { diagnostics.Add(new RudeEditDiagnostic( aroundActiveStatement ? RudeEditKind.InsertAroundActiveStatement : RudeEditKind.Insert, GetDiagnosticSpan(insertedSuspensionPoint, EditKind.Insert), insertedSuspensionPoint, new[] { GetSuspensionPointDisplayName(insertedSuspensionPoint, EditKind.Insert) })); } private static void AddMatchingActiveNodes(ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, IEnumerable<ActiveNode> activeNodes) { // add nodes that are tracked by the editor buffer to known matches: foreach (var activeNode in activeNodes) { if (activeNode.NewTrackedNode != null) { lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); lazyKnownMatches.Add(KeyValuePairUtil.Create(activeNode.OldNode, activeNode.NewTrackedNode)); } } } private void AddMatchingStateMachineSuspensionPoints( ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, ref List<SequenceEdit>? lazyRudeEdits, ImmutableArray<SyntaxNode> oldStateMachineSuspensionPoints, ImmutableArray<SyntaxNode> newStateMachineSuspensionPoints) { // State machine suspension points (yield statements, await expressions, await foreach loops, await using declarations) // determine the structure of the generated state machine. // Change of the SM structure is far more significant then changes of the value (arguments) of these nodes. // Hence we build the match such that these nodes are fixed. lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); void AddMatch(ref List<KeyValuePair<SyntaxNode, SyntaxNode>> lazyKnownMatches, int oldIndex, int newIndex) { var oldNode = oldStateMachineSuspensionPoints[oldIndex]; var newNode = newStateMachineSuspensionPoints[newIndex]; if (StatementLabelEquals(oldNode, newNode)) { lazyKnownMatches.Add(KeyValuePairUtil.Create(oldNode, newNode)); } } if (oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length) { for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { AddMatch(ref lazyKnownMatches, i, i); } } else { // use LCS to provide better errors (deletes, inserts and updates) var edits = GetSyntaxSequenceEdits(oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); foreach (var edit in edits) { var editKind = edit.Kind; if (editKind == EditKind.Update) { AddMatch(ref lazyKnownMatches, edit.OldIndex, edit.NewIndex); } else { lazyRudeEdits ??= new List<SequenceEdit>(); lazyRudeEdits.Add(edit); } } Debug.Assert(lazyRudeEdits != null); } } public ActiveStatementExceptionRegions GetExceptionRegions(SyntaxNode syntaxRoot, TextSpan unmappedActiveStatementSpan, bool isNonLeaf, CancellationToken cancellationToken) { var token = syntaxRoot.FindToken(unmappedActiveStatementSpan.Start); var ancestors = GetExceptionHandlingAncestors(token.Parent!, isNonLeaf); return GetExceptionRegions(ancestors, syntaxRoot.SyntaxTree, cancellationToken); } private ActiveStatementExceptionRegions GetExceptionRegions(List<SyntaxNode> exceptionHandlingAncestors, SyntaxTree tree, CancellationToken cancellationToken) { if (exceptionHandlingAncestors.Count == 0) { return new ActiveStatementExceptionRegions(ImmutableArray<SourceFileSpan>.Empty, isActiveStatementCovered: false); } var isCovered = false; using var _ = ArrayBuilder<SourceFileSpan>.GetInstance(out var result); for (var i = exceptionHandlingAncestors.Count - 1; i >= 0; i--) { var span = GetExceptionHandlingRegion(exceptionHandlingAncestors[i], out var coversAllChildren); // TODO: https://github.com/dotnet/roslyn/issues/52971 // 1) Check that the span doesn't cross #line pragmas with different file mappings. // 2) Check that the mapped path does not change and report rude edits if it does. result.Add(tree.GetMappedLineSpan(span, cancellationToken)); // Exception regions describe regions of code that can't be edited. // If the span covers all the children nodes we don't need to descend further. if (coversAllChildren) { isCovered = true; break; } } return new ActiveStatementExceptionRegions(result.ToImmutable(), isCovered); } private TextSpan GetDeletedNodeDiagnosticSpan(SyntaxNode deletedLambdaBody, Match<SyntaxNode> match, Dictionary<SyntaxNode, LambdaInfo> lambdaInfos) { var oldLambdaBody = deletedLambdaBody; while (true) { var oldParentLambdaBody = FindEnclosingLambdaBody(match.OldRoot, GetLambda(oldLambdaBody)); if (oldParentLambdaBody == null) { return GetDeletedNodeDiagnosticSpan(match.Matches, oldLambdaBody); } if (lambdaInfos.TryGetValue(oldParentLambdaBody, out var lambdaInfo) && lambdaInfo.Match != null) { return GetDeletedNodeDiagnosticSpan(lambdaInfo.Match.Matches, oldLambdaBody); } oldLambdaBody = oldParentLambdaBody; } } private TextSpan FindClosestActiveSpan(SyntaxNode statement, int statementPart) { if (TryGetActiveSpan(statement, statementPart, minLength: statement.Span.Length, out var span)) { return span; } // The node doesn't have sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. foreach (var (node, part) in EnumerateNearStatements(statement)) { if (part == -1) { return node.Span; } if (TryGetActiveSpan(node, part, minLength: 0, out span)) { return span; } } // This might occur in cases where we report rude edit, so the exact location of the active span doesn't matter. // For example, when a method expression body is removed in C#. return statement.Span; } internal TextSpan GetDeletedNodeActiveSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { foreach (var (oldNode, part) in EnumerateNearStatements(deletedNode)) { if (part == -1) { break; } if (forwardMap.TryGetValue(oldNode, out var newNode)) { return FindClosestActiveSpan(newNode, part); } } return GetDeletedNodeDiagnosticSpan(forwardMap, deletedNode); } internal TextSpan GetDeletedNodeDiagnosticSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { var hasAncestor = TryGetMatchingAncestor(forwardMap, deletedNode, out var newAncestor); RoslynDebug.Assert(hasAncestor && newAncestor != null); return GetDiagnosticSpan(newAncestor, EditKind.Delete); } /// <summary> /// Finds the inner-most ancestor of the specified node that has a matching node in the new tree. /// </summary> private static bool TryGetMatchingAncestor(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode? oldNode, [NotNullWhen(true)] out SyntaxNode? newAncestor) { while (oldNode != null) { if (forwardMap.TryGetValue(oldNode, out newAncestor)) { return true; } oldNode = oldNode.Parent; } // only happens if original oldNode is a root, // otherwise we always find a matching ancestor pair (roots). newAncestor = null; return false; } private IEnumerable<int> GetOverlappingActiveStatements(SyntaxNode declaration, ImmutableArray<UnmappedActiveStatement> statements) { var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (envelope == default) { yield break; } var range = ActiveStatementsMap.GetSpansStartingInSpan( envelope.Start, envelope.End, statements, startPositionComparer: (x, y) => x.UnmappedSpan.Start.CompareTo(y)); for (var i = range.Start.Value; i < range.End.Value; i++) { if (!hole.Contains(statements[i].UnmappedSpan.Start)) { yield return i; } } } protected static bool HasParentEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, Edit<SyntaxNode> edit) { SyntaxNode node; switch (edit.Kind) { case EditKind.Insert: node = edit.NewNode; break; case EditKind.Delete: node = edit.OldNode; break; default: return false; } return HasEdit(editMap, node.Parent, edit.Kind); } protected static bool HasEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, SyntaxNode? node, EditKind editKind) { return node is object && editMap.TryGetValue(node, out var parentEdit) && parentEdit == editKind; } #endregion #region Rude Edits around Active Statement protected void AddAroundActiveStatementRudeDiagnostic(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode? oldNode, SyntaxNode? newNode, TextSpan newActiveStatementSpan) { if (oldNode == null) { RoslynDebug.Assert(newNode != null); AddRudeInsertAroundActiveStatement(diagnostics, newNode); } else if (newNode == null) { RoslynDebug.Assert(oldNode != null); AddRudeDeleteAroundActiveStatement(diagnostics, oldNode, newActiveStatementSpan); } else { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } protected void AddRudeUpdateAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode, EditKind.Update) })); } protected void AddRudeInsertAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, new[] { GetDisplayName(newNode, EditKind.Insert) })); } protected void AddRudeDeleteAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, TextSpan newActiveStatementSpan) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeleteAroundActiveStatement, newActiveStatementSpan, oldNode, new[] { GetDisplayName(oldNode, EditKind.Delete) })); } protected void ReportUnmatchedStatements<TSyntaxNode>( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Func<SyntaxNode, bool> nodeSelector, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, Func<TSyntaxNode, TSyntaxNode, bool> areEquivalent, Func<TSyntaxNode, TSyntaxNode, bool>? areSimilar) where TSyntaxNode : SyntaxNode { var newNodes = GetAncestors(GetEncompassingAncestor(match.NewRoot), newActiveStatement, nodeSelector); if (newNodes == null) { return; } var oldNodes = GetAncestors(GetEncompassingAncestor(match.OldRoot), oldActiveStatement, nodeSelector); int matchCount; if (oldNodes != null) { matchCount = MatchNodes(oldNodes, newNodes, diagnostics: null, match: match, comparer: areEquivalent); // Do another pass over the nodes to improve error messages. if (areSimilar != null && matchCount < Math.Min(oldNodes.Count, newNodes.Count)) { matchCount += MatchNodes(oldNodes, newNodes, diagnostics: diagnostics, match: null, comparer: areSimilar); } } else { matchCount = 0; } if (matchCount < newNodes.Count) { ReportRudeEditsAndInserts(oldNodes, newNodes, diagnostics); } } private void ReportRudeEditsAndInserts(List<SyntaxNode?>? oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics) { var oldNodeCount = (oldNodes != null) ? oldNodes.Count : 0; for (var i = 0; i < newNodes.Count; i++) { var newNode = newNodes[i]; if (newNode != null) { // Any difference can be expressed as insert, delete & insert, edit, or move & edit. // Heuristic: If the nesting levels of the old and new nodes are the same we report an edit. // Otherwise we report an insert. if (i < oldNodeCount && oldNodes![i] != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } else { AddRudeInsertAroundActiveStatement(diagnostics, newNode); } } } } private int MatchNodes<TSyntaxNode>( List<SyntaxNode?> oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic>? diagnostics, Match<SyntaxNode>? match, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { var matchCount = 0; var oldIndex = 0; for (var newIndex = 0; newIndex < newNodes.Count; newIndex++) { var newNode = newNodes[newIndex]; if (newNode == null) { continue; } SyntaxNode? oldNode; while (oldIndex < oldNodes.Count) { oldNode = oldNodes[oldIndex]; if (oldNode != null) { break; } // node has already been matched with a previous new node: oldIndex++; } if (oldIndex == oldNodes.Count) { break; } var i = -1; if (match == null) { i = IndexOfEquivalent(newNode, oldNodes, oldIndex, comparer); } else if (match.TryGetOldNode(newNode, out var partner) && comparer((TSyntaxNode)partner, (TSyntaxNode)newNode)) { i = oldNodes.IndexOf(partner, oldIndex); } if (i >= 0) { // we have an update or an exact match: oldNodes[i] = null; newNodes[newIndex] = null; matchCount++; if (diagnostics != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } } return matchCount; } private static int IndexOfEquivalent<TSyntaxNode>(SyntaxNode newNode, List<SyntaxNode?> oldNodes, int startIndex, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { for (var i = startIndex; i < oldNodes.Count; i++) { var oldNode = oldNodes[i]; if (oldNode != null && comparer((TSyntaxNode)oldNode, (TSyntaxNode)newNode)) { return i; } } return -1; } private static List<SyntaxNode?>? GetAncestors(SyntaxNode? root, SyntaxNode node, Func<SyntaxNode, bool> nodeSelector) { List<SyntaxNode?>? list = null; var current = node; while (current is object && current != root) { if (nodeSelector(current)) { list ??= new List<SyntaxNode?>(); list.Add(current); } current = current.Parent; } list?.Reverse(); return list; } #endregion #region Trivia Analysis /// <summary> /// Top-level edit script does not contain edits for a member if only trivia changed in its body. /// It also does not reflect changes in line mapping directives. /// Members that are unchanged but their location in the file changes are not considered updated. /// This method calculates line and trivia edits for all these cases. /// /// The resulting line edits are grouped by mapped document path and sorted by <see cref="SourceLineUpdate.OldLine"/> in each group. /// </summary> private void AnalyzeTrivia( Match<SyntaxNode> topMatch, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, [Out] ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)> triviaEdits, [Out] ArrayBuilder<SequencePointUpdates> lineEdits, CancellationToken cancellationToken) { var oldTree = topMatch.OldRoot.SyntaxTree; var newTree = topMatch.NewRoot.SyntaxTree; // note: range [oldStartLine, oldEndLine] is end-inclusive using var _ = ArrayBuilder<(string filePath, int oldStartLine, int oldEndLine, int delta, SyntaxNode oldNode, SyntaxNode newNode)>.GetInstance(out var segments); foreach (var (oldNode, newNode) in topMatch.Matches) { cancellationToken.ThrowIfCancellationRequested(); if (editMap.ContainsKey(newNode)) { // Updated or inserted members will be (re)generated and don't need line edits. Debug.Assert(editMap[newNode] is EditKind.Update or EditKind.Insert); continue; } var newTokens = TryGetActiveTokens(newNode); if (newTokens == null) { continue; } // A (rude) edit could have been made that changes whether the node may contain active statements, // so although the nodes match they might not have the same active tokens. // E.g. field declaration changed to const field declaration. var oldTokens = TryGetActiveTokens(oldNode); if (oldTokens == null) { continue; } var newTokensEnum = newTokens.GetEnumerator(); var oldTokensEnum = oldTokens.GetEnumerator(); // We enumerate tokens of the body and split them into segments. // Each segment has sequence points mapped to the same file and also all lines the segment covers map to the same line delta. // The first token of a segment must be the first token that starts on the line. If the first segment token was in the middle line // the previous token on the same line would have different line delta and we wouldn't be able to map both of them at the same time. // All segments are included in the segments list regardless of their line delta (even when it's 0 - i.e. the lines did not change). // This is necessary as we need to detect collisions of multiple segments with different deltas later on. var lastNewToken = default(SyntaxToken); var lastOldStartLine = -1; var lastOldFilePath = (string?)null; var requiresUpdate = false; var firstSegmentIndex = segments.Count; var currentSegment = (path: (string?)null, oldStartLine: 0, delta: 0, firstOldNode: (SyntaxNode?)null, firstNewNode: (SyntaxNode?)null); var rudeEditSpan = default(TextSpan); // Check if the breakpoint span that covers the first node of the segment can be translated from the old to the new by adding a line delta. // If not we need to recompile the containing member since we are not able to produce line update for it. // The first node of the segment can be the first node on its line but the breakpoint span might start on the previous line. bool IsCurrentSegmentBreakpointSpanMappable() { var oldNode = currentSegment.firstOldNode; var newNode = currentSegment.firstNewNode; Contract.ThrowIfNull(oldNode); Contract.ThrowIfNull(newNode); // Some nodes (e.g. const local declaration) may not be covered by a breakpoint span. if (!TryGetEnclosingBreakpointSpan(oldNode, oldNode.SpanStart, out var oldBreakpointSpan) || !TryGetEnclosingBreakpointSpan(newNode, newNode.SpanStart, out var newBreakpointSpan)) { return true; } var oldMappedBreakpointSpan = (SourceFileSpan)oldTree.GetMappedLineSpan(oldBreakpointSpan, cancellationToken); var newMappedBreakpointSpan = (SourceFileSpan)newTree.GetMappedLineSpan(newBreakpointSpan, cancellationToken); if (oldMappedBreakpointSpan.AddLineDelta(currentSegment.delta) == newMappedBreakpointSpan) { return true; } rudeEditSpan = newBreakpointSpan; return false; } void AddCurrentSegment() { Debug.Assert(currentSegment.path != null); Debug.Assert(lastOldStartLine >= 0); // segment it ends on the line where the previous token starts (lastOldStartLine) segments.Add((currentSegment.path, currentSegment.oldStartLine, lastOldStartLine, currentSegment.delta, oldNode, newNode)); } bool oldHasToken; bool newHasToken; while (true) { oldHasToken = oldTokensEnum.MoveNext(); newHasToken = newTokensEnum.MoveNext(); // no update edit => tokens must match: Debug.Assert(oldHasToken == newHasToken); if (!oldHasToken) { if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; } else { // add last segment of the method body: AddCurrentSegment(); } break; } var oldSpan = oldTokensEnum.Current.Span; var newSpan = newTokensEnum.Current.Span; var oldMappedSpan = oldTree.GetMappedLineSpan(oldSpan, cancellationToken); var newMappedSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); var oldStartLine = oldMappedSpan.Span.Start.Line; var newStartLine = newMappedSpan.Span.Start.Line; var lineDelta = newStartLine - oldStartLine; // If any tokens in the method change their mapped column or mapped path the method must be recompiled // since the Debugger/SymReader does not support these updates. if (oldMappedSpan.Span.Start.Character != newMappedSpan.Span.Start.Character) { requiresUpdate = true; break; } if (currentSegment.path != oldMappedSpan.Path || currentSegment.delta != lineDelta) { // end of segment: if (currentSegment.path != null) { // Previous token start line is the same as this token start line, but the previous token line delta is not the same. // We can't therefore map the old start line to a new one using line delta since that would affect both tokens the same. if (lastOldStartLine == oldStartLine && string.Equals(lastOldFilePath, oldMappedSpan.Path)) { requiresUpdate = true; break; } if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; break; } // add current segment: AddCurrentSegment(); } // start new segment: currentSegment = (oldMappedSpan.Path, oldStartLine, lineDelta, oldTokensEnum.Current.Parent, newTokensEnum.Current.Parent); } lastNewToken = newTokensEnum.Current; lastOldStartLine = oldStartLine; lastOldFilePath = oldMappedSpan.Path; } // All tokens of a member body have been processed now. if (requiresUpdate) { // report the rude edit for the span of tokens that forced recompilation: if (rudeEditSpan.IsEmpty) { rudeEditSpan = TextSpan.FromBounds( lastNewToken.HasTrailingTrivia ? lastNewToken.Span.End : newTokensEnum.Current.FullSpan.Start, newTokensEnum.Current.SpanStart); } triviaEdits.Add((oldNode, newNode, rudeEditSpan)); // remove all segments added for the current member body: segments.Count = firstSegmentIndex; } } if (segments.Count == 0) { return; } // sort segments by file and then by start line: segments.Sort((x, y) => { var result = string.CompareOrdinal(x.filePath, y.filePath); return (result != 0) ? result : x.oldStartLine.CompareTo(y.oldStartLine); }); // Calculate line updates based on segments. // If two segments with different line deltas overlap we need to recompile all overlapping members except for the first one. // The debugger does not apply line deltas to recompiled methods and hence we can chose to recompile either of the overlapping segments // and apply line delta to the others. // // The line delta is applied to the start line of a sequence point. If start lines of two sequence points mapped to the same location // before the delta is applied then they will point to the same location after the delta is applied. But that wouldn't be correct // if two different mappings required applying different deltas and thus different locations. // This also applies when two methods are on the same line in the old version and they move by different deltas. using var _1 = ArrayBuilder<SourceLineUpdate>.GetInstance(out var documentLineEdits); var currentDocumentPath = segments[0].filePath; var previousOldEndLine = -1; var previousLineDelta = 0; foreach (var segment in segments) { if (segment.filePath != currentDocumentPath) { // store results for the previous document: if (documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutableAndClear())); } // switch to the next document: currentDocumentPath = segment.filePath; previousOldEndLine = -1; previousLineDelta = 0; } else if (segment.oldStartLine <= previousOldEndLine && segment.delta != previousLineDelta) { // The segment overlaps the previous one that has a different line delta. We need to recompile the method. // The debugger filters out line deltas that correspond to recompiled methods so we don't need to. triviaEdits.Add((segment.oldNode, segment.newNode, segment.newNode.Span)); continue; } // If the segment being added does not start on the line immediately following the previous segment end line // we need to insert another line update that resets the delta to 0 for the lines following the end line. if (documentLineEdits.Count > 0 && segment.oldStartLine > previousOldEndLine + 1) { Debug.Assert(previousOldEndLine >= 0); documentLineEdits.Add(CreateZeroDeltaSourceLineUpdate(previousOldEndLine + 1)); previousLineDelta = 0; } // Skip segment that doesn't change line numbers - the line edit would have no effect. // It was only added to facilitate detection of overlap with other segments. // Also skip the segment if the last line update has the same line delta as // consecutive same line deltas has the same effect as a single one. if (segment.delta != 0 && segment.delta != previousLineDelta) { documentLineEdits.Add(new SourceLineUpdate(segment.oldStartLine, segment.oldStartLine + segment.delta)); } previousOldEndLine = segment.oldEndLine; previousLineDelta = segment.delta; } if (currentDocumentPath != null && documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutable())); } } // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. internal static SourceLineUpdate CreateZeroDeltaSourceLineUpdate(int line) { var result = new SourceLineUpdate(); // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. unsafe { Unsafe.Write(&result, ((long)line << 32) | (long)line); } return result; } #endregion #region Semantic Analysis private sealed class AssemblyEqualityComparer : IEqualityComparer<IAssemblySymbol?> { public static readonly IEqualityComparer<IAssemblySymbol?> Instance = new AssemblyEqualityComparer(); public bool Equals(IAssemblySymbol? x, IAssemblySymbol? y) { // Types defined in old source assembly need to be treated as equivalent to types in the new source assembly, // provided that they only differ in their containing assemblies. // // The old source symbol has the same identity as the new one. // Two distinct assembly symbols that are referenced by the compilations have to have distinct identities. // If the compilation has two metadata references whose identities unify the compiler de-dups them and only creates // a single PE symbol. Thus comparing assemblies by identity partitions them so that each partition // contains assemblies that originated from the same Gen0 assembly. return Equals(x?.Identity, y?.Identity); } public int GetHashCode(IAssemblySymbol? obj) => obj?.Identity.GetHashCode() ?? 0; } // Ignore tuple element changes, nullability and dynamic. These type changes do not affect runtime type. // They only affect custom attributes emitted on the members - all runtimes are expected to accept // custom attribute updates in metadata deltas, even if they do not have any observable effect. private static readonly SymbolEquivalenceComparer s_runtimeSymbolEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: false, ignoreNullableAnnotations: true); private static readonly SymbolEquivalenceComparer s_exactSymbolEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: true, ignoreNullableAnnotations: false); protected static bool SymbolsEquivalent(ISymbol oldSymbol, ISymbol newSymbol) => s_exactSymbolEqualityComparer.Equals(oldSymbol, newSymbol); protected static bool SignaturesEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType) => ParameterTypesEquivalent(oldParameters, newParameters, exact: false) && s_runtimeSymbolEqualityComparer.Equals(oldReturnType, newReturnType); // TODO: should check ref, ref readonly, custom mods protected static bool ParameterTypesEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ImmutableArray<IParameterSymbol> newParameters, bool exact) => oldParameters.SequenceEqual(newParameters, exact, (oldParameter, newParameter, exact) => ParameterTypesEquivalent(oldParameter, newParameter, exact)); protected static bool CustomModifiersEquivalent(CustomModifier oldModifier, CustomModifier newModifier, bool exact) => oldModifier.IsOptional == newModifier.IsOptional && TypesEquivalent(oldModifier.Modifier, newModifier.Modifier, exact); protected static bool CustomModifiersEquivalent(ImmutableArray<CustomModifier> oldModifiers, ImmutableArray<CustomModifier> newModifiers, bool exact) => oldModifiers.SequenceEqual(newModifiers, exact, (x, y, exact) => CustomModifiersEquivalent(x, y, exact)); protected static bool ReturnTypesEquivalent(IMethodSymbol oldMethod, IMethodSymbol newMethod, bool exact) => oldMethod.ReturnsByRef == newMethod.ReturnsByRef && oldMethod.ReturnsByRefReadonly == newMethod.ReturnsByRefReadonly && CustomModifiersEquivalent(oldMethod.ReturnTypeCustomModifiers, newMethod.ReturnTypeCustomModifiers, exact) && CustomModifiersEquivalent(oldMethod.RefCustomModifiers, newMethod.RefCustomModifiers, exact) && TypesEquivalent(oldMethod.ReturnType, newMethod.ReturnType, exact); protected static bool ReturnTypesEquivalent(IPropertySymbol oldProperty, IPropertySymbol newProperty, bool exact) => oldProperty.ReturnsByRef == newProperty.ReturnsByRef && oldProperty.ReturnsByRefReadonly == newProperty.ReturnsByRefReadonly && CustomModifiersEquivalent(oldProperty.TypeCustomModifiers, newProperty.TypeCustomModifiers, exact) && CustomModifiersEquivalent(oldProperty.RefCustomModifiers, newProperty.RefCustomModifiers, exact) && TypesEquivalent(oldProperty.Type, newProperty.Type, exact); protected static bool ReturnTypesEquivalent(IEventSymbol oldEvent, IEventSymbol newEvent, bool exact) => TypesEquivalent(oldEvent.Type, newEvent.Type, exact); // Note: SignatureTypeEquivalenceComparer compares dynamic and object the same. protected static bool TypesEquivalent(ITypeSymbol? oldType, ITypeSymbol? newType, bool exact) => (exact ? s_exactSymbolEqualityComparer : (IEqualityComparer<ITypeSymbol?>)s_runtimeSymbolEqualityComparer.SignatureTypeEquivalenceComparer).Equals(oldType, newType); protected static bool TypesEquivalent<T>(ImmutableArray<T> oldTypes, ImmutableArray<T> newTypes, bool exact) where T : ITypeSymbol => oldTypes.SequenceEqual(newTypes, exact, (x, y, exact) => TypesEquivalent(x, y, exact)); protected static bool ParameterTypesEquivalent(IParameterSymbol oldParameter, IParameterSymbol newParameter, bool exact) => (exact ? s_exactSymbolEqualityComparer : s_runtimeSymbolEqualityComparer).ParameterEquivalenceComparer.Equals(oldParameter, newParameter); protected static bool TypeParameterConstraintsEquivalent(ITypeParameterSymbol oldParameter, ITypeParameterSymbol newParameter, bool exact) => TypesEquivalent(oldParameter.ConstraintTypes, newParameter.ConstraintTypes, exact) && oldParameter.HasReferenceTypeConstraint == newParameter.HasReferenceTypeConstraint && oldParameter.HasValueTypeConstraint == newParameter.HasValueTypeConstraint && oldParameter.HasConstructorConstraint == newParameter.HasConstructorConstraint && oldParameter.HasNotNullConstraint == newParameter.HasNotNullConstraint && oldParameter.HasUnmanagedTypeConstraint == newParameter.HasUnmanagedTypeConstraint && oldParameter.Variance == newParameter.Variance; protected static bool TypeParametersEquivalent(ImmutableArray<ITypeParameterSymbol> oldParameters, ImmutableArray<ITypeParameterSymbol> newParameters, bool exact) => oldParameters.SequenceEqual(newParameters, exact, (oldParameter, newParameter, exact) => oldParameter.Name == newParameter.Name && TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact)); protected static bool BaseTypesEquivalent(INamedTypeSymbol oldType, INamedTypeSymbol newType, bool exact) => TypesEquivalent(oldType.BaseType, newType.BaseType, exact) && TypesEquivalent(oldType.AllInterfaces, newType.AllInterfaces, exact); protected static bool MemberSignaturesEquivalent( ISymbol? oldMember, ISymbol? newMember, Func<ImmutableArray<IParameterSymbol>, ITypeSymbol, ImmutableArray<IParameterSymbol>, ITypeSymbol, bool>? signatureComparer = null) { if (oldMember == newMember) { return true; } if (oldMember == null || newMember == null || oldMember.Kind != newMember.Kind) { return false; } signatureComparer ??= SignaturesEquivalent; switch (oldMember.Kind) { case SymbolKind.Field: var oldField = (IFieldSymbol)oldMember; var newField = (IFieldSymbol)newMember; return signatureComparer(ImmutableArray<IParameterSymbol>.Empty, oldField.Type, ImmutableArray<IParameterSymbol>.Empty, newField.Type); case SymbolKind.Property: var oldProperty = (IPropertySymbol)oldMember; var newProperty = (IPropertySymbol)newMember; return signatureComparer(oldProperty.Parameters, oldProperty.Type, newProperty.Parameters, newProperty.Type); case SymbolKind.Method: var oldMethod = (IMethodSymbol)oldMember; var newMethod = (IMethodSymbol)newMember; return signatureComparer(oldMethod.Parameters, oldMethod.ReturnType, newMethod.Parameters, newMethod.ReturnType); default: throw ExceptionUtilities.UnexpectedValue(oldMember.Kind); } } private readonly struct ConstructorEdit { public readonly INamedTypeSymbol OldType; /// <summary> /// Contains syntax maps for all changed data member initializers or constructor declarations (of constructors emitting initializers) /// in the currently analyzed document. The key is the declaration of the member. /// </summary> public readonly Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> ChangedDeclarations; public ConstructorEdit(INamedTypeSymbol oldType) { OldType = oldType; ChangedDeclarations = new Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?>(); } } private async Task<ImmutableArray<SemanticEditInfo>> AnalyzeSemanticsAsync( EditScript<SyntaxNode> editScript, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, IReadOnlyList<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)> triviaEdits, Project oldProject, Document? oldDocument, Document newDocument, SourceText newText, ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<ActiveStatement>.Builder newActiveStatements, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, EditAndContinueCapabilities capabilities, bool inBreakState, CancellationToken cancellationToken) { Debug.Assert(inBreakState || newActiveStatementSpans.IsEmpty); if (editScript.Edits.Length == 0 && triviaEdits.Count == 0) { return ImmutableArray<SemanticEditInfo>.Empty; } // { new type -> constructor update } PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits = null; PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits = null; var oldModel = (oldDocument != null) ? await oldDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false) : null; var newModel = await newDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldCompilation = oldModel?.Compilation ?? await oldProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = newModel.Compilation; using var _1 = PooledHashSet<ISymbol>.GetInstance(out var processedSymbols); using var _2 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var semanticEdits); try { INamedTypeSymbol? lazyLayoutAttribute = null; foreach (var edit in editScript.Edits) { cancellationToken.ThrowIfCancellationRequested(); if (edit.Kind == EditKind.Move) { // Move is either a Rude Edit and already reported in syntax analysis, or has no semantic effect. // For example, in VB we allow move from field multi-declaration. // "Dim a, b As Integer" -> "Dim a As Integer" (update) and "Dim b As Integer" (move) continue; } if (edit.Kind == EditKind.Reorder) { // Currently we don't do any semantic checks for reordering // and we don't need to report them to the compiler either. // Consider: Currently symbol ordering changes are not reflected in metadata (Reflection will report original order). // Consider: Reordering of fields is not allowed since it changes the layout of the type. // This ordering should however not matter unless the type has explicit layout so we might want to allow it. // We do not check changes to the order if they occur across multiple documents (the containing type is partial). Debug.Assert(!IsDeclarationWithInitializer(edit.OldNode) && !IsDeclarationWithInitializer(edit.NewNode)); continue; } foreach (var symbolEdits in GetSymbolEdits(edit.Kind, edit.OldNode, edit.NewNode, oldModel, newModel, editMap, cancellationToken)) { Func<SyntaxNode, SyntaxNode?>? syntaxMap; SemanticEditKind editKind; var (oldSymbol, newSymbol, syntacticEditKind) = symbolEdits; var symbol = newSymbol ?? oldSymbol; Contract.ThrowIfNull(symbol); if (!processedSymbols.Add(symbol)) { continue; } var symbolKey = SymbolKey.Create(symbol, cancellationToken); // Ignore ambiguous resolution result - it may happen if there are semantic errors in the compilation. oldSymbol ??= symbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; newSymbol ??= symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, edit.OldNode, edit.NewNode); // The syntax change implies an update of the associated symbol but the old/new symbol does not actually exist. // Treat the edit as Insert/Delete. This may happen e.g. when all C# global statements are removed, the first one is added or they are moved to another file. if (syntacticEditKind == EditKind.Update) { if (oldSymbol == null || oldDeclaration != null && oldDeclaration.SyntaxTree != oldModel?.SyntaxTree) { syntacticEditKind = EditKind.Insert; } else if (newSymbol == null || newDeclaration != null && newDeclaration.SyntaxTree != newModel.SyntaxTree) { syntacticEditKind = EditKind.Delete; } } if (!inBreakState) { // Delete/insert/update edit of a member of a reloadable type (including nested types) results in Replace edit of the containing type. // If a Delete edit is part of delete-insert operation (member moved to a different partial type declaration or to a different file) // skip producing Replace semantic edit for this Delete edit as one will be reported by the corresponding Insert edit. var oldContainingType = oldSymbol?.ContainingType; var newContainingType = newSymbol?.ContainingType; var containingType = newContainingType ?? oldContainingType; if (containingType != null && (syntacticEditKind != EditKind.Delete || newSymbol == null)) { var containingTypeSymbolKey = SymbolKey.Create(containingType, cancellationToken); oldContainingType ??= (INamedTypeSymbol?)containingTypeSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; newContainingType ??= (INamedTypeSymbol?)containingTypeSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (oldContainingType != null && newContainingType != null && IsReloadable(oldContainingType)) { if (processedSymbols.Add(newContainingType)) { if (capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, containingTypeSymbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldContainingType, newContainingType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newContainingType, newDeclaration, cancellationToken); } } continue; } } var oldType = oldSymbol as INamedTypeSymbol; var newType = newSymbol as INamedTypeSymbol; // Deleting a reloadable type is a rude edit, reported the same as for non-reloadable. // Adding a reloadable type is a standard type addition (TODO: unless added to a reloadable type?). // Making reloadable attribute non-reloadable results in a new version of the type that is // not reloadable but does not update the old version in-place. if (syntacticEditKind != EditKind.Delete && oldType != null && newType != null && IsReloadable(oldType)) { if (symbol == newType || processedSymbols.Add(newType)) { if (oldType.Name != newType.Name) { // https://github.com/dotnet/roslyn/issues/54886 ReportUpdateRudeEdit(diagnostics, RudeEditKind.Renamed, newType, newDeclaration, cancellationToken); } else if (oldType.Arity != newType.Arity) { // https://github.com/dotnet/roslyn/issues/54881 ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingTypeParameters, newType, newDeclaration, cancellationToken); } else if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newType, newDeclaration, cancellationToken); } else { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, symbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldType, newType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } continue; } } switch (syntacticEditKind) { case EditKind.Delete: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(oldDeclaration); var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); var hasActiveStatement = activeStatementIndices.Any(); // TODO: if the member isn't a field/property we should return empty span. // We need to adjust the tracking span design and UpdateUneditedSpans to account for such empty spans. if (hasActiveStatement) { var newSpan = IsDeclarationWithInitializer(oldDeclaration) ? GetDeletedNodeActiveSpan(editScript.Match.Matches, oldDeclaration) : GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); foreach (var index in activeStatementIndices) { Debug.Assert(newActiveStatements[index] is null); newActiveStatements[index] = GetActiveStatementWithSpan(oldActiveStatements[index], editScript.Match.NewRoot.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[index] = ImmutableArray<SourceFileSpan>.Empty; } } syntaxMap = null; editKind = SemanticEditKind.Delete; // Check if the declaration has been moved from one document to another. if (newSymbol != null && !(newSymbol is IMethodSymbol newMethod && newMethod.IsPartialDefinition)) { // Symbol has actually not been deleted but rather moved to another document, another partial type declaration // or replaced with an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) // Report rude edit if the deleted code contains active statements. // TODO (https://github.com/dotnet/roslyn/issues/51177): // Only report rude edit when replacing member with an implicit one if it has an active statement. // We might be able to support moving active members but we would need to // 1) Move AnalyzeChangedMemberBody from Insert to Delete // 2) Handle active statements that moved to a different document in ActiveStatementTrackingService // 3) The debugger's ManagedActiveStatementUpdate might need another field indicating the source file path. if (hasActiveStatement) { ReportDeletedMemberRudeEdit(diagnostics, oldSymbol, newCompilation, RudeEditKind.DeleteActiveStatement, cancellationToken); continue; } if (!newSymbol.IsImplicitlyDeclared) { // Ignore the delete. The new symbol is explicitly declared and thus there will be an insert edit that will issue a semantic update. // Note that this could also be the case for deleting properties of records, but they will be handled when we see // their accessors below. continue; } if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(oldDeclaration, newSymbol.ContainingType, out var isFirst)) { // Defer a constructor edit to cover the property initializer changing DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // If there was no body deleted then we are done since the compiler generated property also has no body if (TryGetDeclarationBody(oldDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. // We only need to do this once though. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newSymbol.ContainingType, semanticEdits, cancellationToken); } } // If a constructor is deleted and replaced by an implicit one the update needs to aggregate updates to all data member initializers, // or if a property is deleted that is part of a records primary constructor, which is effectivelly moving from an explicit to implicit // initializer. if (IsConstructorWithMemberInitializers(oldDeclaration)) { processedSymbols.Remove(oldSymbol); DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); continue; } // there is no insert edit for an implicit declaration, therefore we need to issue an update: editKind = SemanticEditKind.Update; } else { var diagnosticSpan = GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); // If we got here for a global statement then the actual edit is a delete of the synthesized Main method if (IsGlobalMain(oldSymbol)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.Delete, diagnosticSpan, edit.OldNode, new[] { GetDisplayName(edit.OldNode, EditKind.Delete) })); continue; } // If the associated member declaration (accessor -> property/indexer/event, parameter -> method) has also been deleted skip // the delete of the symbol as it will be deleted by the delete of the associated member. // // Associated member declarations must be in the same document as the symbol, so we don't need to resolve their symbol. // In some cases the symbol even can't be resolved unambiguously. Consider e.g. resolving a method with its parameter deleted - // we wouldn't know which overload to resolve to. if (TryGetAssociatedMemberDeclaration(oldDeclaration, out var oldAssociatedMemberDeclaration)) { if (HasEdit(editMap, oldAssociatedMemberDeclaration, EditKind.Delete)) { continue; } } else if (oldSymbol.ContainingType != null) { // Check if the symbol being deleted is a member of a type that's also being deleted. // If so, skip the member deletion and only report the containing symbol deletion. var containingSymbolKey = SymbolKey.Create(oldSymbol.ContainingType, cancellationToken); var newContainingSymbol = containingSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContainingSymbol == null) { continue; } } // deleting symbol is not allowed diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, diagnosticSpan, oldDeclaration, new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldDeclaration, EditKind.Delete), oldSymbol.ToDisplayString(diagnosticSpan.IsEmpty ? s_fullyQualifiedMemberDisplayFormat : s_unqualifiedMemberDisplayFormat)) })); continue; } } break; case EditKind.Insert: { Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(newDeclaration); syntaxMap = null; editKind = SemanticEditKind.Insert; INamedTypeSymbol? oldContainingType; var newContainingType = newSymbol.ContainingType; // Check if the declaration has been moved from one document to another. if (oldSymbol != null) { // Symbol has actually not been inserted but rather moved between documents or partial type declarations, // or is replacing an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) oldContainingType = oldSymbol.ContainingType; if (oldSymbol.IsImplicitlyDeclared) { // If a user explicitly implements a member of a record then we want to issue an update, not an insert. if (oldSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfNull(oldDeclaration); ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol, cancellationToken); if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(newDeclaration, newContainingType, out var isFirst)) { // If there is no body declared we can skip it entirely because for a property accessor // it matches what the compiler would have previously implicitly implemented. if (TryGetDeclarationBody(newDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. Only need to do it once. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits, cancellationToken); } } editKind = SemanticEditKind.Update; } } else if (oldSymbol.DeclaringSyntaxReferences.Length == 1 && newSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfNull(oldDeclaration); // Handles partial methods and explicitly implemented properties that implement positional parameters of records // We ignore partial method definition parts when processing edits (GetSymbolForEdit). // The only declaration in compilation without syntax errors that can have multiple declaring references is a type declaration. // We can therefore ignore any symbols that have more than one declaration. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // Compare the old declaration syntax of the symbol with its new declaration and report rude edits // if it changed in any way that's not allowed. ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol, cancellationToken); var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { // The old symbol's declaration syntax may be located in a different document than the old version of the current document. var oldSyntaxDocument = oldProject.Solution.GetRequiredDocument(oldDeclaration.SyntaxTree); var oldSyntaxModel = await oldSyntaxDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldSyntaxText = await oldSyntaxDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var newBody = TryGetDeclarationBody(newDeclaration); // Skip analysis of active statements. We already report rude edit for removal of code containing // active statements in the old declaration and don't currently support moving active statements. AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldSyntaxModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements: ImmutableArray<UnmappedActiveStatement>.Empty, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, capabilities: capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isNewConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration); var isRecordPrimaryConstructorParameter = IsRecordPrimaryConstructorParameter(oldDeclaration); if (isNewConstructorWithMemberInitializers || isDeclarationWithInitializer || isRecordPrimaryConstructorParameter) { if (isNewConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isDeclarationWithInitializer) { AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } DeferConstructorEdit(oldSymbol.ContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } editKind = SemanticEditKind.Update; } else { editKind = SemanticEditKind.Update; } } else if (TryGetAssociatedMemberDeclaration(newDeclaration, out var newAssociatedMemberDeclaration) && HasEdit(editMap, newAssociatedMemberDeclaration, EditKind.Insert)) { // If the symbol is an accessor and the containing property/indexer/event declaration has also been inserted skip // the insert of the accessor as it will be inserted by the property/indexer/event. continue; } else if (newSymbol is IParameterSymbol || newSymbol is ITypeParameterSymbol) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); continue; } else if (newContainingType != null && !IsGlobalMain(newSymbol)) { // The edit actually adds a new symbol into an existing or a new type. var containingSymbolKey = SymbolKey.Create(newContainingType, cancellationToken); oldContainingType = containingSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol as INamedTypeSymbol; if (oldContainingType != null && !CanAddNewMember(newSymbol, capabilities)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } // Check rude edits for each member even if it is inserted into a new type. ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: oldContainingType != null); if (oldContainingType == null) { // Insertion of a new symbol into a new type. // We'll produce a single insert edit for the entire type. continue; } // Report rude edits for changes to data member changes of a type with an explicit layout. // We disallow moving a data member of a partial type with explicit layout even when it actually does not change the layout. // We could compare the exact order of the members but the scenario is unlikely to occur. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // If a property or field is added to a record then the implicit constructors change, // and we need to mark a number of other synthesized members as having changed. if (newSymbol is IPropertySymbol or IFieldSymbol && newContainingType.IsRecord) { DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits, cancellationToken); } } else { // adds a new top-level type, or a global statement where none existed before, which is // therefore inserting the <Program>$ type Contract.ThrowIfFalse(newSymbol is INamedTypeSymbol || IsGlobalMain(newSymbol)); if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } oldContainingType = null; ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: false); } var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); if (isConstructorWithMemberInitializers || IsDeclarationWithInitializer(newDeclaration)) { Contract.ThrowIfNull(newContainingType); Contract.ThrowIfNull(oldContainingType); // TODO (bug https://github.com/dotnet/roslyn/issues/2504) if (isConstructorWithMemberInitializers && editKind == SemanticEditKind.Insert && IsPartial(newContainingType) && HasMemberInitializerContainingLambda(oldContainingType, newSymbol.IsStatic, cancellationToken)) { // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); break; } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isConstructorWithMemberInitializers || editKind == SemanticEditKind.Update) { // Don't add a separate semantic edit. // Edits of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } // A semantic edit to create the field/property is gonna be added. Contract.ThrowIfFalse(editKind == SemanticEditKind.Insert); } } break; case EditKind.Update: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(newSymbol); editKind = SemanticEditKind.Update; syntaxMap = null; // Partial type declarations and their type parameters. if (oldSymbol.DeclaringSyntaxReferences.Length != 1 && newSymbol.DeclaringSyntaxReferences.Length != 1) { break; } Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { var newBody = TryGetDeclarationBody(newDeclaration); AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements, newActiveStatementSpans, capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration); if (isConstructorWithMemberInitializers || isDeclarationWithInitializer) { if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isDeclarationWithInitializer) { AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } } break; default: throw ExceptionUtilities.UnexpectedValue(edit.Kind); } Contract.ThrowIfFalse(editKind is SemanticEditKind.Update or SemanticEditKind.Insert); if (editKind == SemanticEditKind.Update) { Contract.ThrowIfNull(oldSymbol); AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); if (newSymbol is INamedTypeSymbol or IFieldSymbol or IPropertySymbol or IEventSymbol or IParameterSymbol or ITypeParameterSymbol) { continue; } } semanticEdits.Add(new SemanticEditInfo(editKind, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } foreach (var (oldEditNode, newEditNode, diagnosticSpan) in triviaEdits) { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); foreach (var (oldSymbol, newSymbol, editKind) in GetSymbolEdits(EditKind.Update, oldEditNode, newEditNode, oldModel, newModel, editMap, cancellationToken)) { // Trivia edits are only calculated for member bodies and each member has a symbol. Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(oldSymbol); if (!processedSymbols.Add(newSymbol)) { // symbol already processed continue; } var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, oldEditNode, newEditNode); Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldContainingType = oldSymbol.ContainingType; var newContainingType = newSymbol.ContainingType; Contract.ThrowIfNull(oldContainingType); Contract.ThrowIfNull(newContainingType); if (IsReloadable(oldContainingType)) { if (processedSymbols.Add(newContainingType)) { if (capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { var containingTypeSymbolKey = SymbolKey.Create(oldContainingType, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, containingTypeSymbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldContainingType, newContainingType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newContainingType, newDeclaration, cancellationToken); } } continue; } // We need to provide syntax map to the compiler if the member is active (see member update above): var isActiveMember = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements).Any() || IsStateMachineMethod(oldDeclaration) || ContainsLambda(oldDeclaration); var syntaxMap = isActiveMember ? CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration) : null; // only trivia changed: Contract.ThrowIfFalse(IsConstructorWithMemberInitializers(oldDeclaration) == IsConstructorWithMemberInitializers(newDeclaration)); Contract.ThrowIfFalse(IsDeclarationWithInitializer(oldDeclaration) == IsDeclarationWithInitializer(newDeclaration)); var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(newDeclaration); if (isConstructorWithMemberInitializers || isDeclarationWithInitializer) { // TODO: only create syntax map if any field initializers are active/contain lambdas or this is a partial type syntaxMap ??= CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, diagnosticSpan); // updating generic methods and types if (InGenericContext(oldSymbol, out var oldIsGenericMethod)) { var rudeEdit = oldIsGenericMethod ? RudeEditKind.GenericMethodTriviaUpdate : RudeEditKind.GenericTypeTriviaUpdate; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, diagnosticSpan, newEditNode, new[] { GetDisplayName(newEditNode) })); continue; } var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } if (instanceConstructorEdits != null) { AddConstructorEdits( instanceConstructorEdits, editScript.Match, oldModel, oldCompilation, newCompilation, processedSymbols, capabilities, isStatic: false, semanticEdits, diagnostics, cancellationToken); } if (staticConstructorEdits != null) { AddConstructorEdits( staticConstructorEdits, editScript.Match, oldModel, oldCompilation, newCompilation, processedSymbols, capabilities, isStatic: true, semanticEdits, diagnostics, cancellationToken); } } finally { instanceConstructorEdits?.Free(); staticConstructorEdits?.Free(); } return semanticEdits.Distinct(SemanticEditInfoComparer.Instance).ToImmutableArray(); // If the symbol has a single declaring reference use its syntax node for further analysis. // Some syntax edits may not be directly associated with the declarations. // For example, in VB an update to AsNew clause of a multi-variable field declaration results in update to multiple symbols associated // with the variable declaration. But we need to analyse each symbol's modified identifier separately. (SyntaxNode? oldDeclaration, SyntaxNode? newDeclaration) GetSymbolDeclarationNodes(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxNode? oldNode, SyntaxNode? newNode) { return ( (oldSymbol != null && oldSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(oldSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : oldNode, (newSymbol != null && newSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(newSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : newNode); } } private static bool IsReloadable(INamedTypeSymbol type) { var current = type; while (current != null) { foreach (var attributeData in current.GetAttributes()) { // We assume that the attribute System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute, if it exists, is well formed. // If not an error will be reported during EnC delta emit. if (attributeData.AttributeClass is { Name: CreateNewOnMetadataUpdateAttributeName, ContainingNamespace: { Name: "CompilerServices", ContainingNamespace: { Name: "Runtime", ContainingNamespace: { Name: "System" } } } }) { return true; } } current = current.BaseType; } return false; } private sealed class SemanticEditInfoComparer : IEqualityComparer<SemanticEditInfo> { public static SemanticEditInfoComparer Instance = new(); private static readonly IEqualityComparer<SymbolKey> s_symbolKeyComparer = SymbolKey.GetComparer(); public bool Equals([AllowNull] SemanticEditInfo x, [AllowNull] SemanticEditInfo y) => s_symbolKeyComparer.Equals(x.Symbol, y.Symbol); public int GetHashCode([DisallowNull] SemanticEditInfo obj) => obj.Symbol.GetHashCode(); } private void ReportUpdatedSymbolDeclarationRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, out bool hasGeneratedAttributeChange, out bool hasGeneratedReturnTypeAttributeChange, out bool hasParameterRename, CancellationToken cancellationToken) { var rudeEdit = RudeEditKind.None; hasGeneratedAttributeChange = false; hasGeneratedReturnTypeAttributeChange = false; hasParameterRename = false; if (oldSymbol.Kind != newSymbol.Kind) { rudeEdit = (oldSymbol.Kind == SymbolKind.Field || newSymbol.Kind == SymbolKind.Field) ? RudeEditKind.FieldKindUpdate : RudeEditKind.Update; } else if (oldSymbol.Name != newSymbol.Name) { if (oldSymbol is IParameterSymbol && newSymbol is IParameterSymbol) { if (capabilities.HasFlag(EditAndContinueCapabilities.UpdateParameters)) { hasParameterRename = true; } else { rudeEdit = RudeEditKind.RenamingNotSupportedByRuntime; } } else { rudeEdit = RudeEditKind.Renamed; } // specialize rude edit for accessors and conversion operators: if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { if (oldMethod.AssociatedSymbol != null && newMethod.AssociatedSymbol != null) { if (oldMethod.MethodKind != newMethod.MethodKind) { rudeEdit = RudeEditKind.AccessorKindUpdate; } else { // rude edit will be reported by the associated symbol rudeEdit = RudeEditKind.None; } } else if (oldMethod.MethodKind == MethodKind.Conversion) { rudeEdit = RudeEditKind.ModifiersUpdate; } } } if (oldSymbol.DeclaredAccessibility != newSymbol.DeclaredAccessibility) { rudeEdit = RudeEditKind.ChangingAccessibility; } if (oldSymbol.IsStatic != newSymbol.IsStatic || oldSymbol.IsVirtual != newSymbol.IsVirtual || oldSymbol.IsAbstract != newSymbol.IsAbstract || oldSymbol.IsOverride != newSymbol.IsOverride || oldSymbol.IsExtern != newSymbol.IsExtern) { // Do not report for accessors as the error will be reported on their associated symbol. if (oldSymbol is not IMethodSymbol { AssociatedSymbol: not null }) { rudeEdit = RudeEditKind.ModifiersUpdate; } } if (oldSymbol is IFieldSymbol oldField && newSymbol is IFieldSymbol newField) { if (oldField.IsConst != newField.IsConst || oldField.IsReadOnly != newField.IsReadOnly || oldField.IsVolatile != newField.IsVolatile) { rudeEdit = RudeEditKind.ModifiersUpdate; } // Report rude edit for updating const fields and values of enums. // The latter is only reported whne the enum underlying type does not change to avoid cascading rude edits. if (oldField.IsConst && newField.IsConst && !Equals(oldField.ConstantValue, newField.ConstantValue) && TypesEquivalent(oldField.ContainingType.EnumUnderlyingType, newField.ContainingType.EnumUnderlyingType, exact: false)) { rudeEdit = RudeEditKind.InitializerUpdate; } if (oldField.FixedSize != newField.FixedSize) { rudeEdit = RudeEditKind.FixedSizeFieldUpdate; } AnalyzeType(oldField.Type, newField.Type, ref rudeEdit, ref hasGeneratedAttributeChange); } else if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { if (oldMethod.IsReadOnly != newMethod.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } if (oldMethod.IsInitOnly != newMethod.IsInitOnly) { rudeEdit = RudeEditKind.AccessorKindUpdate; } // Consider: Generalize to compare P/Invokes regardless of how they are defined (using attribute or Declare) if (oldMethod.MethodKind == MethodKind.DeclareMethod || newMethod.MethodKind == MethodKind.DeclareMethod) { var oldImportData = oldMethod.GetDllImportData(); var newImportData = newMethod.GetDllImportData(); if (oldImportData != null && newImportData != null) { // Declare method syntax can't change these. Debug.Assert(oldImportData.BestFitMapping == newImportData.BestFitMapping || oldImportData.CallingConvention == newImportData.CallingConvention || oldImportData.ExactSpelling == newImportData.ExactSpelling || oldImportData.SetLastError == newImportData.SetLastError || oldImportData.ThrowOnUnmappableCharacter == newImportData.ThrowOnUnmappableCharacter); if (oldImportData.ModuleName != newImportData.ModuleName) { rudeEdit = RudeEditKind.DeclareLibraryUpdate; } else if (oldImportData.EntryPointName != newImportData.EntryPointName) { rudeEdit = RudeEditKind.DeclareAliasUpdate; } else if (oldImportData.CharacterSet != newImportData.CharacterSet) { rudeEdit = RudeEditKind.ModifiersUpdate; } } else if (oldImportData is null != newImportData is null) { rudeEdit = RudeEditKind.ModifiersUpdate; } } // VB implements clause if (!oldMethod.ExplicitInterfaceImplementations.SequenceEqual(newMethod.ExplicitInterfaceImplementations, (x, y) => SymbolsEquivalent(x, y))) { rudeEdit = RudeEditKind.ImplementsClauseUpdate; } // VB handles clause if (!AreHandledEventsEqual(oldMethod, newMethod)) { rudeEdit = RudeEditKind.HandlesClauseUpdate; } // Check return type - do not report for accessors, their containing symbol will report the rude edits and attribute updates. if (rudeEdit == RudeEditKind.None && oldMethod.AssociatedSymbol == null && newMethod.AssociatedSymbol == null) { AnalyzeReturnType(oldMethod, newMethod, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } else if (oldSymbol is INamedTypeSymbol oldType && newSymbol is INamedTypeSymbol newType) { if (oldType.TypeKind != newType.TypeKind || oldType.IsRecord != newType.IsRecord) // TODO: https://github.com/dotnet/roslyn/issues/51874 { rudeEdit = RudeEditKind.TypeKindUpdate; } else if (oldType.IsRefLikeType != newType.IsRefLikeType || oldType.IsReadOnly != newType.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } if (rudeEdit == RudeEditKind.None) { AnalyzeBaseTypes(oldType, newType, ref rudeEdit, ref hasGeneratedAttributeChange); if (oldType.DelegateInvokeMethod != null) { Contract.ThrowIfNull(newType.DelegateInvokeMethod); AnalyzeReturnType(oldType.DelegateInvokeMethod, newType.DelegateInvokeMethod, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } } else if (oldSymbol is IPropertySymbol oldProperty && newSymbol is IPropertySymbol newProperty) { AnalyzeReturnType(oldProperty, newProperty, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } else if (oldSymbol is IEventSymbol oldEvent && newSymbol is IEventSymbol newEvent) { // "readonly" modifier can only be applied on the event itself, not on its accessors. if (oldEvent.AddMethod != null && newEvent.AddMethod != null && oldEvent.AddMethod.IsReadOnly != newEvent.AddMethod.IsReadOnly || oldEvent.RemoveMethod != null && newEvent.RemoveMethod != null && oldEvent.RemoveMethod.IsReadOnly != newEvent.RemoveMethod.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } else { AnalyzeReturnType(oldEvent, newEvent, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } else if (oldSymbol is IParameterSymbol oldParameter && newSymbol is IParameterSymbol newParameter) { if (oldParameter.RefKind != newParameter.RefKind || oldParameter.IsParams != newParameter.IsParams || IsExtensionMethodThisParameter(oldParameter) != IsExtensionMethodThisParameter(newParameter)) { rudeEdit = RudeEditKind.ModifiersUpdate; } else if (oldParameter.HasExplicitDefaultValue != newParameter.HasExplicitDefaultValue || oldParameter.HasExplicitDefaultValue && !Equals(oldParameter.ExplicitDefaultValue, newParameter.ExplicitDefaultValue)) { rudeEdit = RudeEditKind.InitializerUpdate; } else { AnalyzeParameterType(oldParameter, newParameter, ref rudeEdit, ref hasGeneratedAttributeChange); } } else if (oldSymbol is ITypeParameterSymbol oldTypeParameter && newSymbol is ITypeParameterSymbol newTypeParameter) { AnalyzeTypeParameter(oldTypeParameter, newTypeParameter, ref rudeEdit, ref hasGeneratedAttributeChange); } // Do not report modifier update if type kind changed. if (rudeEdit == RudeEditKind.None && oldSymbol.IsSealed != newSymbol.IsSealed) { // Do not report for accessors as the error will be reported on their associated symbol. if (oldSymbol is not IMethodSymbol { AssociatedSymbol: not null }) { rudeEdit = RudeEditKind.ModifiersUpdate; } } if (rudeEdit != RudeEditKind.None) { // so we'll just use the last global statement in the file ReportUpdateRudeEdit(diagnostics, rudeEdit, oldSymbol, newSymbol, newNode, newCompilation, cancellationToken); } } private static void AnalyzeType(ITypeSymbol oldType, ITypeSymbol newType, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange, RudeEditKind rudeEditKind = RudeEditKind.TypeUpdate) { if (!TypesEquivalent(oldType, newType, exact: true)) { if (TypesEquivalent(oldType, newType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = rudeEditKind; } } } private static void AnalyzeBaseTypes(INamedTypeSymbol oldType, INamedTypeSymbol newType, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (oldType.EnumUnderlyingType != null && newType.EnumUnderlyingType != null) { if (!TypesEquivalent(oldType.EnumUnderlyingType, newType.EnumUnderlyingType, exact: true)) { if (TypesEquivalent(oldType.EnumUnderlyingType, newType.EnumUnderlyingType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.EnumUnderlyingTypeUpdate; } } } else if (!BaseTypesEquivalent(oldType, newType, exact: true)) { if (BaseTypesEquivalent(oldType, newType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.BaseTypeOrInterfaceUpdate; } } } private static void AnalyzeParameterType(IParameterSymbol oldParameter, IParameterSymbol newParameter, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (!ParameterTypesEquivalent(oldParameter, newParameter, exact: true)) { if (ParameterTypesEquivalent(oldParameter, newParameter, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeTypeParameter(ITypeParameterSymbol oldParameter, ITypeParameterSymbol newParameter, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (!TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact: true)) { if (TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = (oldParameter.Variance != newParameter.Variance) ? RudeEditKind.VarianceUpdate : RudeEditKind.ChangingConstraints; } } } private static void AnalyzeReturnType(IMethodSymbol oldMethod, IMethodSymbol newMethod, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldMethod, newMethod, exact: true)) { if (ReturnTypesEquivalent(oldMethod, newMethod, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else if (IsGlobalMain(oldMethod) || IsGlobalMain(newMethod)) { rudeEdit = RudeEditKind.ChangeImplicitMainReturnType; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeReturnType(IEventSymbol oldEvent, IEventSymbol newEvent, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldEvent, newEvent, exact: true)) { if (ReturnTypesEquivalent(oldEvent, newEvent, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeReturnType(IPropertySymbol oldProperty, IPropertySymbol newProperty, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldProperty, newProperty, exact: true)) { if (ReturnTypesEquivalent(oldProperty, newProperty, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static bool IsExtensionMethodThisParameter(IParameterSymbol parameter) => parameter is { Ordinal: 0, ContainingSymbol: IMethodSymbol { IsExtensionMethod: true } }; private void AnalyzeSymbolUpdate( ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, Match<SyntaxNode> topMatch, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, ArrayBuilder<SemanticEditInfo> semanticEdits, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { // TODO: fails in VB on delegate parameter https://github.com/dotnet/roslyn/issues/53337 // Contract.ThrowIfFalse(newSymbol.IsImplicitlyDeclared == newDeclaration is null); ReportCustomAttributeRudeEdits(diagnostics, oldSymbol, newSymbol, newNode, newCompilation, capabilities, out var hasAttributeChange, out var hasReturnTypeAttributeChange, cancellationToken); ReportUpdatedSymbolDeclarationRudeEdits(diagnostics, oldSymbol, newSymbol, newNode, newCompilation, capabilities, out var hasGeneratedAttributeChange, out var hasGeneratedReturnTypeAttributeChange, out var hasParameterRename, cancellationToken); hasAttributeChange |= hasGeneratedAttributeChange; hasReturnTypeAttributeChange |= hasGeneratedReturnTypeAttributeChange; if (hasParameterRename) { Debug.Assert(newSymbol is IParameterSymbol); AddParameterUpdateSemanticEdit(semanticEdits, (IParameterSymbol)newSymbol, syntaxMap, cancellationToken); } else if (hasAttributeChange || hasReturnTypeAttributeChange) { AddCustomAttributeSemanticEdits(semanticEdits, oldSymbol, newSymbol, topMatch, syntaxMap, hasAttributeChange, hasReturnTypeAttributeChange, cancellationToken); } // updating generic methods and types if (InGenericContext(oldSymbol, out var oldIsGenericMethod) || InGenericContext(newSymbol, out _)) { var rudeEdit = oldIsGenericMethod ? RudeEditKind.GenericMethodUpdate : RudeEditKind.GenericTypeUpdate; ReportUpdateRudeEdit(diagnostics, rudeEdit, newSymbol, newNode, cancellationToken); } } private static void AddCustomAttributeSemanticEdits( ArrayBuilder<SemanticEditInfo> semanticEdits, ISymbol oldSymbol, ISymbol newSymbol, Match<SyntaxNode> topMatch, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool hasAttributeChange, bool hasReturnTypeAttributeChange, CancellationToken cancellationToken) { // Most symbol types will automatically have an edit added, so we just need to handle a few if (newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newDelegateInvokeMethod } newDelegateType) { if (hasAttributeChange) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newDelegateType, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } if (hasReturnTypeAttributeChange) { // attributes applied on return type of a delegate are applied to both Invoke and BeginInvoke methods semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newDelegateInvokeMethod, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); AddDelegateBeginInvokeEdit(semanticEdits, newDelegateType, syntaxMap, cancellationToken); } } else if (newSymbol is INamedTypeSymbol) { var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, topMatch.OldRoot.SyntaxTree, topMatch.NewRoot.SyntaxTree) ? symbolKey : null)); } else if (newSymbol is ITypeParameterSymbol) { var containingTypeSymbolKey = SymbolKey.Create(newSymbol.ContainingSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, containingTypeSymbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol.ContainingSymbol, newSymbol.ContainingSymbol, topMatch.OldRoot.SyntaxTree, topMatch.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else if (newSymbol is IFieldSymbol or IPropertySymbol or IEventSymbol) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newSymbol, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } else if (newSymbol is IParameterSymbol newParameterSymbol) { AddParameterUpdateSemanticEdit(semanticEdits, newParameterSymbol, syntaxMap, cancellationToken); } } private static void AddParameterUpdateSemanticEdit(ArrayBuilder<SemanticEditInfo> semanticEdits, IParameterSymbol newParameterSymbol, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { var newContainingSymbol = newParameterSymbol.ContainingSymbol; semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newContainingSymbol, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); // attributes applied on parameters of a delegate are applied to both Invoke and BeginInvoke methods if (newContainingSymbol.ContainingSymbol is INamedTypeSymbol { TypeKind: TypeKind.Delegate } newContainingDelegateType) { AddDelegateBeginInvokeEdit(semanticEdits, newContainingDelegateType, syntaxMap, cancellationToken); } } private static void AddDelegateBeginInvokeEdit(ArrayBuilder<SemanticEditInfo> semanticEdits, INamedTypeSymbol delegateType, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { Debug.Assert(semanticEdits != null); var beginInvokeMethod = delegateType.GetMembers("BeginInvoke").FirstOrDefault(); if (beginInvokeMethod != null) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(beginInvokeMethod, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } } private void ReportCustomAttributeRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, out bool hasAttributeChange, out bool hasReturnTypeAttributeChange, CancellationToken cancellationToken) { // This is the only case we care about whether to issue an edit or not, because this is the only case where types have their attributes checked // and types are the only things that would otherwise not have edits reported. hasAttributeChange = ReportCustomAttributeRudeEdits(diagnostics, oldSymbol.GetAttributes(), newSymbol.GetAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); hasReturnTypeAttributeChange = false; if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { hasReturnTypeAttributeChange |= ReportCustomAttributeRudeEdits(diagnostics, oldMethod.GetReturnTypeAttributes(), newMethod.GetReturnTypeAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); } else if (oldSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var oldInvokeMethod } && newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newInvokeMethod }) { hasReturnTypeAttributeChange |= ReportCustomAttributeRudeEdits(diagnostics, oldInvokeMethod.GetReturnTypeAttributes(), newInvokeMethod.GetReturnTypeAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); } } private bool ReportCustomAttributeRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { using var _ = ArrayBuilder<AttributeData>.GetInstance(out var changedAttributes); FindChangedAttributes(oldAttributes, newAttributes, changedAttributes); if (oldAttributes.HasValue) { FindChangedAttributes(newAttributes, oldAttributes.Value, changedAttributes); } if (changedAttributes.Count == 0) { return false; } // We need diagnostics reported if the runtime doesn't support changing attributes, // but even if it does, only attributes stored in the CustomAttributes table are editable if (!capabilities.HasFlag(EditAndContinueCapabilities.ChangeCustomAttributes) || changedAttributes.Any(IsNonCustomAttribute)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingAttributesNotSupportedByRuntime, oldSymbol, newSymbol, newNode, newCompilation, cancellationToken); // If the runtime doesn't support edits then pretend there weren't changes, so no edits are produced return false; } return true; static void FindChangedAttributes(ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ArrayBuilder<AttributeData> changedAttributes) { for (var i = 0; i < newAttributes.Length; i++) { var newAttribute = newAttributes[i]; var oldAttribute = FindMatch(newAttribute, oldAttributes); if (oldAttribute is null) { changedAttributes.Add(newAttribute); } } } static AttributeData? FindMatch(AttributeData attribute, ImmutableArray<AttributeData>? oldAttributes) { if (!oldAttributes.HasValue) { return null; } foreach (var match in oldAttributes.Value) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeClass, attribute.AttributeClass)) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeConstructor, attribute.AttributeConstructor) && match.ConstructorArguments.SequenceEqual(attribute.ConstructorArguments, TypedConstantComparer.Instance) && match.NamedArguments.SequenceEqual(attribute.NamedArguments, NamedArgumentComparer.Instance)) { return match; } } } return null; } static bool IsNonCustomAttribute(AttributeData attribute) { // TODO: Use a compiler API to get this information rather than hard coding a list: https://github.com/dotnet/roslyn/issues/53410 // This list comes from ShouldEmitAttribute in src\Compilers\CSharp\Portable\Symbols\Attributes\AttributeData.cs // and src\Compilers\VisualBasic\Portable\Symbols\Attributes\AttributeData.vb return attribute.AttributeClass?.ToNameDisplayString() switch { "System.CLSCompliantAttribute" => true, "System.Diagnostics.CodeAnalysis.AllowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" => true, "System.Diagnostics.CodeAnalysis.NotNullAttribute" => true, "System.NonSerializedAttribute" => true, "System.Reflection.AssemblyAlgorithmIdAttribute" => true, "System.Reflection.AssemblyCultureAttribute" => true, "System.Reflection.AssemblyFlagsAttribute" => true, "System.Reflection.AssemblyVersionAttribute" => true, "System.Runtime.CompilerServices.DllImportAttribute" => true, // Already covered by other rude edits, but included for completeness "System.Runtime.CompilerServices.IndexerNameAttribute" => true, "System.Runtime.CompilerServices.MethodImplAttribute" => true, "System.Runtime.CompilerServices.SpecialNameAttribute" => true, "System.Runtime.CompilerServices.TypeForwardedToAttribute" => true, "System.Runtime.InteropServices.ComImportAttribute" => true, "System.Runtime.InteropServices.DefaultParameterValueAttribute" => true, "System.Runtime.InteropServices.FieldOffsetAttribute" => true, "System.Runtime.InteropServices.InAttribute" => true, "System.Runtime.InteropServices.MarshalAsAttribute" => true, "System.Runtime.InteropServices.OptionalAttribute" => true, "System.Runtime.InteropServices.OutAttribute" => true, "System.Runtime.InteropServices.PreserveSigAttribute" => true, "System.Runtime.InteropServices.StructLayoutAttribute" => true, "System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeImportAttribute" => true, "System.Security.DynamicSecurityMethodAttribute" => true, "System.SerializableAttribute" => true, not null => IsSecurityAttribute(attribute.AttributeClass), _ => false }; } static bool IsSecurityAttribute(INamedTypeSymbol namedTypeSymbol) { // Security attributes are any attribute derived from System.Security.Permissions.SecurityAttribute, directly or indirectly var symbol = namedTypeSymbol; while (symbol is not null) { if (symbol.ToNameDisplayString() == "System.Security.Permissions.SecurityAttribute") { return true; } symbol = symbol.BaseType; } return false; } } private static bool CanAddNewMember(ISymbol newSymbol, EditAndContinueCapabilities capabilities) { if (newSymbol is IMethodSymbol or IPropertySymbol) // Properties are just get_ and set_ methods { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } else if (newSymbol is IFieldSymbol field) { if (field.IsStatic) { return capabilities.HasFlag(EditAndContinueCapabilities.AddStaticFieldToExistingType); } return capabilities.HasFlag(EditAndContinueCapabilities.AddInstanceFieldToExistingType); } return true; } private static void AddEditsForSynthesizedRecordMembers(Compilation compilation, INamedTypeSymbol recordType, ArrayBuilder<SemanticEditInfo> semanticEdits, CancellationToken cancellationToken) { foreach (var member in GetRecordUpdatedSynthesizedMembers(compilation, recordType)) { var symbolKey = SymbolKey.Create(member, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } private static IEnumerable<ISymbol> GetRecordUpdatedSynthesizedMembers(Compilation compilation, INamedTypeSymbol record) { // All methods that are updated have well known names, and calling GetMembers(string) is // faster than enumerating. // When a new field or property is added the PrintMembers, Equals(R) and GetHashCode() methods are updated // We don't need to worry about Deconstruct because it only changes when a new positional parameter // is added, and those are rude edits (due to adding a constructor parameter). // We don't need to worry about the constructors as they are reported elsewhere. // We have to use SingleOrDefault and check IsImplicitlyDeclared because the user can provide their // own implementation of these methods, and edits to them are handled by normal processing. var result = record.GetMembers(WellKnownMemberNames.PrintMembersMethodName) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, compilation.GetTypeByMetadataName(typeof(StringBuilder).FullName!)) && SymbolEqualityComparer.Default.Equals(m.ReturnType, compilation.GetTypeByMetadataName(typeof(bool).FullName!))); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectEquals) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType)); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectGetHashCode) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 0); if (result is not null) { yield return result; } } private void ReportDeletedMemberRudeEdit( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, Compilation newCompilation, RudeEditKind rudeEditKind, CancellationToken cancellationToken) { var newNode = GetDeleteRudeEditDiagnosticNode(oldSymbol, newCompilation, cancellationToken); diagnostics.Add(new RudeEditDiagnostic( rudeEditKind, GetDiagnosticSpan(newNode, EditKind.Delete), arguments: new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldSymbol), oldSymbol.ToDisplayString(s_unqualifiedMemberDisplayFormat)) })); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( rudeEdit, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode) })); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, ISymbol newSymbol, SyntaxNode? newNode, CancellationToken cancellationToken) { var node = newNode ?? GetRudeEditDiagnosticNode(newSymbol, cancellationToken); var span = (rudeEdit == RudeEditKind.ChangeImplicitMainReturnType) ? GetGlobalStatementDiagnosticSpan(node) : GetDiagnosticSpan(node, EditKind.Update); var arguments = rudeEdit switch { RudeEditKind.TypeKindUpdate or RudeEditKind.ChangeImplicitMainReturnType or RudeEditKind.GenericMethodUpdate or RudeEditKind.GenericTypeUpdate => Array.Empty<string>(), RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime => new[] { CreateNewOnMetadataUpdateAttributeName }, _ => new[] { GetDisplayName(newSymbol) } }; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, span, node, arguments)); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, CancellationToken cancellationToken) { if (newSymbol.IsImplicitlyDeclared) { ReportDeletedMemberRudeEdit(diagnostics, oldSymbol, newCompilation, rudeEdit, cancellationToken); } else { ReportUpdateRudeEdit(diagnostics, rudeEdit, newSymbol, newNode, cancellationToken); } } private static SyntaxNode GetRudeEditDiagnosticNode(ISymbol symbol, CancellationToken cancellationToken) { var container = symbol; while (container != null) { if (container.DeclaringSyntaxReferences.Length > 0) { return container.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken); } container = container.ContainingSymbol; } throw ExceptionUtilities.Unreachable; } private static SyntaxNode GetDeleteRudeEditDiagnosticNode(ISymbol oldSymbol, Compilation newCompilation, CancellationToken cancellationToken) { var oldContainer = oldSymbol.ContainingSymbol; while (oldContainer != null) { var containerKey = SymbolKey.Create(oldContainer, cancellationToken); var newContainer = containerKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContainer != null) { return GetRudeEditDiagnosticNode(newContainer, cancellationToken); } oldContainer = oldContainer.ContainingSymbol; } throw ExceptionUtilities.Unreachable; } #region Type Layout Update Validation internal void ReportTypeLayoutUpdateRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newSyntax, SemanticModel newModel, ref INamedTypeSymbol? lazyLayoutAttribute) { switch (newSymbol.Kind) { case SymbolKind.Field: if (HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Property: if (HasBackingField(newSyntax) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Event: if (HasBackingField((IEventSymbol)newSymbol) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; } } private void ReportTypeLayoutUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol symbol, SyntaxNode syntax) { var intoStruct = symbol.ContainingType.TypeKind == TypeKind.Struct; diagnostics.Add(new RudeEditDiagnostic( intoStruct ? RudeEditKind.InsertIntoStruct : RudeEditKind.InsertIntoClassWithLayout, syntax.Span, syntax, new[] { GetDisplayName(syntax, EditKind.Insert), GetDisplayName(TryGetContainingTypeDeclaration(syntax)!, EditKind.Update) })); } private static bool HasBackingField(IEventSymbol @event) { #nullable disable // https://github.com/dotnet/roslyn/issues/39288 return @event.AddMethod.IsImplicitlyDeclared #nullable enable && [email protected]; } private static bool HasExplicitOrSequentialLayout( INamedTypeSymbol type, SemanticModel model, ref INamedTypeSymbol? lazyLayoutAttribute) { if (type.TypeKind == TypeKind.Struct) { return true; } if (type.TypeKind != TypeKind.Class) { return false; } // Fields can't be inserted into a class with explicit or sequential layout var attributes = type.GetAttributes(); if (attributes.Length == 0) { return false; } lazyLayoutAttribute ??= model.Compilation.GetTypeByMetadataName(typeof(StructLayoutAttribute).FullName!); if (lazyLayoutAttribute == null) { return false; } foreach (var attribute in attributes) { RoslynDebug.Assert(attribute.AttributeClass is object); if (attribute.AttributeClass.Equals(lazyLayoutAttribute) && attribute.ConstructorArguments.Length == 1) { var layoutValue = attribute.ConstructorArguments.Single().Value; return (layoutValue is int ? (int)layoutValue : layoutValue is short ? (short)layoutValue : (int)LayoutKind.Auto) != (int)LayoutKind.Auto; } } return false; } #endregion private Func<SyntaxNode, SyntaxNode?> CreateSyntaxMapForEquivalentNodes(SyntaxNode oldDeclaration, SyntaxNode newDeclaration) { return newNode => newDeclaration.FullSpan.Contains(newNode.SpanStart) ? FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode) : null; } private static Func<SyntaxNode, SyntaxNode?> CreateSyntaxMap(IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) => newNode => reverseMap.TryGetValue(newNode, out var oldNode) ? oldNode : null; private Func<SyntaxNode, SyntaxNode?>? CreateAggregateSyntaxMap( IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseTopMatches, IReadOnlyDictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> changedDeclarations) { return newNode => { // containing declaration if (!TryFindMemberDeclaration(root: null, newNode, out var newDeclarations)) { return null; } foreach (var newDeclaration in newDeclarations) { // The node is in a field, property or constructor declaration that has been changed: if (changedDeclarations.TryGetValue(newDeclaration, out var syntaxMap)) { // If syntax map is not available the declaration was either // 1) updated but is not active // 2) inserted return syntaxMap?.Invoke(newNode); } // The node is in a declaration that hasn't been changed: if (reverseTopMatches.TryGetValue(newDeclaration, out var oldDeclaration)) { return FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode); } } return null; }; } #region Constructors and Initializers /// <summary> /// Called when a body of a constructor or an initializer of a member is updated or inserted. /// </summary> private static void DeferConstructorEdit( INamedTypeSymbol oldType, INamedTypeSymbol newType, SyntaxNode? newDeclaration, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool isStatic, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits) { Dictionary<INamedTypeSymbol, ConstructorEdit> constructorEdits; if (isStatic) { constructorEdits = staticConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } else { constructorEdits = instanceConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } if (!constructorEdits.TryGetValue(newType, out var constructorEdit)) { constructorEdits.Add(newType, constructorEdit = new ConstructorEdit(oldType)); } if (newDeclaration != null && !constructorEdit.ChangedDeclarations.ContainsKey(newDeclaration)) { constructorEdit.ChangedDeclarations.Add(newDeclaration, syntaxMap); } } private void AddConstructorEdits( IReadOnlyDictionary<INamedTypeSymbol, ConstructorEdit> updatedTypes, Match<SyntaxNode> topMatch, SemanticModel? oldModel, Compilation oldCompilation, Compilation newCompilation, IReadOnlySet<ISymbol> processedSymbols, EditAndContinueCapabilities capabilities, bool isStatic, [Out] ArrayBuilder<SemanticEditInfo> semanticEdits, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var oldSyntaxTree = topMatch.OldRoot.SyntaxTree; var newSyntaxTree = topMatch.NewRoot.SyntaxTree; foreach (var (newType, updatesInCurrentDocument) in updatedTypes) { var oldType = updatesInCurrentDocument.OldType; var anyInitializerUpdatesInCurrentDocument = updatesInCurrentDocument.ChangedDeclarations.Keys.Any(IsDeclarationWithInitializer); var isPartialEdit = IsPartialEdit(oldType, newType, oldSyntaxTree, newSyntaxTree); // Create a syntax map that aggregates syntax maps of the constructor body and all initializers in this document. // Use syntax maps stored in update.ChangedDeclarations and fallback to 1:1 map for unchanged members. // // This aggregated map will be combined with similar maps capturing members declared in partial type declarations // located in other documents when the semantic edits are merged across all changed documents of the project. // // We will create an aggregate syntax map even in cases when we don't necessarily need it, // for example if none of the edited declarations are active. It's ok to have a map that we don't need. // This is simpler than detecting whether or not some of the initializers/constructors contain active statements. var aggregateSyntaxMap = CreateAggregateSyntaxMap(topMatch.ReverseMatches, updatesInCurrentDocument.ChangedDeclarations); bool? lazyOldTypeHasMemberInitializerContainingLambda = null; foreach (var newCtor in isStatic ? newType.StaticConstructors : newType.InstanceConstructors) { if (processedSymbols.Contains(newCtor)) { // we already have an edit for the new constructor continue; } var newCtorKey = SymbolKey.Create(newCtor, cancellationToken); var syntaxMapToUse = aggregateSyntaxMap; SyntaxNode? newDeclaration = null; ISymbol? oldCtor; if (!newCtor.IsImplicitlyDeclared) { // Constructors have to have a single declaration syntax, they can't be partial newDeclaration = GetSymbolDeclarationSyntax(newCtor.DeclaringSyntaxReferences.Single(), cancellationToken); // Implicit record constructors are represented by the record declaration itself. // https://github.com/dotnet/roslyn/issues/54403 var isPrimaryRecordConstructor = IsRecordDeclaration(newDeclaration); // Constructor that doesn't contain initializers had a corresponding semantic edit produced previously // or was not edited. In either case we should not produce a semantic edit for it. if (!isPrimaryRecordConstructor && !IsConstructorWithMemberInitializers(newDeclaration)) { continue; } // If no initializer updates were made in the type we only need to produce semantic edits for constructors // whose body has been updated, otherwise we need to produce edits for all constructors that include initializers. // If changes were made to initializers or constructors of a partial type in another document they will be merged // when aggregating semantic edits from all changed documents. Rude edits resulting from those changes, if any, will // be reported in the document they were made in. if (!isPrimaryRecordConstructor && !anyInitializerUpdatesInCurrentDocument && !updatesInCurrentDocument.ChangedDeclarations.ContainsKey(newDeclaration)) { continue; } // To avoid costly SymbolKey resolution we first try to match the constructor in the current document // and special case parameter-less constructor. // In the case of records, newDeclaration will point to the record declaration, take the slow path. if (!isPrimaryRecordConstructor && topMatch.TryGetOldNode(newDeclaration, out var oldDeclaration)) { Contract.ThrowIfNull(oldModel); oldCtor = oldModel.GetDeclaredSymbol(oldDeclaration, cancellationToken); Contract.ThrowIfFalse(oldCtor is IMethodSymbol { MethodKind: MethodKind.Constructor or MethodKind.StaticConstructor }); } else if (!isPrimaryRecordConstructor && newCtor.Parameters.Length == 0) { oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } else { var resolution = newCtorKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); // There may be semantic errors in the compilation that result in multiple candidates. // Pick the first candidate. oldCtor = resolution.Symbol; } if (oldCtor == null && HasMemberInitializerContainingLambda(oldType, isStatic, ref lazyOldTypeHasMemberInitializerContainingLambda, cancellationToken)) { // TODO (bug https://github.com/dotnet/roslyn/issues/2504) // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); continue; } // Report an error if the updated constructor's declaration is in the current document // and its body edit is disallowed (e.g. contains stackalloc). if (oldCtor != null && newDeclaration.SyntaxTree == newSyntaxTree && anyInitializerUpdatesInCurrentDocument) { // attribute rude edit to one of the modified members var firstSpan = updatesInCurrentDocument.ChangedDeclarations.Keys.Where(IsDeclarationWithInitializer).Aggregate( (min: int.MaxValue, span: default(TextSpan)), (accumulate, node) => (node.SpanStart < accumulate.min) ? (node.SpanStart, node.Span) : accumulate).span; Contract.ThrowIfTrue(firstSpan.IsEmpty); ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, firstSpan); } // When explicitly implementing the copy constructor of a record the parameter name must match for symbol matching to work // TODO: Remove this requirement with https://github.com/dotnet/roslyn/issues/52563 if (oldCtor != null && !isPrimaryRecordConstructor && oldCtor.DeclaringSyntaxReferences.Length == 0 && newCtor.Parameters.Length == 1 && newType.IsRecord && oldCtor.GetParameters().First().Name != newCtor.GetParameters().First().Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, GetDiagnosticSpan(newDeclaration, EditKind.Update), arguments: new[] { oldCtor.ToDisplayString(SymbolDisplayFormats.NameFormat) })); continue; } } else { if (newCtor.Parameters.Length == 1) { // New constructor is implicitly declared with a parameter, so its the copy constructor of a record Debug.Assert(oldType.IsRecord); Debug.Assert(newType.IsRecord); // We only need an edit for this if the number of properties or fields on the record has changed. Changes to // initializers, or whether the property is part of the primary constructor, will still come through this code // path because they need an edit to the other constructor, but not the copy construcor. if (oldType.GetMembers().OfType<IPropertySymbol>().Count() == newType.GetMembers().OfType<IPropertySymbol>().Count() && oldType.GetMembers().OfType<IFieldSymbol>().Count() == newType.GetMembers().OfType<IFieldSymbol>().Count()) { continue; } oldCtor = oldType.InstanceConstructors.Single(c => c.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(c.Parameters[0].Type, c.ContainingType)); // The copy constructor does not have a syntax map syntaxMapToUse = null; // Since there is no syntax map, we don't need to handle anything special to merge them for partial types. // The easiest way to do this is just to pretend this isn't a partial edit. isPartialEdit = false; } else { // New constructor is implicitly declared so it must be parameterless. // // Instance constructor: // Its presence indicates there are no other instance constructors in the new type and therefore // there must be a single parameterless instance constructor in the old type (constructors with parameters can't be removed). // // Static constructor: // Static constructor is always parameterless and not implicitly generated if there are no static initializers. oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } Contract.ThrowIfFalse(isStatic || oldCtor != null); } if (oldCtor != null) { AnalyzeSymbolUpdate(oldCtor, newCtor, newDeclaration, newCompilation, topMatch, capabilities, diagnostics, semanticEdits, syntaxMapToUse, cancellationToken); semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Update, newCtorKey, syntaxMapToUse, syntaxMapTree: isPartialEdit ? newSyntaxTree : null, partialType: isPartialEdit ? SymbolKey.Create(newType, cancellationToken) : null)); } else { semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Insert, newCtorKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } } } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, ref bool? lazyHasMemberInitializerContainingLambda, CancellationToken cancellationToken) { if (lazyHasMemberInitializerContainingLambda == null) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) lazyHasMemberInitializerContainingLambda = HasMemberInitializerContainingLambda(type, isStatic, cancellationToken); } return lazyHasMemberInitializerContainingLambda.Value; } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, CancellationToken cancellationToken) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) foreach (var member in type.GetMembers()) { if (member.IsStatic == isStatic && (member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property) && member.DeclaringSyntaxReferences.Length > 0) // skip generated fields (e.g. VB auto-property backing fields) { var syntax = GetSymbolDeclarationSyntax(member.DeclaringSyntaxReferences.Single(), cancellationToken); if (IsDeclarationWithInitializer(syntax) && ContainsLambda(syntax)) { return true; } } } return false; } private static ISymbol? TryGetParameterlessConstructor(INamedTypeSymbol type, bool isStatic) { var oldCtors = isStatic ? type.StaticConstructors : type.InstanceConstructors; if (isStatic) { return type.StaticConstructors.FirstOrDefault(); } else { return type.InstanceConstructors.FirstOrDefault(m => m.Parameters.Length == 0); } } private static bool IsPartialEdit(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxTree oldSyntaxTree, SyntaxTree newSyntaxTree) { // If any of the partial declarations of the new or the old type are in another document // the edit will need to be merged with other partial edits with matching partial type static bool IsNotInDocument(SyntaxReference reference, SyntaxTree syntaxTree) => reference.SyntaxTree != syntaxTree; return oldSymbol?.Kind == SymbolKind.NamedType && oldSymbol.DeclaringSyntaxReferences.Length > 1 && oldSymbol.DeclaringSyntaxReferences.Any(IsNotInDocument, oldSyntaxTree) || newSymbol?.Kind == SymbolKind.NamedType && newSymbol.DeclaringSyntaxReferences.Length > 1 && newSymbol.DeclaringSyntaxReferences.Any(IsNotInDocument, newSyntaxTree); } #endregion #region Lambdas and Closures private void ReportLambdaAndClosureRudeEdits( SemanticModel oldModel, SyntaxNode oldMemberBody, SemanticModel newModel, SyntaxNode newMemberBody, ISymbol newMember, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas, BidirectionalMap<SyntaxNode> map, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool syntaxMapRequired, CancellationToken cancellationToken) { syntaxMapRequired = false; if (matchedLambdas != null) { var anySignatureErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { // Any unmatched lambdas would have contained an active statement and a rude edit would be reported in syntax analysis phase. // Skip the rest of lambda and closure analysis if such lambdas are present. if (newLambdaInfo.Match == null || newLambdaInfo.NewBody == null) { return; } ReportLambdaSignatureRudeEdits(diagnostics, oldModel, oldLambdaBody, newModel, newLambdaInfo.NewBody, capabilities, out var hasErrors, cancellationToken); anySignatureErrors |= hasErrors; } ArrayBuilder<SyntaxNode>? lazyNewErroneousClauses = null; foreach (var (oldQueryClause, newQueryClause) in map.Forward) { if (!QueryClauseLambdasTypeEquivalent(oldModel, oldQueryClause, newModel, newQueryClause, cancellationToken)) { lazyNewErroneousClauses ??= ArrayBuilder<SyntaxNode>.GetInstance(); lazyNewErroneousClauses.Add(newQueryClause); } } if (lazyNewErroneousClauses != null) { foreach (var newQueryClause in from clause in lazyNewErroneousClauses orderby clause.SpanStart group clause by GetContainingQueryExpression(clause) into clausesByQuery select clausesByQuery.First()) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingQueryLambdaType, GetDiagnosticSpan(newQueryClause, EditKind.Update), newQueryClause, new[] { GetDisplayName(newQueryClause, EditKind.Update) })); } lazyNewErroneousClauses.Free(); anySignatureErrors = true; } // only dig into captures if lambda signatures match if (anySignatureErrors) { return; } } using var oldLambdaBodyEnumerator = GetLambdaBodies(oldMemberBody).GetEnumerator(); using var newLambdaBodyEnumerator = GetLambdaBodies(newMemberBody).GetEnumerator(); var oldHasLambdas = oldLambdaBodyEnumerator.MoveNext(); var newHasLambdas = newLambdaBodyEnumerator.MoveNext(); // Exit early if there are no lambdas in the method to avoid expensive data flow analysis: if (!oldHasLambdas && !newHasLambdas) { return; } var oldCaptures = GetCapturedVariables(oldModel, oldMemberBody); var newCaptures = GetCapturedVariables(newModel, newMemberBody); // { new capture index -> old capture index } using var _1 = ArrayBuilder<int>.GetInstance(newCaptures.Length, fillWithValue: 0, out var reverseCapturesMap); // { new capture index -> new closure scope or null for "this" } using var _2 = ArrayBuilder<SyntaxNode?>.GetInstance(newCaptures.Length, fillWithValue: null, out var newCapturesToClosureScopes); // Can be calculated from other maps but it's simpler to just calculate it upfront. // { old capture index -> old closure scope or null for "this" } using var _3 = ArrayBuilder<SyntaxNode?>.GetInstance(oldCaptures.Length, fillWithValue: null, out var oldCapturesToClosureScopes); CalculateCapturedVariablesMaps( oldCaptures, oldMemberBody, newCaptures, newMember, newMemberBody, map, reverseCapturesMap, newCapturesToClosureScopes, oldCapturesToClosureScopes, diagnostics, out var anyCaptureErrors, cancellationToken); if (anyCaptureErrors) { return; } // Every captured variable accessed in the new lambda has to be // accessed in the old lambda as well and vice versa. // // An added lambda can only reference captured variables that // // This requirement ensures that: // - Lambda methods are generated to the same frame as before, so they can be updated in-place. // - "Parent" links between closure scopes are preserved. using var _11 = PooledDictionary<ISymbol, int>.GetInstance(out var oldCapturesIndex); using var _12 = PooledDictionary<ISymbol, int>.GetInstance(out var newCapturesIndex); BuildIndex(oldCapturesIndex, oldCaptures); BuildIndex(newCapturesIndex, newCaptures); if (matchedLambdas != null) { var mappedLambdasHaveErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { var newLambdaBody = newLambdaInfo.NewBody; // The map now contains only matched lambdas. Any unmatched ones would have contained an active statement and // a rude edit would be reported in syntax analysis phase. RoslynDebug.Assert(newLambdaInfo.Match != null && newLambdaBody != null); var accessedOldCaptures = GetAccessedCaptures(oldLambdaBody, oldModel, oldCaptures, oldCapturesIndex); var accessedNewCaptures = GetAccessedCaptures(newLambdaBody, newModel, newCaptures, newCapturesIndex); // Requirement: // (new(ReadInside) \/ new(WrittenInside)) /\ new(Captured) == (old(ReadInside) \/ old(WrittenInside)) /\ old(Captured) for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newAccessed = accessedNewCaptures[newCaptureIndex]; var oldAccessed = accessedOldCaptures[reverseCapturesMap[newCaptureIndex]]; if (newAccessed != oldAccessed) { var newCapture = newCaptures[newCaptureIndex]; var rudeEdit = newAccessed ? RudeEditKind.AccessingCapturedVariableInLambda : RudeEditKind.NotAccessingCapturedVariableInLambda; var arguments = new[] { newCapture.Name, GetDisplayName(GetLambda(newLambdaBody)) }; if (newCapture.IsThisParameter() || oldAccessed) { // changed accessed to "this", or captured variable accessed in old lambda is not accessed in the new lambda diagnostics.Add(new RudeEditDiagnostic(rudeEdit, GetDiagnosticSpan(GetLambda(newLambdaBody), EditKind.Update), null, arguments)); } else if (newAccessed) { // captured variable accessed in new lambda is not accessed in the old lambda var hasUseSites = false; foreach (var useSite in GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(newLambdaBody), newCapture, newModel, cancellationToken)) { hasUseSites = true; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, useSite.Span, null, arguments)); } Debug.Assert(hasUseSites); } mappedLambdasHaveErrors = true; } } } if (mappedLambdasHaveErrors) { return; } } // Report rude edits for lambdas added to the method. // We already checked that no new captures are introduced or removed. // We also need to make sure that no new parent frame links are introduced. // // We could implement the same analysis as the compiler does when rewriting lambdas - // to determine what closure scopes are connected at runtime via parent link, // and then disallow adding a lambda that connects two previously unconnected // groups of scopes. // // However even if we implemented that logic here, it would be challenging to // present the result of the analysis to the user in a short comprehensible error message. // // In practice, we believe the common scenarios are (in order of commonality): // 1) adding a static lambda // 2) adding a lambda that accesses only "this" // 3) adding a lambda that accesses variables from the same scope // 4) adding a lambda that accesses "this" and variables from a single scope // 5) adding a lambda that accesses variables from different scopes that are linked // 6) adding a lambda that accesses variables from unlinked scopes // // We currently allow #1, #2, and #3 and report a rude edit for the other cases. // In future we might be able to enable more. var containingTypeDeclaration = TryGetContainingTypeDeclaration(newMemberBody); var isInInterfaceDeclaration = containingTypeDeclaration != null && IsInterfaceDeclaration(containingTypeDeclaration); var newHasLambdaBodies = newHasLambdas; while (newHasLambdaBodies) { var (newLambda, newLambdaBody1, newLambdaBody2) = newLambdaBodyEnumerator.Current; if (!map.Reverse.ContainsKey(newLambda)) { if (!CanAddNewLambda(newLambda, capabilities, matchedLambdas)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda, new string[] { GetDisplayName(newLambda, EditKind.Insert) })); } // TODO: https://github.com/dotnet/roslyn/issues/37128 // Local functions are emitted directly to the type containing the containing method. // Although local functions are non-virtual the Core CLR currently does not support adding any method to an interface. if (isInInterfaceDeclaration && IsLocalFunction(newLambda)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda)); } ReportMultiScopeCaptures(newLambdaBody1, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); if (newLambdaBody2 != null) { ReportMultiScopeCaptures(newLambdaBody2, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); } } newHasLambdaBodies = newLambdaBodyEnumerator.MoveNext(); } // Similarly for addition. We don't allow removal of lambda that has captures from multiple scopes. var oldHasMoreLambdas = oldHasLambdas; while (oldHasMoreLambdas) { var (oldLambda, oldLambdaBody1, oldLambdaBody2) = oldLambdaBodyEnumerator.Current; if (!map.Forward.ContainsKey(oldLambda)) { ReportMultiScopeCaptures(oldLambdaBody1, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); if (oldLambdaBody2 != null) { ReportMultiScopeCaptures(oldLambdaBody2, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); } } oldHasMoreLambdas = oldLambdaBodyEnumerator.MoveNext(); } syntaxMapRequired = newHasLambdas; } private IEnumerable<(SyntaxNode lambda, SyntaxNode lambdaBody1, SyntaxNode? lambdaBody2)> GetLambdaBodies(SyntaxNode body) { foreach (var node in body.DescendantNodesAndSelf()) { if (TryGetLambdaBodies(node, out var body1, out var body2)) { yield return (node, body1, body2); } } } private bool CanAddNewLambda(SyntaxNode newLambda, EditAndContinueCapabilities capabilities, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas) { // New local functions mean new methods in existing classes if (IsLocalFunction(newLambda)) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // New lambdas sometimes mean creating new helper classes, and sometimes mean new methods in exising helper classes // Unfortunately we are limited here in what we can do here. See: https://github.com/dotnet/roslyn/issues/52759 // If there is already a lambda in the method then the new lambda would result in a new method in the existing helper class. // This check is redundant with the below, once the limitation in the referenced issue is resolved if (matchedLambdas is { Count: > 0 }) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // If there is already a lambda in the class then the new lambda would result in a new method in the existing helper class. // If there isn't already a lambda in the class then the new lambda would result in a new helper class. // Unfortunately right now we can't determine which of these is true so we have to just check both capabilities instead. return capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition) && capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } private void ReportMultiScopeCaptures( SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, ImmutableArray<ISymbol> newCaptures, ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, PooledDictionary<ISymbol, int> capturesIndex, ArrayBuilder<int> reverseCapturesMap, ArrayBuilder<RudeEditDiagnostic> diagnostics, bool isInsert, CancellationToken cancellationToken) { if (captures.Length == 0) { return; } var accessedCaptures = GetAccessedCaptures(lambdaBody, model, captures, capturesIndex); var firstAccessedCaptureIndex = -1; for (var i = 0; i < captures.Length; i++) { if (accessedCaptures[i]) { if (firstAccessedCaptureIndex == -1) { firstAccessedCaptureIndex = i; } else if (newCapturesToClosureScopes[firstAccessedCaptureIndex] != newCapturesToClosureScopes[i]) { // the lambda accesses variables from two different scopes: TextSpan errorSpan; RudeEditKind rudeEdit; if (isInsert) { if (captures[i].IsThisParameter()) { errorSpan = GetDiagnosticSpan(GetLambda(lambdaBody), EditKind.Insert); } else { errorSpan = GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(lambdaBody), captures[i], model, cancellationToken).First().Span; } rudeEdit = RudeEditKind.InsertLambdaWithMultiScopeCapture; } else { errorSpan = newCaptures[reverseCapturesMap.IndexOf(i)].Locations.Single().SourceSpan; rudeEdit = RudeEditKind.DeleteLambdaWithMultiScopeCapture; } diagnostics.Add(new RudeEditDiagnostic( rudeEdit, errorSpan, null, new[] { GetDisplayName(GetLambda(lambdaBody)), captures[firstAccessedCaptureIndex].Name, captures[i].Name })); break; } } } } private BitVector GetAccessedCaptures(SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, PooledDictionary<ISymbol, int> capturesIndex) { var result = BitVector.Create(captures.Length); foreach (var expressionOrStatement in GetLambdaBodyExpressionsAndStatements(lambdaBody)) { var dataFlow = model.AnalyzeDataFlow(expressionOrStatement); MarkVariables(ref result, dataFlow.ReadInside, capturesIndex); MarkVariables(ref result, dataFlow.WrittenInside, capturesIndex); } return result; } private static void MarkVariables(ref BitVector mask, ImmutableArray<ISymbol> variables, Dictionary<ISymbol, int> index) { foreach (var variable in variables) { if (index.TryGetValue(variable, out var newCaptureIndex)) { mask[newCaptureIndex] = true; } } } private static void BuildIndex<TKey>(Dictionary<TKey, int> index, ImmutableArray<TKey> array) where TKey : notnull { for (var i = 0; i < array.Length; i++) { index.Add(array[i], i); } } /// <summary> /// Returns node that represents a declaration of the symbol whose <paramref name="reference"/> is passed in. /// </summary> protected abstract SyntaxNode GetSymbolDeclarationSyntax(SyntaxReference reference, CancellationToken cancellationToken); private static TextSpan GetThisParameterDiagnosticSpan(ISymbol member) => member.Locations.First().SourceSpan; private static TextSpan GetVariableDiagnosticSpan(ISymbol local) { // Note that in VB implicit value parameter in property setter doesn't have a location. // In C# its location is the location of the setter. // See https://github.com/dotnet/roslyn/issues/14273 return local.Locations.FirstOrDefault()?.SourceSpan ?? local.ContainingSymbol.Locations.First().SourceSpan; } private static (SyntaxNode? Node, int Ordinal) GetParameterKey(IParameterSymbol parameter, CancellationToken cancellationToken) { var containingLambda = parameter.ContainingSymbol as IMethodSymbol; if (containingLambda?.MethodKind is MethodKind.LambdaMethod or MethodKind.LocalFunction) { var oldContainingLambdaSyntax = containingLambda.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); return (oldContainingLambdaSyntax, parameter.Ordinal); } else { return (Node: null, parameter.Ordinal); } } private static bool TryMapParameter((SyntaxNode? Node, int Ordinal) parameterKey, IReadOnlyDictionary<SyntaxNode, SyntaxNode> map, out (SyntaxNode? Node, int Ordinal) mappedParameterKey) { var containingLambdaSyntax = parameterKey.Node; if (containingLambdaSyntax == null) { // method parameter: no syntax, same ordinal (can't change since method signatures must match) mappedParameterKey = parameterKey; return true; } if (map.TryGetValue(containingLambdaSyntax, out var mappedContainingLambdaSyntax)) { // parameter of an existing lambda: same ordinal (can't change since lambda signatures must match), mappedParameterKey = (mappedContainingLambdaSyntax, parameterKey.Ordinal); return true; } // no mapping mappedParameterKey = default; return false; } private void CalculateCapturedVariablesMaps( ImmutableArray<ISymbol> oldCaptures, SyntaxNode oldMemberBody, ImmutableArray<ISymbol> newCaptures, ISymbol newMember, SyntaxNode newMemberBody, BidirectionalMap<SyntaxNode> map, [Out] ArrayBuilder<int> reverseCapturesMap, // {new capture index -> old capture index} [Out] ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, // {new capture index -> new closure scope} [Out] ArrayBuilder<SyntaxNode?> oldCapturesToClosureScopes, // {old capture index -> old closure scope} [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool hasErrors, CancellationToken cancellationToken) { hasErrors = false; // Validate that all variables that are/were captured in the new/old body were captured in // the old/new one and their type and scope haven't changed. // // Frames are created based upon captured variables and their scopes. If the scopes haven't changed the frames won't either. // // In future we can relax some of these limitations. // - If a newly captured variable's scope is already a closure then it is ok to lift this variable to the existing closure, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the local variable to the lifted field. // // Consider the following edit: // Gen0 Gen1 // ... ... // { { // int x = 1, y = 2; int x = 1, y = 2; // F(() => x); F(() => x); // AS-->W(y) AS-->W(y) // F(() => y); // } } // ... ... // // - If an "uncaptured" variable's scope still defines other captured variables it is ok to cease capturing the variable, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the lifted field to the local variable (consider reverse edit in the example above). // // - While building the closure tree for the new version the compiler can recreate // the closure tree of the previous version and then map // closure scopes in the new version to the previous ones, keeping empty closures around. using var _1 = PooledDictionary<SyntaxNode, int>.GetInstance(out var oldLocalCapturesBySyntax); using var _2 = PooledDictionary<(SyntaxNode? Node, int Ordinal), int>.GetInstance(out var oldParameterCapturesByLambdaAndOrdinal); for (var i = 0; i < oldCaptures.Length; i++) { var oldCapture = oldCaptures[i]; if (oldCapture.Kind == SymbolKind.Parameter) { oldParameterCapturesByLambdaAndOrdinal.Add(GetParameterKey((IParameterSymbol)oldCapture, cancellationToken), i); } else { oldLocalCapturesBySyntax.Add(oldCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken), i); } } for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newCapture = newCaptures[newCaptureIndex]; int oldCaptureIndex; if (newCapture.Kind == SymbolKind.Parameter) { var newParameterCapture = (IParameterSymbol)newCapture; var newParameterKey = GetParameterKey(newParameterCapture, cancellationToken); if (!TryMapParameter(newParameterKey, map.Reverse, out var oldParameterKey) || !oldParameterCapturesByLambdaAndOrdinal.TryGetValue(oldParameterKey, out oldCaptureIndex)) { // parameter has not been captured prior the edit: diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old parameter capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldParameterCapturesByLambdaAndOrdinal.Remove(oldParameterKey); } else { var newCaptureSyntax = newCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); // variable doesn't exists in the old method or has not been captured prior the edit: if (!map.Reverse.TryGetValue(newCaptureSyntax, out var mappedOldSyntax) || !oldLocalCapturesBySyntax.TryGetValue(mappedOldSyntax, out oldCaptureIndex)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, newCapture.Locations.First().SourceSpan, null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldLocalCapturesBySyntax.Remove(mappedOldSyntax); } reverseCapturesMap[newCaptureIndex] = oldCaptureIndex; // the type and scope of parameters can't change if (newCapture.Kind == SymbolKind.Parameter) { continue; } var oldCapture = oldCaptures[oldCaptureIndex]; // Parameter capture can't be changed to local capture and vice versa // because parameters can't be introduced or deleted during EnC // (we checked above for changes in lambda signatures). // Also range variables can't be mapped to other variables since they have // different kinds of declarator syntax nodes. Debug.Assert(oldCapture.Kind == newCapture.Kind); // Range variables don't have types. Each transparent identifier (range variable use) // might have a different type. Changing these types is ok as long as the containing lambda // signatures remain unchanged, which we validate for all lambdas in general. // // The scope of a transparent identifier is the containing lambda body. Since we verify that // each lambda body accesses the same captured variables (including range variables) // the corresponding scopes are guaranteed to be preserved as well. if (oldCapture.Kind == SymbolKind.RangeVariable) { continue; } // rename: // Note that the name has to match exactly even in VB, since we can't rename a field. // Consider: We could allow rename by emitting some special debug info for the field. if (newCapture.Name != oldCapture.Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.RenamingCapturedVariable, newCapture.Locations.First().SourceSpan, null, new[] { oldCapture.Name, newCapture.Name })); hasErrors = true; continue; } // type check var oldTypeOpt = GetType(oldCapture); var newTypeOpt = GetType(newCapture); if (!TypesEquivalent(oldTypeOpt, newTypeOpt, exact: false)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableType, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name, oldTypeOpt.ToDisplayString(ErrorDisplayFormat) })); hasErrors = true; continue; } // scope check: var oldScopeOpt = GetCapturedVariableScope(oldCapture, oldMemberBody, cancellationToken); var newScopeOpt = GetCapturedVariableScope(newCapture, newMemberBody, cancellationToken); if (!AreEquivalentClosureScopes(oldScopeOpt, newScopeOpt, map.Reverse)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableScope, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } newCapturesToClosureScopes[newCaptureIndex] = newScopeOpt; oldCapturesToClosureScopes[oldCaptureIndex] = oldScopeOpt; } // What's left in oldCapturesBySyntax are captured variables in the previous version // that have no corresponding captured variables in the new version. // Report a rude edit for all such variables. if (oldParameterCapturesByLambdaAndOrdinal.Count > 0) { // syntax-less parameters are not included: var newMemberParametersWithSyntax = newMember.GetParameters(); // uncaptured parameters: foreach (var ((oldContainingLambdaSyntax, ordinal), oldCaptureIndex) in oldParameterCapturesByLambdaAndOrdinal) { var oldCapture = oldCaptures[oldCaptureIndex]; TextSpan span; if (ordinal < 0) { // this parameter: span = GetThisParameterDiagnosticSpan(newMember); } else if (oldContainingLambdaSyntax != null) { // lambda: span = GetLambdaParameterDiagnosticSpan(oldContainingLambdaSyntax, ordinal); } else if (oldCapture.IsImplicitValueParameter()) { // value parameter of a property/indexer setter, event adder/remover: span = newMember.Locations.First().SourceSpan; } else { // method or property: span = GetVariableDiagnosticSpan(newMemberParametersWithSyntax[ordinal]); } diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, span, null, new[] { oldCapture.Name })); } hasErrors = true; } if (oldLocalCapturesBySyntax.Count > 0) { // uncaptured or deleted variables: foreach (var entry in oldLocalCapturesBySyntax) { var oldCaptureNode = entry.Key; var oldCaptureIndex = entry.Value; var name = oldCaptures[oldCaptureIndex].Name; if (map.Forward.TryGetValue(oldCaptureNode, out var newCaptureNode)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, newCaptureNode.Span, null, new[] { name })); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeletingCapturedVariable, GetDeletedNodeDiagnosticSpan(map.Forward, oldCaptureNode), null, new[] { name })); } } hasErrors = true; } } private void ReportLambdaSignatureRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, SemanticModel oldModel, SyntaxNode oldLambdaBody, SemanticModel newModel, SyntaxNode newLambdaBody, EditAndContinueCapabilities capabilities, out bool hasSignatureErrors, CancellationToken cancellationToken) { hasSignatureErrors = false; var newLambda = GetLambda(newLambdaBody); var oldLambda = GetLambda(oldLambdaBody); Debug.Assert(IsNestedFunction(newLambda) == IsNestedFunction(oldLambda)); // queries are analyzed separately if (!IsNestedFunction(newLambda)) { return; } if (IsLocalFunction(oldLambda) != IsLocalFunction(newLambda)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.SwitchBetweenLambdaAndLocalFunction, newLambda); hasSignatureErrors = true; return; } var oldLambdaSymbol = GetLambdaExpressionSymbol(oldModel, oldLambda, cancellationToken); var newLambdaSymbol = GetLambdaExpressionSymbol(newModel, newLambda, cancellationToken); // signature validation: if (!ParameterTypesEquivalent(oldLambdaSymbol.Parameters, newLambdaSymbol.Parameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingLambdaParameters, newLambda); hasSignatureErrors = true; } else if (!ReturnTypesEquivalent(oldLambdaSymbol, newLambdaSymbol, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingLambdaReturnType, newLambda); hasSignatureErrors = true; } else if (!TypeParametersEquivalent(oldLambdaSymbol.TypeParameters, newLambdaSymbol.TypeParameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingTypeParameters, newLambda); hasSignatureErrors = true; } if (hasSignatureErrors) { return; } // custom attributes ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol, newLambdaSymbol, newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); for (var i = 0; i < oldLambdaSymbol.Parameters.Length; i++) { ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol.Parameters[i], newLambdaSymbol.Parameters[i], newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); } for (var i = 0; i < oldLambdaSymbol.TypeParameters.Length; i++) { ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol.TypeParameters[i], newLambdaSymbol.TypeParameters[i], newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); } } private static ITypeSymbol GetType(ISymbol localOrParameter) => localOrParameter.Kind switch { SymbolKind.Parameter => ((IParameterSymbol)localOrParameter).Type, SymbolKind.Local => ((ILocalSymbol)localOrParameter).Type, _ => throw ExceptionUtilities.UnexpectedValue(localOrParameter.Kind), }; private SyntaxNode GetCapturedVariableScope(ISymbol localOrParameter, SyntaxNode memberBody, CancellationToken cancellationToken) { Debug.Assert(localOrParameter.Kind != SymbolKind.RangeVariable); if (localOrParameter.Kind == SymbolKind.Parameter) { var member = localOrParameter.ContainingSymbol; // lambda parameters and C# constructor parameters are lifted to their own scope: if ((member as IMethodSymbol)?.MethodKind == MethodKind.AnonymousFunction || HasParameterClosureScope(member)) { var result = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); Debug.Assert(IsLambda(result)); return result; } return memberBody; } var node = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); while (true) { RoslynDebug.Assert(node is object); if (IsClosureScope(node)) { return node; } node = node.Parent; } } private static bool AreEquivalentClosureScopes(SyntaxNode oldScopeOpt, SyntaxNode newScopeOpt, IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) { if (oldScopeOpt == null || newScopeOpt == null) { return oldScopeOpt == newScopeOpt; } return reverseMap.TryGetValue(newScopeOpt, out var mappedScope) && mappedScope == oldScopeOpt; } #endregion #region State Machines private void ReportStateMachineRudeEdits( Compilation oldCompilation, ISymbol oldMember, SyntaxNode newBody, ArrayBuilder<RudeEditDiagnostic> diagnostics) { // Only methods, local functions and anonymous functions can be async/iterators machines, // but don't assume so to be resiliant against errors in code. if (oldMember is not IMethodSymbol oldMethod) { return; } var stateMachineAttributeQualifiedName = oldMethod.IsAsync ? "System.Runtime.CompilerServices.AsyncStateMachineAttribute" : "System.Runtime.CompilerServices.IteratorStateMachineAttribute"; // We assume that the attributes, if exist, are well formed. // If not an error will be reported during EnC delta emit. // Report rude edit if the type is not found in the compilation. // Consider: This diagnostic is cached in the document analysis, // so it could happen that the attribute type is added later to // the compilation and we continue to report the diagnostic. // We could report rude edit when adding these types or flush all // (or specific) document caches. This is not a common scenario though, // since the attribute has been long defined in the BCL. if (oldCompilation.GetTypeByMetadataName(stateMachineAttributeQualifiedName) == null) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodMissingAttribute, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { stateMachineAttributeQualifiedName })); } } #endregion #endregion #region Helpers private static SyntaxNode? TryGetNode(SyntaxNode root, int position) => root.FullSpan.Contains(position) ? root.FindToken(position).Parent : null; internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SyntaxList<T> list) where T : SyntaxNode { foreach (var node in list) { nodes.Add(node); } } internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SeparatedSyntaxList<T>? list) where T : SyntaxNode { if (list.HasValue) { foreach (var node in list.Value) { nodes.Add(node); } } } private sealed class TypedConstantComparer : IEqualityComparer<TypedConstant> { public static TypedConstantComparer Instance = new TypedConstantComparer(); public bool Equals(TypedConstant x, TypedConstant y) => x.Kind.Equals(y.Kind) && x.IsNull.Equals(y.IsNull) && SymbolEquivalenceComparer.Instance.Equals(x.Type, y.Type) && x.Kind switch { TypedConstantKind.Array => x.Values.SequenceEqual(y.Values, TypedConstantComparer.Instance), _ => object.Equals(x.Value, y.Value) }; public int GetHashCode(TypedConstant obj) => obj.GetHashCode(); } private sealed class NamedArgumentComparer : IEqualityComparer<KeyValuePair<string, TypedConstant>> { public static NamedArgumentComparer Instance = new NamedArgumentComparer(); public bool Equals(KeyValuePair<string, TypedConstant> x, KeyValuePair<string, TypedConstant> y) => x.Key.Equals(y.Key) && TypedConstantComparer.Instance.Equals(x.Value, y.Value); public int GetHashCode(KeyValuePair<string, TypedConstant> obj) => obj.GetHashCode(); } #pragma warning disable format private static bool IsGlobalMain(ISymbol symbol) => symbol is IMethodSymbol { Name: WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, ContainingType.Name: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName }; #pragma warning restore format private static bool InGenericContext(ISymbol symbol, out bool isGenericMethod) { var current = symbol; while (true) { if (current is IMethodSymbol { Arity: > 0 }) { isGenericMethod = true; return true; } if (current is INamedTypeSymbol { Arity: > 0 }) { isGenericMethod = false; return true; } current = current.ContainingSymbol; if (current == null) { isGenericMethod = false; return false; } } } #endregion #region Testing internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly AbstractEditAndContinueAnalyzer _abstractEditAndContinueAnalyzer; public TestAccessor(AbstractEditAndContinueAnalyzer abstractEditAndContinueAnalyzer) => _abstractEditAndContinueAnalyzer = abstractEditAndContinueAnalyzer; internal void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) => _abstractEditAndContinueAnalyzer.ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); internal BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { return _abstractEditAndContinueAnalyzer.ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); } internal Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { return _abstractEditAndContinueAnalyzer.ComputeBodyMatch(oldBody, newBody, activeNodes, diagnostics, out oldHasStateMachineSuspensionPoint, out newHasStateMachineSuspensionPoint); } } #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.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal abstract class AbstractEditAndContinueAnalyzer : IEditAndContinueAnalyzer { internal const int DefaultStatementPart = 0; private const string CreateNewOnMetadataUpdateAttributeName = "CreateNewOnMetadataUpdateAttribute"; /// <summary> /// Contains enough information to determine whether two symbols have the same signature. /// </summary> private static readonly SymbolDisplayFormat s_unqualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private static readonly SymbolDisplayFormat s_fullyQualifiedMemberDisplayFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes); // used by tests to validate correct handlign of unexpected exceptions private readonly Action<SyntaxNode>? _testFaultInjector; protected AbstractEditAndContinueAnalyzer(Action<SyntaxNode>? testFaultInjector) { _testFaultInjector = testFaultInjector; } internal abstract bool ExperimentalFeaturesEnabled(SyntaxTree tree); /// <summary> /// Finds member declaration node(s) containing given <paramref name="node"/>. /// Specified <paramref name="node"/> may be either a node of the declaration body or an active node that belongs to the declaration. /// </summary> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// Note that in some cases the set of nodes of the declaration body may differ from the set of active nodes that /// belong to the declaration. For example, in <c>Dim a, b As New T</c> the sets for member <c>a</c> are /// { <c>New</c>, <c>T</c> } and { <c>a</c> }, respectively. /// /// May return multiple declarations if the specified <paramref name="node"/> belongs to multiple declarations, /// such as in VB <c>Dim a, b As New T</c> case when <paramref name="node"/> is e.g. <c>T</c>. /// </remarks> internal abstract bool TryFindMemberDeclaration(SyntaxNode? root, SyntaxNode node, out OneOrMany<SyntaxNode> declarations); /// <summary> /// If the specified node represents a member declaration returns a node that represents its body, /// i.e. a node used as the root of statement-level match. /// </summary> /// <param name="node">A node representing a declaration or a top-level edit node.</param> /// /// <returns> /// Returns null for nodes that don't represent declarations. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// If a member doesn't have a body (null is returned) it can't have associated active statements. /// /// Body does not need to cover all active statements that may be associated with the member. /// E.g. Body of a C# constructor is the method body block. Active statements may be placed on the base constructor call. /// Body of a VB field declaration with shared AsNew initializer is the New expression. Active statements might be placed on the field variables. /// <see cref="FindStatementAndPartner"/> has to account for such cases. /// </remarks> internal abstract SyntaxNode? TryGetDeclarationBody(SyntaxNode node); /// <summary> /// True if the specified <paramref name="declaration"/> node shares body with another declaration. /// </summary> internal abstract bool IsDeclarationWithSharedBody(SyntaxNode declaration); /// <summary> /// If the specified node represents a member declaration returns all tokens of the member declaration /// that might be covered by an active statement. /// </summary> /// <returns> /// Tokens covering all possible breakpoint spans associated with the member, /// or null if the specified node doesn't represent a member declaration or /// doesn't have a body that can contain active statements. /// </returns> /// <remarks> /// The implementation has to decide what kinds of nodes in top-level match relationship represent a declaration. /// Every member declaration must be represented by exactly one node, but not all nodes have to represent a declaration. /// /// TODO: consider implementing this via <see cref="GetActiveSpanEnvelope"/>. /// </remarks> internal abstract IEnumerable<SyntaxToken>? TryGetActiveTokens(SyntaxNode node); /// <summary> /// Returns a span that contains all possible breakpoint spans of the <paramref name="declaration"/> /// and no breakpoint spans that do not belong to the <paramref name="declaration"/>. /// /// Returns default if the declaration does not have any breakpoint spans. /// </summary> internal abstract (TextSpan envelope, TextSpan hole) GetActiveSpanEnvelope(SyntaxNode declaration); /// <summary> /// Returns an ancestor that encompasses all active and statement level /// nodes that belong to the member represented by <paramref name="bodyOrMatchRoot"/>. /// </summary> protected SyntaxNode? GetEncompassingAncestor(SyntaxNode? bodyOrMatchRoot) { if (bodyOrMatchRoot == null) { return null; } var root = GetEncompassingAncestorImpl(bodyOrMatchRoot); Debug.Assert(root.Span.Contains(bodyOrMatchRoot.Span)); return root; } protected abstract SyntaxNode GetEncompassingAncestorImpl(SyntaxNode bodyOrMatchRoot); /// <summary> /// Finds a statement at given span and a declaration body. /// Also returns the corresponding partner statement in <paramref name="partnerDeclarationBody"/>, if specified. /// </summary> /// <remarks> /// The declaration body node may not contain the <paramref name="span"/>. /// This happens when an active statement associated with the member is outside of its body /// (e.g. C# constructor, or VB <c>Dim a,b As New T</c>). /// If the position doesn't correspond to any statement uses the start of the <paramref name="declarationBody"/>. /// </remarks> protected abstract SyntaxNode FindStatementAndPartner(SyntaxNode declarationBody, TextSpan span, SyntaxNode? partnerDeclarationBody, out SyntaxNode? partner, out int statementPart); private SyntaxNode FindStatement(SyntaxNode declarationBody, TextSpan span, out int statementPart) => FindStatementAndPartner(declarationBody, span, null, out _, out statementPart); /// <summary> /// Maps <paramref name="leftNode"/> of a body of <paramref name="leftDeclaration"/> to corresponding body node /// of <paramref name="rightDeclaration"/>, assuming that the declaration bodies only differ in trivia. /// </summary> internal abstract SyntaxNode FindDeclarationBodyPartner(SyntaxNode leftDeclaration, SyntaxNode rightDeclaration, SyntaxNode leftNode); /// <summary> /// Returns a node that represents a body of a lambda containing specified <paramref name="node"/>, /// or null if the node isn't contained in a lambda. If a node is returned it must uniquely represent the lambda, /// i.e. be no two distinct nodes may represent the same lambda. /// </summary> protected abstract SyntaxNode? FindEnclosingLambdaBody(SyntaxNode? container, SyntaxNode node); /// <summary> /// Given a node that represents a lambda body returns all nodes of the body in a syntax list. /// </summary> /// <remarks> /// Note that VB lambda bodies are represented by a lambda header and that some lambda bodies share /// their parent nodes with other bodies (e.g. join clause expressions). /// </remarks> protected abstract IEnumerable<SyntaxNode> GetLambdaBodyExpressionsAndStatements(SyntaxNode lambdaBody); protected abstract SyntaxNode? TryGetPartnerLambdaBody(SyntaxNode oldBody, SyntaxNode newLambda); protected abstract Match<SyntaxNode> ComputeTopLevelMatch(SyntaxNode oldCompilationUnit, SyntaxNode newCompilationUnit); protected abstract Match<SyntaxNode> ComputeBodyMatch(SyntaxNode oldBody, SyntaxNode newBody, IEnumerable<KeyValuePair<SyntaxNode, SyntaxNode>>? knownMatches); protected abstract Match<SyntaxNode> ComputeTopLevelDeclarationMatch(SyntaxNode oldDeclaration, SyntaxNode newDeclaration); protected abstract IEnumerable<SequenceEdit> GetSyntaxSequenceEdits(ImmutableArray<SyntaxNode> oldNodes, ImmutableArray<SyntaxNode> newNodes); /// <summary> /// Matches old active statement to new active statement without constructing full method body match. /// This is needed for active statements that are outside of method body, like constructor initializer. /// </summary> protected abstract bool TryMatchActiveStatement( SyntaxNode oldStatement, int statementPart, SyntaxNode oldBody, SyntaxNode newBody, [NotNullWhen(true)] out SyntaxNode? newStatement); protected abstract bool TryGetEnclosingBreakpointSpan(SyntaxNode root, int position, out TextSpan span); /// <summary> /// Get the active span that corresponds to specified node (or its part). /// </summary> /// <returns> /// True if the node has an active span associated with it, false otherwise. /// </returns> protected abstract bool TryGetActiveSpan(SyntaxNode node, int statementPart, int minLength, out TextSpan span); /// <summary> /// Yields potential active statements around the specified active statement /// starting with siblings following the statement, then preceding the statement, follows with its parent, its following siblings, etc. /// </summary> /// <returns> /// Pairs of (node, statement part), or (node, -1) indicating there is no logical following statement. /// The enumeration continues until the root is reached. /// </returns> protected abstract IEnumerable<(SyntaxNode statement, int statementPart)> EnumerateNearStatements(SyntaxNode statement); protected abstract bool StatementLabelEquals(SyntaxNode node1, SyntaxNode node2); /// <summary> /// True if both nodes represent the same kind of suspension point /// (await expression, await foreach statement, await using declarator, yield return, yield break). /// </summary> protected virtual bool StateMachineSuspensionPointKindEquals(SyntaxNode suspensionPoint1, SyntaxNode suspensionPoint2) => suspensionPoint1.RawKind == suspensionPoint2.RawKind; /// <summary> /// Determines if two syntax nodes are the same, disregarding trivia differences. /// </summary> protected abstract bool AreEquivalent(SyntaxNode left, SyntaxNode right); /// <summary> /// Returns true if the code emitted for the old active statement part (<paramref name="statementPart"/> of <paramref name="oldStatement"/>) /// is the same as the code emitted for the corresponding new active statement part (<paramref name="statementPart"/> of <paramref name="newStatement"/>). /// </summary> /// <remarks> /// A rude edit is reported if an active statement is changed and this method returns true. /// </remarks> protected abstract bool AreEquivalentActiveStatements(SyntaxNode oldStatement, SyntaxNode newStatement, int statementPart); protected abstract TextSpan GetGlobalStatementDiagnosticSpan(SyntaxNode node); /// <summary> /// Returns all symbols associated with an edit and an actual edit kind, which may be different then the specified one. /// Returns an empty set if the edit is not associated with any symbols. /// </summary> protected abstract OneOrMany<(ISymbol? oldSymbol, ISymbol? newSymbol, EditKind editKind)> GetSymbolEdits( EditKind editKind, SyntaxNode? oldNode, SyntaxNode? newNode, SemanticModel? oldModel, SemanticModel newModel, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, CancellationToken cancellationToken); /// <summary> /// Analyzes data flow in the member body represented by the specified node and returns all captured variables and parameters (including "this"). /// If the body is a field/property initializer analyzes the initializer expression only. /// </summary> protected abstract ImmutableArray<ISymbol> GetCapturedVariables(SemanticModel model, SyntaxNode memberBody); /// <summary> /// Enumerates all use sites of a specified variable within the specified syntax subtrees. /// </summary> protected abstract IEnumerable<SyntaxNode> GetVariableUseSites(IEnumerable<SyntaxNode> roots, ISymbol localOrParameter, SemanticModel model, CancellationToken cancellationToken); protected abstract bool AreHandledEventsEqual(IMethodSymbol oldMethod, IMethodSymbol newMethod); // diagnostic spans: protected abstract TextSpan? TryGetDiagnosticSpan(SyntaxNode node, EditKind editKind); internal TextSpan GetDiagnosticSpan(SyntaxNode node, EditKind editKind) => TryGetDiagnosticSpan(node, editKind) ?? node.Span; protected virtual TextSpan GetBodyDiagnosticSpan(SyntaxNode node, EditKind editKind) { var current = node.Parent; while (true) { if (current == null) { return node.Span; } var span = TryGetDiagnosticSpan(current, editKind); if (span != null) { return span.Value; } current = current.Parent; } } internal abstract TextSpan GetLambdaParameterDiagnosticSpan(SyntaxNode lambda, int ordinal); // display names: internal string GetDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) => TryGetDisplayName(node, editKind) ?? throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); internal string GetDisplayName(ISymbol symbol) => symbol.Kind switch { SymbolKind.Event => FeaturesResources.event_, SymbolKind.Field => GetDisplayName((IFieldSymbol)symbol), SymbolKind.Method => GetDisplayName((IMethodSymbol)symbol), SymbolKind.NamedType => GetDisplayName((INamedTypeSymbol)symbol), SymbolKind.Parameter => FeaturesResources.parameter, SymbolKind.Property => GetDisplayName((IPropertySymbol)symbol), SymbolKind.TypeParameter => FeaturesResources.type_parameter, _ => throw ExceptionUtilities.UnexpectedValue(symbol.Kind) }; internal virtual string GetDisplayName(IPropertySymbol symbol) => FeaturesResources.property_; internal virtual string GetDisplayName(INamedTypeSymbol symbol) => symbol.TypeKind switch { TypeKind.Class => FeaturesResources.class_, TypeKind.Interface => FeaturesResources.interface_, TypeKind.Delegate => FeaturesResources.delegate_, TypeKind.Enum => FeaturesResources.enum_, TypeKind.TypeParameter => FeaturesResources.type_parameter, _ => FeaturesResources.type, }; internal virtual string GetDisplayName(IFieldSymbol symbol) => symbol.IsConst ? ((symbol.ContainingType.TypeKind == TypeKind.Enum) ? FeaturesResources.enum_value : FeaturesResources.const_field) : FeaturesResources.field; internal virtual string GetDisplayName(IMethodSymbol symbol) => symbol.MethodKind switch { MethodKind.Constructor => FeaturesResources.constructor, MethodKind.PropertyGet or MethodKind.PropertySet => FeaturesResources.property_accessor, MethodKind.EventAdd or MethodKind.EventRaise or MethodKind.EventRemove => FeaturesResources.event_accessor, MethodKind.BuiltinOperator or MethodKind.UserDefinedOperator or MethodKind.Conversion => FeaturesResources.operator_, _ => FeaturesResources.method, }; /// <summary> /// Returns the display name of an ancestor node that contains the specified node and has a display name. /// </summary> protected virtual string GetBodyDisplayName(SyntaxNode node, EditKind editKind = EditKind.Update) { var current = node.Parent; while (true) { if (current == null) { throw ExceptionUtilities.UnexpectedValue(node.GetType().Name); } var displayName = TryGetDisplayName(current, editKind); if (displayName != null) { return displayName; } current = current.Parent; } } protected abstract string? TryGetDisplayName(SyntaxNode node, EditKind editKind); protected virtual string GetSuspensionPointDisplayName(SyntaxNode node, EditKind editKind) => GetDisplayName(node, editKind); protected abstract string LineDirectiveKeyword { get; } protected abstract ushort LineDirectiveSyntaxKind { get; } protected abstract SymbolDisplayFormat ErrorDisplayFormat { get; } protected abstract List<SyntaxNode> GetExceptionHandlingAncestors(SyntaxNode node, bool isNonLeaf); protected abstract void GetStateMachineInfo(SyntaxNode body, out ImmutableArray<SyntaxNode> suspensionPoints, out StateMachineKinds kinds); protected abstract TextSpan GetExceptionHandlingRegion(SyntaxNode node, out bool coversAllChildren); protected abstract void ReportLocalFunctionsDeclarationRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> bodyMatch); internal abstract void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Edit<SyntaxNode> edit, Dictionary<SyntaxNode, EditKind> editMap); internal abstract void ReportEnclosingExceptionHandlingRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, IEnumerable<Edit<SyntaxNode>> exceptionHandlingEdits, SyntaxNode oldStatement, TextSpan newStatementSpan); internal abstract void ReportOtherRudeEditsAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode oldStatement, SyntaxNode newStatement, bool isNonLeaf); internal abstract void ReportMemberBodyUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newMember, TextSpan? span); internal abstract void ReportInsertedMemberSymbolRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newNode, bool insertingIntoExistingContainingType); internal abstract void ReportStateMachineSuspensionPointRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode); internal abstract bool IsLambda(SyntaxNode node); internal abstract bool IsInterfaceDeclaration(SyntaxNode node); internal abstract bool IsRecordDeclaration(SyntaxNode node); /// <summary> /// True if the node represents any form of a function definition nested in another function body (i.e. anonymous function, lambda, local function). /// </summary> internal abstract bool IsNestedFunction(SyntaxNode node); internal abstract bool IsLocalFunction(SyntaxNode node); internal abstract bool IsClosureScope(SyntaxNode node); internal abstract bool ContainsLambda(SyntaxNode declaration); internal abstract SyntaxNode GetLambda(SyntaxNode lambdaBody); internal abstract IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken); internal abstract SyntaxNode? GetContainingQueryExpression(SyntaxNode node); internal abstract bool QueryClauseLambdasTypeEquivalent(SemanticModel oldModel, SyntaxNode oldNode, SemanticModel newModel, SyntaxNode newNode, CancellationToken cancellationToken); /// <summary> /// Returns true if the parameters of the symbol are lifted into a scope that is different from the symbol's body. /// </summary> internal abstract bool HasParameterClosureScope(ISymbol member); /// <summary> /// Returns all lambda bodies of a node representing a lambda, /// or false if the node doesn't represent a lambda. /// </summary> /// <remarks> /// C# anonymous function expression and VB lambda expression both have a single body /// (in VB the body is the header of the lambda expression). /// /// Some lambda queries (group by, join by) have two bodies. /// </remarks> internal abstract bool TryGetLambdaBodies(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? body1, out SyntaxNode? body2); internal abstract bool IsStateMachineMethod(SyntaxNode declaration); /// <summary> /// Returns the type declaration that contains a specified <paramref name="node"/>. /// This can be class, struct, interface, record or enum declaration. /// </summary> internal abstract SyntaxNode? TryGetContainingTypeDeclaration(SyntaxNode node); /// <summary> /// Returns the declaration of /// - a property, indexer or event declaration whose accessor is the specified <paramref name="node"/>, /// - a method, an indexer or a type (delegate) if the <paramref name="node"/> is a parameter, /// - a method or an type if the <paramref name="node"/> is a type parameter. /// </summary> internal abstract bool TryGetAssociatedMemberDeclaration(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? declaration); internal abstract bool HasBackingField(SyntaxNode propertyDeclaration); /// <summary> /// Return true if the declaration is a field/property declaration with an initializer. /// Shall return false for enum members. /// </summary> internal abstract bool IsDeclarationWithInitializer(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a parameter that is part of a records primary constructor. /// </summary> internal abstract bool IsRecordPrimaryConstructorParameter(SyntaxNode declaration); /// <summary> /// Return true if the declaration is a property accessor for a property that represents one of the parameters in a records primary constructor. /// </summary> internal abstract bool IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(SyntaxNode declaration, INamedTypeSymbol newContainingType, out bool isFirstAccessor); /// <summary> /// Return true if the declaration is a constructor declaration to which field/property initializers are emitted. /// </summary> internal abstract bool IsConstructorWithMemberInitializers(SyntaxNode declaration); internal abstract bool IsPartial(INamedTypeSymbol type); internal abstract SyntaxNode EmptyCompilationUnit { get; } private static readonly SourceText s_emptySource = SourceText.From(""); #region Document Analysis public async Task<DocumentAnalysisResults> AnalyzeDocumentAsync( Project oldProject, AsyncLazy<ActiveStatementsMap> lazyOldActiveStatementMap, Document newDocument, ImmutableArray<LinePositionSpan> newActiveStatementSpans, AsyncLazy<EditAndContinueCapabilities> lazyCapabilities, CancellationToken cancellationToken) { DocumentAnalysisResults.Log.Write("Analyzing document {0}", newDocument.Name); Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newDocument.SupportsSyntaxTree); Debug.Assert(newDocument.SupportsSemanticModel); // assume changes until we determine there are none so that EnC is blocked on unexpected exception: var hasChanges = true; try { cancellationToken.ThrowIfCancellationRequested(); SyntaxTree? oldTree; SyntaxNode oldRoot; SourceText oldText; var oldDocument = await oldProject.GetDocumentAsync(newDocument.Id, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); if (oldDocument != null) { oldTree = await oldDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(oldTree); oldRoot = await oldTree.GetRootAsync(cancellationToken).ConfigureAwait(false); oldText = await oldDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); } else { oldTree = null; oldRoot = EmptyCompilationUnit; oldText = s_emptySource; } var newTree = await newDocument.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(newTree); // Changes in parse options might change the meaning of the code even if nothing else changed. // The IDE should disallow changing the options during debugging session. Debug.Assert(oldTree == null || oldTree.Options.Equals(newTree.Options)); var newRoot = await newTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var newText = await newDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); hasChanges = !oldText.ContentEquals(newText); _testFaultInjector?.Invoke(newRoot); cancellationToken.ThrowIfCancellationRequested(); // TODO: newTree.HasErrors? var syntaxDiagnostics = newRoot.GetDiagnostics(); var hasSyntaxError = syntaxDiagnostics.Any(d => d.Severity == DiagnosticSeverity.Error); if (hasSyntaxError) { // Bail, since we can't do syntax diffing on broken trees (it would not produce useful results anyways). // If we needed to do so for some reason, we'd need to harden the syntax tree comparers. DocumentAnalysisResults.Log.Write("{0}: syntax errors", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray<RudeEditDiagnostic>.Empty, hasChanges); } if (!hasChanges) { // The document might have been closed and reopened, which might have triggered analysis. // If the document is unchanged don't continue the analysis since // a) comparing texts is cheaper than diffing trees // b) we need to ignore errors in unchanged documents DocumentAnalysisResults.Log.Write("{0}: unchanged", newDocument.Name); return DocumentAnalysisResults.Unchanged(newDocument.Id); } // Disallow modification of a file with experimental features enabled. // These features may not be handled well by the analysis below. if (ExperimentalFeaturesEnabled(newTree)) { DocumentAnalysisResults.Log.Write("{0}: experimental features enabled", newDocument.Name); return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.ExperimentalFeaturesEnabled, default)), hasChanges); } var capabilities = await lazyCapabilities.GetValueAsync(cancellationToken).ConfigureAwait(false); var oldActiveStatementMap = await lazyOldActiveStatementMap.GetValueAsync(cancellationToken).ConfigureAwait(false); // If the document has changed at all, lets make sure Edit and Continue is supported if (!capabilities.HasFlag(EditAndContinueCapabilities.Baseline)) { return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create( new RudeEditDiagnostic(RudeEditKind.NotSupportedByRuntime, default)), hasChanges); } // We are in break state when there are no active statements. var inBreakState = !oldActiveStatementMap.IsEmpty; // We do calculate diffs even if there are semantic errors for the following reasons: // 1) We need to be able to find active spans in the new document. // If we didn't calculate them we would only rely on tracking spans (might be ok). // 2) If there are syntactic rude edits we'll report them faster without waiting for semantic analysis. // The user may fix them before they address all the semantic errors. using var _2 = ArrayBuilder<RudeEditDiagnostic>.GetInstance(out var diagnostics); cancellationToken.ThrowIfCancellationRequested(); var topMatch = ComputeTopLevelMatch(oldRoot, newRoot); var syntacticEdits = topMatch.GetTreeEdits(); var editMap = BuildEditMap(syntacticEdits); var hasRudeEdits = false; ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0} syntactic rude edits, first: '{1}'", diagnostics.Count, newDocument.FilePath); hasRudeEdits = true; } cancellationToken.ThrowIfCancellationRequested(); using var _3 = ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)>.GetInstance(out var triviaEdits); using var _4 = ArrayBuilder<SequencePointUpdates>.GetInstance(out var lineEdits); AnalyzeTrivia( topMatch, editMap, triviaEdits, lineEdits, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); var oldActiveStatements = (oldTree == null) ? ImmutableArray<UnmappedActiveStatement>.Empty : oldActiveStatementMap.GetOldActiveStatements(this, oldTree, oldText, oldRoot, cancellationToken); var newActiveStatements = ImmutableArray.CreateBuilder<ActiveStatement>(oldActiveStatements.Length); newActiveStatements.Count = oldActiveStatements.Length; var newExceptionRegions = ImmutableArray.CreateBuilder<ImmutableArray<SourceFileSpan>>(oldActiveStatements.Length); newExceptionRegions.Count = oldActiveStatements.Length; var semanticEdits = await AnalyzeSemanticsAsync( syntacticEdits, editMap, oldActiveStatements, newActiveStatementSpans, triviaEdits, oldProject, oldDocument, newDocument, newText, diagnostics, newActiveStatements, newExceptionRegions, capabilities, inBreakState, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); AnalyzeUnchangedActiveMemberBodies(diagnostics, syntacticEdits.Match, newText, oldActiveStatements, newActiveStatementSpans, newActiveStatements, newExceptionRegions, cancellationToken); Debug.Assert(newActiveStatements.All(a => a != null)); if (diagnostics.Count > 0 && !hasRudeEdits) { DocumentAnalysisResults.Log.Write("{0}@{1}: rude edit ({2} total)", newDocument.FilePath, diagnostics.First().Span.Start, diagnostics.Count); hasRudeEdits = true; } return new DocumentAnalysisResults( newDocument.Id, newActiveStatements.MoveToImmutable(), diagnostics.ToImmutable(), hasRudeEdits ? default : semanticEdits, hasRudeEdits ? default : newExceptionRegions.MoveToImmutable(), hasRudeEdits ? default : lineEdits.ToImmutable(), hasChanges: true, hasSyntaxErrors: false); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // The same behavior as if there was a syntax error - we are unable to analyze the document. // We expect OOM to be thrown during the analysis if the number of top-level entities is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. var diagnostic = (e is OutOfMemoryException) ? new RudeEditDiagnostic(RudeEditKind.SourceFileTooBig, span: default, arguments: new[] { newDocument.FilePath }) : new RudeEditDiagnostic(RudeEditKind.InternalError, span: default, arguments: new[] { newDocument.FilePath, e.ToString() }); // Report as "syntax error" - we can't analyze the document return DocumentAnalysisResults.SyntaxErrors(newDocument.Id, ImmutableArray.Create(diagnostic), hasChanges); } } private void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) { foreach (var edit in syntacticEdits.Edits) { ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits.Match, edit, editMap); } } /// <summary> /// Reports rude edits for a symbol that's been deleted in one location and inserted in another and the edit was not classified as /// <see cref="EditKind.Move"/> or <see cref="EditKind.Reorder"/>. /// The scenarios include moving a type declaration from one file to another and moving a member of a partial type from one partial declaration to another. /// </summary> internal virtual void ReportDeclarationInsertDeleteRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, SyntaxNode newNode, ISymbol oldSymbol, ISymbol newSymbol, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { // When a method is moved to a different declaration and its parameters are changed at the same time // the new method symbol key will not resolve to the old one since the parameters are different. // As a result we will report separate delete and insert rude edits. // // For delegates, however, the symbol key will resolve to the old type so we need to report // rude edits here. if (oldSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var oldDelegateInvoke } && newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newDelegateInvoke }) { if (!ParameterTypesEquivalent(oldDelegateInvoke.Parameters, newDelegateInvoke.Parameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingParameterTypes, newSymbol, newNode, cancellationToken); } } } internal static Dictionary<SyntaxNode, EditKind> BuildEditMap(EditScript<SyntaxNode> editScript) { var map = new Dictionary<SyntaxNode, EditKind>(editScript.Edits.Length); foreach (var edit in editScript.Edits) { // do not include reorder and move edits if (edit.Kind is EditKind.Delete or EditKind.Update) { map.Add(edit.OldNode, edit.Kind); } if (edit.Kind is EditKind.Insert or EditKind.Update) { map.Add(edit.NewNode, edit.Kind); } } return map; } #endregion #region Syntax Analysis private void AnalyzeUnchangedActiveMemberBodies( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> topMatch, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, [In, Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [In, Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(oldActiveStatements.Length == newExceptionRegions.Count); // Active statements in methods that were not updated // are not changed but their spans might have been. for (var i = 0; i < newActiveStatements.Count; i++) { if (newActiveStatements[i] == null) { Contract.ThrowIfFalse(newExceptionRegions[i].IsDefault); var oldStatementSpan = oldActiveStatements[i].UnmappedSpan; var node = TryGetNode(topMatch.OldRoot, oldStatementSpan.Start); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (node != null && TryFindMemberDeclaration(topMatch.OldRoot, node, out var oldMemberDeclarations)) { foreach (var oldMember in oldMemberDeclarations) { var hasPartner = topMatch.TryGetNewNode(oldMember, out var newMember); Contract.ThrowIfFalse(hasPartner); var oldBody = TryGetDeclarationBody(oldMember); var newBody = TryGetDeclarationBody(newMember); // Guard against invalid active statement spans (in case PDB was somehow out of sync with the source). if (oldBody == null || newBody == null) { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); continue; } var statementPart = -1; SyntaxNode? newStatement = null; // We seed the method body matching algorithm with tracking spans (unless they were deleted) // to get precise matching. if (TryGetTrackedStatement(newActiveStatementSpans, i, newText, newMember, newBody, out var trackedStatement, out var trackedStatementPart)) { // Adjust for active statements that cover more than the old member span. // For example, C# variable declarators that represent field initializers: // [|public int <<F = Expr()>>;|] var adjustedOldStatementStart = oldMember.FullSpan.Contains(oldStatementSpan.Start) ? oldStatementSpan.Start : oldMember.SpanStart; // The tracking span might have been moved outside of lambda. // It is not an error to move the statement - we just ignore it. var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldMember.FindToken(adjustedOldStatementStart).Parent!); var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, trackedStatement); if (oldEnclosingLambdaBody == newEnclosingLambdaBody) { newStatement = trackedStatement; statementPart = trackedStatementPart; } } if (newStatement == null) { Contract.ThrowIfFalse(statementPart == -1); FindStatementAndPartner(oldBody, oldStatementSpan, newBody, out newStatement, out statementPart); Contract.ThrowIfNull(newStatement); } if (diagnostics.Count == 0) { var ancestors = GetExceptionHandlingAncestors(newStatement, oldActiveStatements[i].Statement.IsNonLeaf); newExceptionRegions[i] = GetExceptionRegions(ancestors, newStatement.SyntaxTree, cancellationToken).Spans; } // Even though the body of the declaration haven't changed, // changes to its header might have caused the active span to become unavailable. // (e.g. In C# "const" was added to modifiers of a field with an initializer). var newStatementSpan = FindClosestActiveSpan(newStatement, statementPart); newActiveStatements[i] = GetActiveStatementWithSpan(oldActiveStatements[i], newBody.SyntaxTree, newStatementSpan, diagnostics, cancellationToken); } } else { DocumentAnalysisResults.Log.Write("Invalid active statement span: [{0}..{1})", oldStatementSpan.Start, oldStatementSpan.End); } // we were not able to determine the active statement location (PDB data might be invalid) if (newActiveStatements[i] == null) { newActiveStatements[i] = oldActiveStatements[i].Statement.WithSpan(default); newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } } } } internal readonly struct ActiveNode { public readonly int ActiveStatementIndex; public readonly SyntaxNode OldNode; public readonly SyntaxNode? NewTrackedNode; public readonly SyntaxNode? EnclosingLambdaBody; public readonly int StatementPart; public ActiveNode(int activeStatementIndex, SyntaxNode oldNode, SyntaxNode? enclosingLambdaBody, int statementPart, SyntaxNode? newTrackedNode) { ActiveStatementIndex = activeStatementIndex; OldNode = oldNode; NewTrackedNode = newTrackedNode; EnclosingLambdaBody = enclosingLambdaBody; StatementPart = statementPart; } } /// <summary> /// Information about an active and/or a matched lambda. /// </summary> internal readonly struct LambdaInfo { // non-null for an active lambda (lambda containing an active statement) public readonly List<int>? ActiveNodeIndices; // both fields are non-null for a matching lambda (lambda that exists in both old and new document): public readonly Match<SyntaxNode>? Match; public readonly SyntaxNode? NewBody; public LambdaInfo(List<int> activeNodeIndices) : this(activeNodeIndices, null, null) { } private LambdaInfo(List<int>? activeNodeIndices, Match<SyntaxNode>? match, SyntaxNode? newLambdaBody) { ActiveNodeIndices = activeNodeIndices; Match = match; NewBody = newLambdaBody; } public LambdaInfo WithMatch(Match<SyntaxNode> match, SyntaxNode newLambdaBody) => new(ActiveNodeIndices, match, newLambdaBody); } private void AnalyzeChangedMemberBody( SyntaxNode oldDeclaration, SyntaxNode newDeclaration, SyntaxNode oldBody, SyntaxNode? newBody, SemanticModel oldModel, SemanticModel newModel, ISymbol oldSymbol, ISymbol newSymbol, SourceText newText, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, EditAndContinueCapabilities capabilities, [Out] ImmutableArray<ActiveStatement>.Builder newActiveStatements, [Out] ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { Debug.Assert(!newActiveStatementSpans.IsDefault); Debug.Assert(newActiveStatementSpans.IsEmpty || oldActiveStatements.Length == newActiveStatementSpans.Length); Debug.Assert(oldActiveStatements.IsEmpty || oldActiveStatements.Length == newActiveStatements.Count); Debug.Assert(newActiveStatements.Count == newExceptionRegions.Count); syntaxMap = null; var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); if (newBody == null) { // The body has been deleted. var newSpan = FindClosestActiveSpan(newDeclaration, DefaultStatementPart); Debug.Assert(newSpan != default); foreach (var activeStatementIndex in activeStatementIndices) { // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). if (newActiveStatements[activeStatementIndex] != null) { Debug.Assert(IsDeclarationWithSharedBody(newDeclaration)); continue; } newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; } return; } try { ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, GetDiagnosticSpan(newDeclaration, EditKind.Update)); _testFaultInjector?.Invoke(newBody); // Populated with active lambdas and matched lambdas. // Unmatched non-active lambdas are not included. // { old-lambda-body -> info } Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas = null; // finds leaf nodes that correspond to the old active statements: using var _ = ArrayBuilder<ActiveNode>.GetInstance(out var activeNodes); foreach (var activeStatementIndex in activeStatementIndices) { var oldStatementSpan = oldActiveStatements[activeStatementIndex].UnmappedSpan; var oldStatementSyntax = FindStatement(oldBody, oldStatementSpan, out var statementPart); Contract.ThrowIfNull(oldStatementSyntax); var oldEnclosingLambdaBody = FindEnclosingLambdaBody(oldBody, oldStatementSyntax); if (oldEnclosingLambdaBody != null) { lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); if (!lazyActiveOrMatchedLambdas.TryGetValue(oldEnclosingLambdaBody, out var lambda)) { lambda = new LambdaInfo(new List<int>()); lazyActiveOrMatchedLambdas.Add(oldEnclosingLambdaBody, lambda); } lambda.ActiveNodeIndices!.Add(activeNodes.Count); } SyntaxNode? trackedNode = null; if (TryGetTrackedStatement(newActiveStatementSpans, activeStatementIndex, newText, newDeclaration, newBody, out var newStatementSyntax, out var _)) { var newEnclosingLambdaBody = FindEnclosingLambdaBody(newBody, newStatementSyntax); // The tracking span might have been moved outside of the lambda span. // It is not an error to move the statement - we just ignore it. if (oldEnclosingLambdaBody == newEnclosingLambdaBody && StatementLabelEquals(oldStatementSyntax, newStatementSyntax)) { trackedNode = newStatementSyntax; } } activeNodes.Add(new ActiveNode(activeStatementIndex, oldStatementSyntax, oldEnclosingLambdaBody, statementPart, trackedNode)); } var bodyMatch = ComputeBodyMatch(oldBody, newBody, activeNodes.Where(n => n.EnclosingLambdaBody == null).ToArray(), diagnostics, out var oldHasStateMachineSuspensionPoint, out var newHasStateMachineSuspensionPoint); var map = ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); if (oldHasStateMachineSuspensionPoint) { ReportStateMachineRudeEdits(oldModel.Compilation, oldSymbol, newBody, diagnostics); } else if (newHasStateMachineSuspensionPoint && !capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { // Adding a state machine, either for async or iterator, will require creating a new helper class // so is a rude edit if the runtime doesn't support it if (newSymbol is IMethodSymbol { IsAsync: true }) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodAsync, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } else { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.MakeMethodIterator, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); } } ReportLambdaAndClosureRudeEdits( oldModel, oldBody, newModel, newBody, newSymbol, lazyActiveOrMatchedLambdas, map, capabilities, diagnostics, out var newBodyHasLambdas, cancellationToken); // We need to provide syntax map to the compiler if // 1) The new member has a active statement // The values of local variables declared or synthesized in the method have to be preserved. // 2) The new member generates a state machine // In case the state machine is suspended we need to preserve variables. // 3) The new member contains lambdas // We need to map new lambdas in the method to the matching old ones. // If the old method has lambdas but the new one doesn't there is nothing to preserve. // 4) Constructor that emits initializers is updated. // We create syntax map even if it's not necessary: if any data member initializers are active/contain lambdas. // Since initializers are usually simple the map should not be large enough to make it worth optimizing it away. if (!activeNodes.IsEmpty() || newHasStateMachineSuspensionPoint || newBodyHasLambdas || IsConstructorWithMemberInitializers(newDeclaration) || IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration)) { syntaxMap = CreateSyntaxMap(map.Reverse); } foreach (var activeNode in activeNodes) { var activeStatementIndex = activeNode.ActiveStatementIndex; var hasMatching = false; var isNonLeaf = oldActiveStatements[activeStatementIndex].Statement.IsNonLeaf; var isPartiallyExecuted = (oldActiveStatements[activeStatementIndex].Statement.Flags & ActiveStatementFlags.PartiallyExecuted) != 0; var statementPart = activeNode.StatementPart; var oldStatementSyntax = activeNode.OldNode; var oldEnclosingLambdaBody = activeNode.EnclosingLambdaBody; newExceptionRegions[activeStatementIndex] = ImmutableArray<SourceFileSpan>.Empty; TextSpan newSpan; SyntaxNode? newStatementSyntax; Match<SyntaxNode>? match; if (oldEnclosingLambdaBody == null) { match = bodyMatch; hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldBody, newBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); var oldLambdaInfo = lazyActiveOrMatchedLambdas[oldEnclosingLambdaBody]; var newEnclosingLambdaBody = oldLambdaInfo.NewBody; match = oldLambdaInfo.Match; if (match != null) { RoslynDebug.Assert(newEnclosingLambdaBody != null); // matching lambda has body hasMatching = TryMatchActiveStatement(oldStatementSyntax, statementPart, oldEnclosingLambdaBody, newEnclosingLambdaBody, out newStatementSyntax) || match.TryGetNewNode(oldStatementSyntax, out newStatementSyntax); } else { // Lambda match is null if lambdas can't be matched, // in such case we won't have active statement matched either. hasMatching = false; newStatementSyntax = null; } } if (hasMatching) { RoslynDebug.Assert(newStatementSyntax != null); RoslynDebug.Assert(match != null); // The matching node doesn't produce sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. newSpan = FindClosestActiveSpan(newStatementSyntax, statementPart); if ((isNonLeaf || isPartiallyExecuted) && !AreEquivalentActiveStatements(oldStatementSyntax, newStatementSyntax, statementPart)) { // rude edit: non-leaf active statement changed diagnostics.Add(new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.ActiveStatementUpdate : RudeEditKind.PartiallyExecutedActiveStatementUpdate, newSpan)); } // other statements around active statement: ReportOtherRudeEditsAroundActiveStatement(diagnostics, match, oldStatementSyntax, newStatementSyntax, isNonLeaf); } else if (match == null) { RoslynDebug.Assert(oldEnclosingLambdaBody != null); RoslynDebug.Assert(lazyActiveOrMatchedLambdas != null); newSpan = GetDeletedNodeDiagnosticSpan(oldEnclosingLambdaBody, bodyMatch, lazyActiveOrMatchedLambdas); // Lambda containing the active statement can't be found in the new source. var oldLambda = GetLambda(oldEnclosingLambdaBody); diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.ActiveStatementLambdaRemoved, newSpan, oldLambda, new[] { GetDisplayName(oldLambda) })); } else { newSpan = GetDeletedNodeActiveSpan(match.Matches, oldStatementSyntax); if (isNonLeaf || isPartiallyExecuted) { // rude edit: internal active statement deleted diagnostics.Add( new RudeEditDiagnostic(isNonLeaf ? RudeEditKind.DeleteActiveStatement : RudeEditKind.PartiallyExecutedActiveStatementDelete, GetDeletedNodeDiagnosticSpan(match.Matches, oldStatementSyntax), arguments: new[] { FeaturesResources.code })); } } // exception handling around the statement: CalculateExceptionRegionsAroundActiveStatement( bodyMatch, oldStatementSyntax, newStatementSyntax, newSpan, activeStatementIndex, isNonLeaf, newExceptionRegions, diagnostics, cancellationToken); // We have already calculated the new location of this active statement when analyzing another member declaration. // This may only happen when two or more member declarations share the same body (VB AsNew clause). Debug.Assert(IsDeclarationWithSharedBody(newDeclaration) || newActiveStatements[activeStatementIndex] == null); Debug.Assert(newSpan != default); newActiveStatements[activeStatementIndex] = GetActiveStatementWithSpan(oldActiveStatements[activeStatementIndex], newDeclaration.SyntaxTree, newSpan, diagnostics, cancellationToken); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { // Set the new spans of active statements overlapping the method body to match the old spans. // Even though these might be now outside of the method body it's ok since we report a rude edit and don't allow to continue. foreach (var i in activeStatementIndices) { newActiveStatements[i] = oldActiveStatements[i].Statement; newExceptionRegions[i] = ImmutableArray<SourceFileSpan>.Empty; } // We expect OOM to be thrown during the analysis if the number of statements is too large. // In such case we report a rude edit for the document. If the host is actually running out of memory, // it might throw another OOM here or later on. diagnostics.Add(new RudeEditDiagnostic( (e is OutOfMemoryException) ? RudeEditKind.MemberBodyTooBig : RudeEditKind.MemberBodyInternalError, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, arguments: new[] { GetBodyDisplayName(newBody) })); } } private bool TryGetTrackedStatement(ImmutableArray<LinePositionSpan> activeStatementSpans, int index, SourceText text, SyntaxNode declaration, SyntaxNode body, [NotNullWhen(true)] out SyntaxNode? trackedStatement, out int trackedStatementPart) { trackedStatement = null; trackedStatementPart = -1; // Active statements are not tracked in this document (e.g. the file is closed). if (activeStatementSpans.IsEmpty) { return false; } var trackedLineSpan = activeStatementSpans[index]; if (trackedLineSpan == default) { return false; } var trackedSpan = text.Lines.GetTextSpan(trackedLineSpan); // The tracking span might have been deleted or moved outside of the member span. // It is not an error to move the statement - we just ignore it. // Consider: Instead of checking here, explicitly handle all cases when active statements can be outside of the body in FindStatement and // return false if the requested span is outside of the active envelope. var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (!envelope.Contains(trackedSpan) || hole.Contains(trackedSpan)) { return false; } trackedStatement = FindStatement(body, trackedSpan, out trackedStatementPart); return true; } private ActiveStatement GetActiveStatementWithSpan(UnmappedActiveStatement oldStatement, SyntaxTree newTree, TextSpan newSpan, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var mappedLineSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); if (mappedLineSpan.HasMappedPath && mappedLineSpan.Path != oldStatement.Statement.FileSpan.Path) { // changing the source file of an active statement diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, newSpan, LineDirectiveSyntaxKind, arguments: new[] { string.Format(FeaturesResources._0_directive, LineDirectiveKeyword) })); } return oldStatement.Statement.WithFileSpan(mappedLineSpan); } private void CalculateExceptionRegionsAroundActiveStatement( Match<SyntaxNode> bodyMatch, SyntaxNode oldStatementSyntax, SyntaxNode? newStatementSyntax, TextSpan newStatementSyntaxSpan, int ordinal, bool isNonLeaf, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { if (newStatementSyntax == null) { if (!bodyMatch.NewRoot.Span.Contains(newStatementSyntaxSpan.Start)) { return; } newStatementSyntax = bodyMatch.NewRoot.FindToken(newStatementSyntaxSpan.Start).Parent; Contract.ThrowIfNull(newStatementSyntax); } var oldAncestors = GetExceptionHandlingAncestors(oldStatementSyntax, isNonLeaf); var newAncestors = GetExceptionHandlingAncestors(newStatementSyntax, isNonLeaf); if (oldAncestors.Count > 0 || newAncestors.Count > 0) { var edits = bodyMatch.GetSequenceEdits(oldAncestors, newAncestors); ReportEnclosingExceptionHandlingRudeEdits(diagnostics, edits, oldStatementSyntax, newStatementSyntaxSpan); // Exception regions are not needed in presence of errors. if (diagnostics.Count == 0) { Debug.Assert(oldAncestors.Count == newAncestors.Count); newExceptionRegions[ordinal] = GetExceptionRegions(newAncestors, newStatementSyntax.SyntaxTree, cancellationToken).Spans; } } } /// <summary> /// Calculates a syntax map of the entire method body including all lambda bodies it contains (recursively). /// </summary> private BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { ArrayBuilder<Match<SyntaxNode>>? lambdaBodyMatches = null; var currentLambdaBodyMatch = -1; var currentBodyMatch = bodyMatch; while (true) { foreach (var (oldNode, newNode) in currentBodyMatch.Matches) { // Skip root, only enumerate body matches. if (oldNode == currentBodyMatch.OldRoot) { Debug.Assert(newNode == currentBodyMatch.NewRoot); continue; } if (TryGetLambdaBodies(oldNode, out var oldLambdaBody1, out var oldLambdaBody2)) { lambdaBodyMatches ??= ArrayBuilder<Match<SyntaxNode>>.GetInstance(); lazyActiveOrMatchedLambdas ??= new Dictionary<SyntaxNode, LambdaInfo>(); var newLambdaBody1 = TryGetPartnerLambdaBody(oldLambdaBody1, newNode); if (newLambdaBody1 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody1, newLambdaBody1, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } if (oldLambdaBody2 != null) { var newLambdaBody2 = TryGetPartnerLambdaBody(oldLambdaBody2, newNode); if (newLambdaBody2 != null) { lambdaBodyMatches.Add(ComputeLambdaBodyMatch(oldLambdaBody2, newLambdaBody2, activeNodes, lazyActiveOrMatchedLambdas, diagnostics)); } } } } currentLambdaBodyMatch++; if (lambdaBodyMatches == null || currentLambdaBodyMatch == lambdaBodyMatches.Count) { break; } currentBodyMatch = lambdaBodyMatches[currentLambdaBodyMatch]; } if (lambdaBodyMatches == null) { return BidirectionalMap<SyntaxNode>.FromMatch(bodyMatch); } var map = new Dictionary<SyntaxNode, SyntaxNode>(); var reverseMap = new Dictionary<SyntaxNode, SyntaxNode>(); // include all matches, including the root: map.AddRange(bodyMatch.Matches); reverseMap.AddRange(bodyMatch.ReverseMatches); foreach (var lambdaBodyMatch in lambdaBodyMatches) { foreach (var pair in lambdaBodyMatch.Matches) { if (!map.ContainsKey(pair.Key)) { map[pair.Key] = pair.Value; reverseMap[pair.Value] = pair.Key; } } } lambdaBodyMatches?.Free(); return new BidirectionalMap<SyntaxNode>(map, reverseMap); } private Match<SyntaxNode> ComputeLambdaBodyMatch( SyntaxNode oldLambdaBody, SyntaxNode newLambdaBody, IReadOnlyList<ActiveNode> activeNodes, [Out] Dictionary<SyntaxNode, LambdaInfo> activeOrMatchedLambdas, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics) { ActiveNode[]? activeNodesInLambda; if (activeOrMatchedLambdas.TryGetValue(oldLambdaBody, out var info)) { // Lambda may be matched but not be active. activeNodesInLambda = info.ActiveNodeIndices?.Select(i => activeNodes[i]).ToArray(); } else { // If the lambda body isn't in the map it doesn't have any active/tracked statements. activeNodesInLambda = null; info = new LambdaInfo(); } var lambdaBodyMatch = ComputeBodyMatch(oldLambdaBody, newLambdaBody, activeNodesInLambda ?? Array.Empty<ActiveNode>(), diagnostics, out _, out _); activeOrMatchedLambdas[oldLambdaBody] = info.WithMatch(lambdaBodyMatch, newLambdaBody); return lambdaBodyMatch; } private Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches = null; List<SequenceEdit>? lazyRudeEdits = null; GetStateMachineInfo(oldBody, out var oldStateMachineSuspensionPoints, out var oldStateMachineKinds); GetStateMachineInfo(newBody, out var newStateMachineSuspensionPoints, out var newStateMachineKinds); AddMatchingActiveNodes(ref lazyKnownMatches, activeNodes); // Consider following cases: // 1) Both old and new methods contain yields/awaits. // Map the old suspension points to new ones, report errors for added/deleted suspension points. // 2) The old method contains yields/awaits but the new doesn't. // Report rude edits for each deleted yield/await. // 3) The new method contains yields/awaits but the old doesn't. // a) If the method has active statements report rude edits for each inserted yield/await (insert "around" an active statement). // b) If the method has no active statements then the edit is valid, we don't need to calculate map. // 4) The old method is async/iterator, the new method is not and it contains an active statement. // Report rude edit since we can't remap IP from MoveNext to the kickoff method. // Note that iterators in VB don't need to contain yield, so this case is not covered by change in number of yields. var creatingStateMachineAroundActiveStatement = oldStateMachineSuspensionPoints.Length == 0 && newStateMachineSuspensionPoints.Length > 0 && activeNodes.Length > 0; oldHasStateMachineSuspensionPoint = oldStateMachineSuspensionPoints.Length > 0; newHasStateMachineSuspensionPoint = newStateMachineSuspensionPoints.Length > 0; if (oldStateMachineSuspensionPoints.Length > 0 || creatingStateMachineAroundActiveStatement) { AddMatchingStateMachineSuspensionPoints(ref lazyKnownMatches, ref lazyRudeEdits, oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); } var match = ComputeBodyMatch(oldBody, newBody, lazyKnownMatches); if (IsLocalFunction(match.OldRoot) && IsLocalFunction(match.NewRoot)) { ReportLocalFunctionsDeclarationRudeEdits(diagnostics, match); } if (lazyRudeEdits != null) { foreach (var rudeEdit in lazyRudeEdits) { if (rudeEdit.Kind == EditKind.Delete) { var deletedNode = oldStateMachineSuspensionPoints[rudeEdit.OldIndex]; ReportStateMachineSuspensionPointDeletedRudeEdit(diagnostics, match, deletedNode); } else { Debug.Assert(rudeEdit.Kind == EditKind.Insert); var insertedNode = newStateMachineSuspensionPoints[rudeEdit.NewIndex]; ReportStateMachineSuspensionPointInsertedRudeEdit(diagnostics, match, insertedNode, creatingStateMachineAroundActiveStatement); } } } else if (oldStateMachineSuspensionPoints.Length > 0) { Debug.Assert(oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length); for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { var oldNode = oldStateMachineSuspensionPoints[i]; var newNode = newStateMachineSuspensionPoints[i]; // changing yield return to yield break, await to await foreach, yield to await, etc. if (StateMachineSuspensionPointKindEquals(oldNode, newNode)) { Debug.Assert(StatementLabelEquals(oldNode, newNode)); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingStateMachineShape, newNode.Span, newNode, new[] { GetSuspensionPointDisplayName(oldNode, EditKind.Update), GetSuspensionPointDisplayName(newNode, EditKind.Update) })); } ReportStateMachineSuspensionPointRudeEdits(diagnostics, oldNode, newNode); } } else if (activeNodes.Length > 0) { // It is allowed to update a regular method to an async method or an iterator. // The only restriction is a presence of an active statement in the method body // since the debugger does not support remapping active statements to a different method. if (oldStateMachineKinds != newStateMachineKinds) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, GetBodyDiagnosticSpan(newBody, EditKind.Update))); } } // report removing async as rude: if (lazyRudeEdits == null) { if ((oldStateMachineKinds & StateMachineKinds.Async) != 0 && (newStateMachineKinds & StateMachineKinds.Async) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingFromAsynchronousToSynchronous, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } // VB supports iterator lambdas/methods without yields if ((oldStateMachineKinds & StateMachineKinds.Iterator) != 0 && (newStateMachineKinds & StateMachineKinds.Iterator) == 0) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ModifiersUpdate, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { GetBodyDisplayName(newBody) })); } } return match; } internal virtual void ReportStateMachineSuspensionPointDeletedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode deletedSuspensionPoint) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, GetDeletedNodeDiagnosticSpan(match.Matches, deletedSuspensionPoint), deletedSuspensionPoint, new[] { GetSuspensionPointDisplayName(deletedSuspensionPoint, EditKind.Delete) })); } internal virtual void ReportStateMachineSuspensionPointInsertedRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, SyntaxNode insertedSuspensionPoint, bool aroundActiveStatement) { diagnostics.Add(new RudeEditDiagnostic( aroundActiveStatement ? RudeEditKind.InsertAroundActiveStatement : RudeEditKind.Insert, GetDiagnosticSpan(insertedSuspensionPoint, EditKind.Insert), insertedSuspensionPoint, new[] { GetSuspensionPointDisplayName(insertedSuspensionPoint, EditKind.Insert) })); } private static void AddMatchingActiveNodes(ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, IEnumerable<ActiveNode> activeNodes) { // add nodes that are tracked by the editor buffer to known matches: foreach (var activeNode in activeNodes) { if (activeNode.NewTrackedNode != null) { lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); lazyKnownMatches.Add(KeyValuePairUtil.Create(activeNode.OldNode, activeNode.NewTrackedNode)); } } } private void AddMatchingStateMachineSuspensionPoints( ref List<KeyValuePair<SyntaxNode, SyntaxNode>>? lazyKnownMatches, ref List<SequenceEdit>? lazyRudeEdits, ImmutableArray<SyntaxNode> oldStateMachineSuspensionPoints, ImmutableArray<SyntaxNode> newStateMachineSuspensionPoints) { // State machine suspension points (yield statements, await expressions, await foreach loops, await using declarations) // determine the structure of the generated state machine. // Change of the SM structure is far more significant then changes of the value (arguments) of these nodes. // Hence we build the match such that these nodes are fixed. lazyKnownMatches ??= new List<KeyValuePair<SyntaxNode, SyntaxNode>>(); void AddMatch(ref List<KeyValuePair<SyntaxNode, SyntaxNode>> lazyKnownMatches, int oldIndex, int newIndex) { var oldNode = oldStateMachineSuspensionPoints[oldIndex]; var newNode = newStateMachineSuspensionPoints[newIndex]; if (StatementLabelEquals(oldNode, newNode)) { lazyKnownMatches.Add(KeyValuePairUtil.Create(oldNode, newNode)); } } if (oldStateMachineSuspensionPoints.Length == newStateMachineSuspensionPoints.Length) { for (var i = 0; i < oldStateMachineSuspensionPoints.Length; i++) { AddMatch(ref lazyKnownMatches, i, i); } } else { // use LCS to provide better errors (deletes, inserts and updates) var edits = GetSyntaxSequenceEdits(oldStateMachineSuspensionPoints, newStateMachineSuspensionPoints); foreach (var edit in edits) { var editKind = edit.Kind; if (editKind == EditKind.Update) { AddMatch(ref lazyKnownMatches, edit.OldIndex, edit.NewIndex); } else { lazyRudeEdits ??= new List<SequenceEdit>(); lazyRudeEdits.Add(edit); } } Debug.Assert(lazyRudeEdits != null); } } public ActiveStatementExceptionRegions GetExceptionRegions(SyntaxNode syntaxRoot, TextSpan unmappedActiveStatementSpan, bool isNonLeaf, CancellationToken cancellationToken) { var token = syntaxRoot.FindToken(unmappedActiveStatementSpan.Start); var ancestors = GetExceptionHandlingAncestors(token.Parent!, isNonLeaf); return GetExceptionRegions(ancestors, syntaxRoot.SyntaxTree, cancellationToken); } private ActiveStatementExceptionRegions GetExceptionRegions(List<SyntaxNode> exceptionHandlingAncestors, SyntaxTree tree, CancellationToken cancellationToken) { if (exceptionHandlingAncestors.Count == 0) { return new ActiveStatementExceptionRegions(ImmutableArray<SourceFileSpan>.Empty, isActiveStatementCovered: false); } var isCovered = false; using var _ = ArrayBuilder<SourceFileSpan>.GetInstance(out var result); for (var i = exceptionHandlingAncestors.Count - 1; i >= 0; i--) { var span = GetExceptionHandlingRegion(exceptionHandlingAncestors[i], out var coversAllChildren); // TODO: https://github.com/dotnet/roslyn/issues/52971 // 1) Check that the span doesn't cross #line pragmas with different file mappings. // 2) Check that the mapped path does not change and report rude edits if it does. result.Add(tree.GetMappedLineSpan(span, cancellationToken)); // Exception regions describe regions of code that can't be edited. // If the span covers all the children nodes we don't need to descend further. if (coversAllChildren) { isCovered = true; break; } } return new ActiveStatementExceptionRegions(result.ToImmutable(), isCovered); } private TextSpan GetDeletedNodeDiagnosticSpan(SyntaxNode deletedLambdaBody, Match<SyntaxNode> match, Dictionary<SyntaxNode, LambdaInfo> lambdaInfos) { var oldLambdaBody = deletedLambdaBody; while (true) { var oldParentLambdaBody = FindEnclosingLambdaBody(match.OldRoot, GetLambda(oldLambdaBody)); if (oldParentLambdaBody == null) { return GetDeletedNodeDiagnosticSpan(match.Matches, oldLambdaBody); } if (lambdaInfos.TryGetValue(oldParentLambdaBody, out var lambdaInfo) && lambdaInfo.Match != null) { return GetDeletedNodeDiagnosticSpan(lambdaInfo.Match.Matches, oldLambdaBody); } oldLambdaBody = oldParentLambdaBody; } } private TextSpan FindClosestActiveSpan(SyntaxNode statement, int statementPart) { if (TryGetActiveSpan(statement, statementPart, minLength: statement.Span.Length, out var span)) { return span; } // The node doesn't have sequence points. // E.g. "const" keyword is inserted into a local variable declaration with an initializer. foreach (var (node, part) in EnumerateNearStatements(statement)) { if (part == -1) { return node.Span; } if (TryGetActiveSpan(node, part, minLength: 0, out span)) { return span; } } // This might occur in cases where we report rude edit, so the exact location of the active span doesn't matter. // For example, when a method expression body is removed in C#. return statement.Span; } internal TextSpan GetDeletedNodeActiveSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { foreach (var (oldNode, part) in EnumerateNearStatements(deletedNode)) { if (part == -1) { break; } if (forwardMap.TryGetValue(oldNode, out var newNode)) { return FindClosestActiveSpan(newNode, part); } } return GetDeletedNodeDiagnosticSpan(forwardMap, deletedNode); } internal TextSpan GetDeletedNodeDiagnosticSpan(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode deletedNode) { var hasAncestor = TryGetMatchingAncestor(forwardMap, deletedNode, out var newAncestor); RoslynDebug.Assert(hasAncestor && newAncestor != null); return GetDiagnosticSpan(newAncestor, EditKind.Delete); } /// <summary> /// Finds the inner-most ancestor of the specified node that has a matching node in the new tree. /// </summary> private static bool TryGetMatchingAncestor(IReadOnlyDictionary<SyntaxNode, SyntaxNode> forwardMap, SyntaxNode? oldNode, [NotNullWhen(true)] out SyntaxNode? newAncestor) { while (oldNode != null) { if (forwardMap.TryGetValue(oldNode, out newAncestor)) { return true; } oldNode = oldNode.Parent; } // only happens if original oldNode is a root, // otherwise we always find a matching ancestor pair (roots). newAncestor = null; return false; } private IEnumerable<int> GetOverlappingActiveStatements(SyntaxNode declaration, ImmutableArray<UnmappedActiveStatement> statements) { var (envelope, hole) = GetActiveSpanEnvelope(declaration); if (envelope == default) { yield break; } var range = ActiveStatementsMap.GetSpansStartingInSpan( envelope.Start, envelope.End, statements, startPositionComparer: (x, y) => x.UnmappedSpan.Start.CompareTo(y)); for (var i = range.Start.Value; i < range.End.Value; i++) { if (!hole.Contains(statements[i].UnmappedSpan.Start)) { yield return i; } } } protected static bool HasParentEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, Edit<SyntaxNode> edit) { SyntaxNode node; switch (edit.Kind) { case EditKind.Insert: node = edit.NewNode; break; case EditKind.Delete: node = edit.OldNode; break; default: return false; } return HasEdit(editMap, node.Parent, edit.Kind); } protected static bool HasEdit(IReadOnlyDictionary<SyntaxNode, EditKind> editMap, SyntaxNode? node, EditKind editKind) { return node is object && editMap.TryGetValue(node, out var parentEdit) && parentEdit == editKind; } #endregion #region Rude Edits around Active Statement protected void AddAroundActiveStatementRudeDiagnostic(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode? oldNode, SyntaxNode? newNode, TextSpan newActiveStatementSpan) { if (oldNode == null) { RoslynDebug.Assert(newNode != null); AddRudeInsertAroundActiveStatement(diagnostics, newNode); } else if (newNode == null) { RoslynDebug.Assert(oldNode != null); AddRudeDeleteAroundActiveStatement(diagnostics, oldNode, newActiveStatementSpan); } else { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } protected void AddRudeUpdateAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdateAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode, EditKind.Update) })); } protected void AddRudeInsertAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertAroundActiveStatement, GetDiagnosticSpan(newNode, EditKind.Insert), newNode, new[] { GetDisplayName(newNode, EditKind.Insert) })); } protected void AddRudeDeleteAroundActiveStatement(ArrayBuilder<RudeEditDiagnostic> diagnostics, SyntaxNode oldNode, TextSpan newActiveStatementSpan) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeleteAroundActiveStatement, newActiveStatementSpan, oldNode, new[] { GetDisplayName(oldNode, EditKind.Delete) })); } protected void ReportUnmatchedStatements<TSyntaxNode>( ArrayBuilder<RudeEditDiagnostic> diagnostics, Match<SyntaxNode> match, Func<SyntaxNode, bool> nodeSelector, SyntaxNode oldActiveStatement, SyntaxNode newActiveStatement, Func<TSyntaxNode, TSyntaxNode, bool> areEquivalent, Func<TSyntaxNode, TSyntaxNode, bool>? areSimilar) where TSyntaxNode : SyntaxNode { var newNodes = GetAncestors(GetEncompassingAncestor(match.NewRoot), newActiveStatement, nodeSelector); if (newNodes == null) { return; } var oldNodes = GetAncestors(GetEncompassingAncestor(match.OldRoot), oldActiveStatement, nodeSelector); int matchCount; if (oldNodes != null) { matchCount = MatchNodes(oldNodes, newNodes, diagnostics: null, match: match, comparer: areEquivalent); // Do another pass over the nodes to improve error messages. if (areSimilar != null && matchCount < Math.Min(oldNodes.Count, newNodes.Count)) { matchCount += MatchNodes(oldNodes, newNodes, diagnostics: diagnostics, match: null, comparer: areSimilar); } } else { matchCount = 0; } if (matchCount < newNodes.Count) { ReportRudeEditsAndInserts(oldNodes, newNodes, diagnostics); } } private void ReportRudeEditsAndInserts(List<SyntaxNode?>? oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics) { var oldNodeCount = (oldNodes != null) ? oldNodes.Count : 0; for (var i = 0; i < newNodes.Count; i++) { var newNode = newNodes[i]; if (newNode != null) { // Any difference can be expressed as insert, delete & insert, edit, or move & edit. // Heuristic: If the nesting levels of the old and new nodes are the same we report an edit. // Otherwise we report an insert. if (i < oldNodeCount && oldNodes![i] != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } else { AddRudeInsertAroundActiveStatement(diagnostics, newNode); } } } } private int MatchNodes<TSyntaxNode>( List<SyntaxNode?> oldNodes, List<SyntaxNode?> newNodes, ArrayBuilder<RudeEditDiagnostic>? diagnostics, Match<SyntaxNode>? match, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { var matchCount = 0; var oldIndex = 0; for (var newIndex = 0; newIndex < newNodes.Count; newIndex++) { var newNode = newNodes[newIndex]; if (newNode == null) { continue; } SyntaxNode? oldNode; while (oldIndex < oldNodes.Count) { oldNode = oldNodes[oldIndex]; if (oldNode != null) { break; } // node has already been matched with a previous new node: oldIndex++; } if (oldIndex == oldNodes.Count) { break; } var i = -1; if (match == null) { i = IndexOfEquivalent(newNode, oldNodes, oldIndex, comparer); } else if (match.TryGetOldNode(newNode, out var partner) && comparer((TSyntaxNode)partner, (TSyntaxNode)newNode)) { i = oldNodes.IndexOf(partner, oldIndex); } if (i >= 0) { // we have an update or an exact match: oldNodes[i] = null; newNodes[newIndex] = null; matchCount++; if (diagnostics != null) { AddRudeUpdateAroundActiveStatement(diagnostics, newNode); } } } return matchCount; } private static int IndexOfEquivalent<TSyntaxNode>(SyntaxNode newNode, List<SyntaxNode?> oldNodes, int startIndex, Func<TSyntaxNode, TSyntaxNode, bool> comparer) where TSyntaxNode : SyntaxNode { for (var i = startIndex; i < oldNodes.Count; i++) { var oldNode = oldNodes[i]; if (oldNode != null && comparer((TSyntaxNode)oldNode, (TSyntaxNode)newNode)) { return i; } } return -1; } private static List<SyntaxNode?>? GetAncestors(SyntaxNode? root, SyntaxNode node, Func<SyntaxNode, bool> nodeSelector) { List<SyntaxNode?>? list = null; var current = node; while (current is object && current != root) { if (nodeSelector(current)) { list ??= new List<SyntaxNode?>(); list.Add(current); } current = current.Parent; } list?.Reverse(); return list; } #endregion #region Trivia Analysis /// <summary> /// Top-level edit script does not contain edits for a member if only trivia changed in its body. /// It also does not reflect changes in line mapping directives. /// Members that are unchanged but their location in the file changes are not considered updated. /// This method calculates line and trivia edits for all these cases. /// /// The resulting line edits are grouped by mapped document path and sorted by <see cref="SourceLineUpdate.OldLine"/> in each group. /// </summary> private void AnalyzeTrivia( Match<SyntaxNode> topMatch, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, [Out] ArrayBuilder<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)> triviaEdits, [Out] ArrayBuilder<SequencePointUpdates> lineEdits, CancellationToken cancellationToken) { var oldTree = topMatch.OldRoot.SyntaxTree; var newTree = topMatch.NewRoot.SyntaxTree; // note: range [oldStartLine, oldEndLine] is end-inclusive using var _ = ArrayBuilder<(string filePath, int oldStartLine, int oldEndLine, int delta, SyntaxNode oldNode, SyntaxNode newNode)>.GetInstance(out var segments); foreach (var (oldNode, newNode) in topMatch.Matches) { cancellationToken.ThrowIfCancellationRequested(); if (editMap.ContainsKey(newNode)) { // Updated or inserted members will be (re)generated and don't need line edits. Debug.Assert(editMap[newNode] is EditKind.Update or EditKind.Insert); continue; } var newTokens = TryGetActiveTokens(newNode); if (newTokens == null) { continue; } // A (rude) edit could have been made that changes whether the node may contain active statements, // so although the nodes match they might not have the same active tokens. // E.g. field declaration changed to const field declaration. var oldTokens = TryGetActiveTokens(oldNode); if (oldTokens == null) { continue; } var newTokensEnum = newTokens.GetEnumerator(); var oldTokensEnum = oldTokens.GetEnumerator(); // We enumerate tokens of the body and split them into segments. // Each segment has sequence points mapped to the same file and also all lines the segment covers map to the same line delta. // The first token of a segment must be the first token that starts on the line. If the first segment token was in the middle line // the previous token on the same line would have different line delta and we wouldn't be able to map both of them at the same time. // All segments are included in the segments list regardless of their line delta (even when it's 0 - i.e. the lines did not change). // This is necessary as we need to detect collisions of multiple segments with different deltas later on. var lastNewToken = default(SyntaxToken); var lastOldStartLine = -1; var lastOldFilePath = (string?)null; var requiresUpdate = false; var firstSegmentIndex = segments.Count; var currentSegment = (path: (string?)null, oldStartLine: 0, delta: 0, firstOldNode: (SyntaxNode?)null, firstNewNode: (SyntaxNode?)null); var rudeEditSpan = default(TextSpan); // Check if the breakpoint span that covers the first node of the segment can be translated from the old to the new by adding a line delta. // If not we need to recompile the containing member since we are not able to produce line update for it. // The first node of the segment can be the first node on its line but the breakpoint span might start on the previous line. bool IsCurrentSegmentBreakpointSpanMappable() { var oldNode = currentSegment.firstOldNode; var newNode = currentSegment.firstNewNode; Contract.ThrowIfNull(oldNode); Contract.ThrowIfNull(newNode); // Some nodes (e.g. const local declaration) may not be covered by a breakpoint span. if (!TryGetEnclosingBreakpointSpan(oldNode, oldNode.SpanStart, out var oldBreakpointSpan) || !TryGetEnclosingBreakpointSpan(newNode, newNode.SpanStart, out var newBreakpointSpan)) { return true; } var oldMappedBreakpointSpan = (SourceFileSpan)oldTree.GetMappedLineSpan(oldBreakpointSpan, cancellationToken); var newMappedBreakpointSpan = (SourceFileSpan)newTree.GetMappedLineSpan(newBreakpointSpan, cancellationToken); if (oldMappedBreakpointSpan.AddLineDelta(currentSegment.delta) == newMappedBreakpointSpan) { return true; } rudeEditSpan = newBreakpointSpan; return false; } void AddCurrentSegment() { Debug.Assert(currentSegment.path != null); Debug.Assert(lastOldStartLine >= 0); // segment it ends on the line where the previous token starts (lastOldStartLine) segments.Add((currentSegment.path, currentSegment.oldStartLine, lastOldStartLine, currentSegment.delta, oldNode, newNode)); } bool oldHasToken; bool newHasToken; while (true) { oldHasToken = oldTokensEnum.MoveNext(); newHasToken = newTokensEnum.MoveNext(); // no update edit => tokens must match: Debug.Assert(oldHasToken == newHasToken); if (!oldHasToken) { if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; } else { // add last segment of the method body: AddCurrentSegment(); } break; } var oldSpan = oldTokensEnum.Current.Span; var newSpan = newTokensEnum.Current.Span; var oldMappedSpan = oldTree.GetMappedLineSpan(oldSpan, cancellationToken); var newMappedSpan = newTree.GetMappedLineSpan(newSpan, cancellationToken); var oldStartLine = oldMappedSpan.Span.Start.Line; var newStartLine = newMappedSpan.Span.Start.Line; var lineDelta = newStartLine - oldStartLine; // If any tokens in the method change their mapped column or mapped path the method must be recompiled // since the Debugger/SymReader does not support these updates. if (oldMappedSpan.Span.Start.Character != newMappedSpan.Span.Start.Character) { requiresUpdate = true; break; } if (currentSegment.path != oldMappedSpan.Path || currentSegment.delta != lineDelta) { // end of segment: if (currentSegment.path != null) { // Previous token start line is the same as this token start line, but the previous token line delta is not the same. // We can't therefore map the old start line to a new one using line delta since that would affect both tokens the same. if (lastOldStartLine == oldStartLine && string.Equals(lastOldFilePath, oldMappedSpan.Path)) { requiresUpdate = true; break; } if (!IsCurrentSegmentBreakpointSpanMappable()) { requiresUpdate = true; break; } // add current segment: AddCurrentSegment(); } // start new segment: currentSegment = (oldMappedSpan.Path, oldStartLine, lineDelta, oldTokensEnum.Current.Parent, newTokensEnum.Current.Parent); } lastNewToken = newTokensEnum.Current; lastOldStartLine = oldStartLine; lastOldFilePath = oldMappedSpan.Path; } // All tokens of a member body have been processed now. if (requiresUpdate) { // report the rude edit for the span of tokens that forced recompilation: if (rudeEditSpan.IsEmpty) { rudeEditSpan = TextSpan.FromBounds( lastNewToken.HasTrailingTrivia ? lastNewToken.Span.End : newTokensEnum.Current.FullSpan.Start, newTokensEnum.Current.SpanStart); } triviaEdits.Add((oldNode, newNode, rudeEditSpan)); // remove all segments added for the current member body: segments.Count = firstSegmentIndex; } } if (segments.Count == 0) { return; } // sort segments by file and then by start line: segments.Sort((x, y) => { var result = string.CompareOrdinal(x.filePath, y.filePath); return (result != 0) ? result : x.oldStartLine.CompareTo(y.oldStartLine); }); // Calculate line updates based on segments. // If two segments with different line deltas overlap we need to recompile all overlapping members except for the first one. // The debugger does not apply line deltas to recompiled methods and hence we can chose to recompile either of the overlapping segments // and apply line delta to the others. // // The line delta is applied to the start line of a sequence point. If start lines of two sequence points mapped to the same location // before the delta is applied then they will point to the same location after the delta is applied. But that wouldn't be correct // if two different mappings required applying different deltas and thus different locations. // This also applies when two methods are on the same line in the old version and they move by different deltas. using var _1 = ArrayBuilder<SourceLineUpdate>.GetInstance(out var documentLineEdits); var currentDocumentPath = segments[0].filePath; var previousOldEndLine = -1; var previousLineDelta = 0; foreach (var segment in segments) { if (segment.filePath != currentDocumentPath) { // store results for the previous document: if (documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutableAndClear())); } // switch to the next document: currentDocumentPath = segment.filePath; previousOldEndLine = -1; previousLineDelta = 0; } else if (segment.oldStartLine <= previousOldEndLine && segment.delta != previousLineDelta) { // The segment overlaps the previous one that has a different line delta. We need to recompile the method. // The debugger filters out line deltas that correspond to recompiled methods so we don't need to. triviaEdits.Add((segment.oldNode, segment.newNode, segment.newNode.Span)); continue; } // If the segment being added does not start on the line immediately following the previous segment end line // we need to insert another line update that resets the delta to 0 for the lines following the end line. if (documentLineEdits.Count > 0 && segment.oldStartLine > previousOldEndLine + 1) { Debug.Assert(previousOldEndLine >= 0); documentLineEdits.Add(CreateZeroDeltaSourceLineUpdate(previousOldEndLine + 1)); previousLineDelta = 0; } // Skip segment that doesn't change line numbers - the line edit would have no effect. // It was only added to facilitate detection of overlap with other segments. // Also skip the segment if the last line update has the same line delta as // consecutive same line deltas has the same effect as a single one. if (segment.delta != 0 && segment.delta != previousLineDelta) { documentLineEdits.Add(new SourceLineUpdate(segment.oldStartLine, segment.oldStartLine + segment.delta)); } previousOldEndLine = segment.oldEndLine; previousLineDelta = segment.delta; } if (currentDocumentPath != null && documentLineEdits.Count > 0) { lineEdits.Add(new SequencePointUpdates(currentDocumentPath, documentLineEdits.ToImmutable())); } } // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. internal static SourceLineUpdate CreateZeroDeltaSourceLineUpdate(int line) { var result = new SourceLineUpdate(); // TODO: Currently the constructor SourceLineUpdate does not allow update with zero delta. // Workaround until the debugger updates. unsafe { Unsafe.Write(&result, ((long)line << 32) | (long)line); } return result; } #endregion #region Semantic Analysis private sealed class AssemblyEqualityComparer : IEqualityComparer<IAssemblySymbol?> { public static readonly IEqualityComparer<IAssemblySymbol?> Instance = new AssemblyEqualityComparer(); public bool Equals(IAssemblySymbol? x, IAssemblySymbol? y) { // Types defined in old source assembly need to be treated as equivalent to types in the new source assembly, // provided that they only differ in their containing assemblies. // // The old source symbol has the same identity as the new one. // Two distinct assembly symbols that are referenced by the compilations have to have distinct identities. // If the compilation has two metadata references whose identities unify the compiler de-dups them and only creates // a single PE symbol. Thus comparing assemblies by identity partitions them so that each partition // contains assemblies that originated from the same Gen0 assembly. return Equals(x?.Identity, y?.Identity); } public int GetHashCode(IAssemblySymbol? obj) => obj?.Identity.GetHashCode() ?? 0; } // Ignore tuple element changes, nullability and dynamic. These type changes do not affect runtime type. // They only affect custom attributes emitted on the members - all runtimes are expected to accept // custom attribute updates in metadata deltas, even if they do not have any observable effect. private static readonly SymbolEquivalenceComparer s_runtimeSymbolEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: false, ignoreNullableAnnotations: true); private static readonly SymbolEquivalenceComparer s_exactSymbolEqualityComparer = new( AssemblyEqualityComparer.Instance, distinguishRefFromOut: true, tupleNamesMustMatch: true, ignoreNullableAnnotations: false); protected static bool SymbolsEquivalent(ISymbol oldSymbol, ISymbol newSymbol) => s_exactSymbolEqualityComparer.Equals(oldSymbol, newSymbol); protected static bool SignaturesEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ITypeSymbol oldReturnType, ImmutableArray<IParameterSymbol> newParameters, ITypeSymbol newReturnType) => ParameterTypesEquivalent(oldParameters, newParameters, exact: false) && s_runtimeSymbolEqualityComparer.Equals(oldReturnType, newReturnType); // TODO: should check ref, ref readonly, custom mods protected static bool ParameterTypesEquivalent(ImmutableArray<IParameterSymbol> oldParameters, ImmutableArray<IParameterSymbol> newParameters, bool exact) => oldParameters.SequenceEqual(newParameters, exact, (oldParameter, newParameter, exact) => ParameterTypesEquivalent(oldParameter, newParameter, exact)); protected static bool CustomModifiersEquivalent(CustomModifier oldModifier, CustomModifier newModifier, bool exact) => oldModifier.IsOptional == newModifier.IsOptional && TypesEquivalent(oldModifier.Modifier, newModifier.Modifier, exact); protected static bool CustomModifiersEquivalent(ImmutableArray<CustomModifier> oldModifiers, ImmutableArray<CustomModifier> newModifiers, bool exact) => oldModifiers.SequenceEqual(newModifiers, exact, (x, y, exact) => CustomModifiersEquivalent(x, y, exact)); protected static bool ReturnTypesEquivalent(IMethodSymbol oldMethod, IMethodSymbol newMethod, bool exact) => oldMethod.ReturnsByRef == newMethod.ReturnsByRef && oldMethod.ReturnsByRefReadonly == newMethod.ReturnsByRefReadonly && CustomModifiersEquivalent(oldMethod.ReturnTypeCustomModifiers, newMethod.ReturnTypeCustomModifiers, exact) && CustomModifiersEquivalent(oldMethod.RefCustomModifiers, newMethod.RefCustomModifiers, exact) && TypesEquivalent(oldMethod.ReturnType, newMethod.ReturnType, exact); protected static bool ReturnTypesEquivalent(IPropertySymbol oldProperty, IPropertySymbol newProperty, bool exact) => oldProperty.ReturnsByRef == newProperty.ReturnsByRef && oldProperty.ReturnsByRefReadonly == newProperty.ReturnsByRefReadonly && CustomModifiersEquivalent(oldProperty.TypeCustomModifiers, newProperty.TypeCustomModifiers, exact) && CustomModifiersEquivalent(oldProperty.RefCustomModifiers, newProperty.RefCustomModifiers, exact) && TypesEquivalent(oldProperty.Type, newProperty.Type, exact); protected static bool ReturnTypesEquivalent(IEventSymbol oldEvent, IEventSymbol newEvent, bool exact) => TypesEquivalent(oldEvent.Type, newEvent.Type, exact); // Note: SignatureTypeEquivalenceComparer compares dynamic and object the same. protected static bool TypesEquivalent(ITypeSymbol? oldType, ITypeSymbol? newType, bool exact) => (exact ? s_exactSymbolEqualityComparer : (IEqualityComparer<ITypeSymbol?>)s_runtimeSymbolEqualityComparer.SignatureTypeEquivalenceComparer).Equals(oldType, newType); protected static bool TypesEquivalent<T>(ImmutableArray<T> oldTypes, ImmutableArray<T> newTypes, bool exact) where T : ITypeSymbol => oldTypes.SequenceEqual(newTypes, exact, (x, y, exact) => TypesEquivalent(x, y, exact)); protected static bool ParameterTypesEquivalent(IParameterSymbol oldParameter, IParameterSymbol newParameter, bool exact) => (exact ? s_exactSymbolEqualityComparer : s_runtimeSymbolEqualityComparer).ParameterEquivalenceComparer.Equals(oldParameter, newParameter); protected static bool TypeParameterConstraintsEquivalent(ITypeParameterSymbol oldParameter, ITypeParameterSymbol newParameter, bool exact) => TypesEquivalent(oldParameter.ConstraintTypes, newParameter.ConstraintTypes, exact) && oldParameter.HasReferenceTypeConstraint == newParameter.HasReferenceTypeConstraint && oldParameter.HasValueTypeConstraint == newParameter.HasValueTypeConstraint && oldParameter.HasConstructorConstraint == newParameter.HasConstructorConstraint && oldParameter.HasNotNullConstraint == newParameter.HasNotNullConstraint && oldParameter.HasUnmanagedTypeConstraint == newParameter.HasUnmanagedTypeConstraint && oldParameter.Variance == newParameter.Variance; protected static bool TypeParametersEquivalent(ImmutableArray<ITypeParameterSymbol> oldParameters, ImmutableArray<ITypeParameterSymbol> newParameters, bool exact) => oldParameters.SequenceEqual(newParameters, exact, (oldParameter, newParameter, exact) => oldParameter.Name == newParameter.Name && TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact)); protected static bool BaseTypesEquivalent(INamedTypeSymbol oldType, INamedTypeSymbol newType, bool exact) => TypesEquivalent(oldType.BaseType, newType.BaseType, exact) && TypesEquivalent(oldType.AllInterfaces, newType.AllInterfaces, exact); protected static bool MemberSignaturesEquivalent( ISymbol? oldMember, ISymbol? newMember, Func<ImmutableArray<IParameterSymbol>, ITypeSymbol, ImmutableArray<IParameterSymbol>, ITypeSymbol, bool>? signatureComparer = null) { if (oldMember == newMember) { return true; } if (oldMember == null || newMember == null || oldMember.Kind != newMember.Kind) { return false; } signatureComparer ??= SignaturesEquivalent; switch (oldMember.Kind) { case SymbolKind.Field: var oldField = (IFieldSymbol)oldMember; var newField = (IFieldSymbol)newMember; return signatureComparer(ImmutableArray<IParameterSymbol>.Empty, oldField.Type, ImmutableArray<IParameterSymbol>.Empty, newField.Type); case SymbolKind.Property: var oldProperty = (IPropertySymbol)oldMember; var newProperty = (IPropertySymbol)newMember; return signatureComparer(oldProperty.Parameters, oldProperty.Type, newProperty.Parameters, newProperty.Type); case SymbolKind.Method: var oldMethod = (IMethodSymbol)oldMember; var newMethod = (IMethodSymbol)newMember; return signatureComparer(oldMethod.Parameters, oldMethod.ReturnType, newMethod.Parameters, newMethod.ReturnType); default: throw ExceptionUtilities.UnexpectedValue(oldMember.Kind); } } private readonly struct ConstructorEdit { public readonly INamedTypeSymbol OldType; /// <summary> /// Contains syntax maps for all changed data member initializers or constructor declarations (of constructors emitting initializers) /// in the currently analyzed document. The key is the declaration of the member. /// </summary> public readonly Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> ChangedDeclarations; public ConstructorEdit(INamedTypeSymbol oldType) { OldType = oldType; ChangedDeclarations = new Dictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?>(); } } private async Task<ImmutableArray<SemanticEditInfo>> AnalyzeSemanticsAsync( EditScript<SyntaxNode> editScript, IReadOnlyDictionary<SyntaxNode, EditKind> editMap, ImmutableArray<UnmappedActiveStatement> oldActiveStatements, ImmutableArray<LinePositionSpan> newActiveStatementSpans, IReadOnlyList<(SyntaxNode OldNode, SyntaxNode NewNode, TextSpan DiagnosticSpan)> triviaEdits, Project oldProject, Document? oldDocument, Document newDocument, SourceText newText, ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<ActiveStatement>.Builder newActiveStatements, ImmutableArray<ImmutableArray<SourceFileSpan>>.Builder newExceptionRegions, EditAndContinueCapabilities capabilities, bool inBreakState, CancellationToken cancellationToken) { Debug.Assert(inBreakState || newActiveStatementSpans.IsEmpty); if (editScript.Edits.Length == 0 && triviaEdits.Count == 0) { return ImmutableArray<SemanticEditInfo>.Empty; } // { new type -> constructor update } PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits = null; PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits = null; var oldModel = (oldDocument != null) ? await oldDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false) : null; var newModel = await newDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldCompilation = oldModel?.Compilation ?? await oldProject.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var newCompilation = newModel.Compilation; using var _1 = PooledHashSet<ISymbol>.GetInstance(out var processedSymbols); using var _2 = ArrayBuilder<SemanticEditInfo>.GetInstance(out var semanticEdits); try { INamedTypeSymbol? lazyLayoutAttribute = null; foreach (var edit in editScript.Edits) { cancellationToken.ThrowIfCancellationRequested(); if (edit.Kind == EditKind.Move) { // Move is either a Rude Edit and already reported in syntax analysis, or has no semantic effect. // For example, in VB we allow move from field multi-declaration. // "Dim a, b As Integer" -> "Dim a As Integer" (update) and "Dim b As Integer" (move) continue; } if (edit.Kind == EditKind.Reorder) { // Currently we don't do any semantic checks for reordering // and we don't need to report them to the compiler either. // Consider: Currently symbol ordering changes are not reflected in metadata (Reflection will report original order). // Consider: Reordering of fields is not allowed since it changes the layout of the type. // This ordering should however not matter unless the type has explicit layout so we might want to allow it. // We do not check changes to the order if they occur across multiple documents (the containing type is partial). Debug.Assert(!IsDeclarationWithInitializer(edit.OldNode) && !IsDeclarationWithInitializer(edit.NewNode)); continue; } foreach (var symbolEdits in GetSymbolEdits(edit.Kind, edit.OldNode, edit.NewNode, oldModel, newModel, editMap, cancellationToken)) { Func<SyntaxNode, SyntaxNode?>? syntaxMap; SemanticEditKind editKind; var (oldSymbol, newSymbol, syntacticEditKind) = symbolEdits; var symbol = newSymbol ?? oldSymbol; Contract.ThrowIfNull(symbol); if (!processedSymbols.Add(symbol)) { continue; } var symbolKey = SymbolKey.Create(symbol, cancellationToken); // Ignore ambiguous resolution result - it may happen if there are semantic errors in the compilation. oldSymbol ??= symbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; newSymbol ??= symbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, edit.OldNode, edit.NewNode); // The syntax change implies an update of the associated symbol but the old/new symbol does not actually exist. // Treat the edit as Insert/Delete. This may happen e.g. when all C# global statements are removed, the first one is added or they are moved to another file. if (syntacticEditKind == EditKind.Update) { if (oldSymbol == null || oldDeclaration != null && oldDeclaration.SyntaxTree != oldModel?.SyntaxTree) { syntacticEditKind = EditKind.Insert; } else if (newSymbol == null || newDeclaration != null && newDeclaration.SyntaxTree != newModel.SyntaxTree) { syntacticEditKind = EditKind.Delete; } } if (!inBreakState) { // Delete/insert/update edit of a member of a reloadable type (including nested types) results in Replace edit of the containing type. // If a Delete edit is part of delete-insert operation (member moved to a different partial type declaration or to a different file) // skip producing Replace semantic edit for this Delete edit as one will be reported by the corresponding Insert edit. var oldContainingType = oldSymbol?.ContainingType; var newContainingType = newSymbol?.ContainingType; var containingType = newContainingType ?? oldContainingType; if (containingType != null && (syntacticEditKind != EditKind.Delete || newSymbol == null)) { var containingTypeSymbolKey = SymbolKey.Create(containingType, cancellationToken); oldContainingType ??= (INamedTypeSymbol?)containingTypeSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; newContainingType ??= (INamedTypeSymbol?)containingTypeSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (oldContainingType != null && newContainingType != null && IsReloadable(oldContainingType)) { if (processedSymbols.Add(newContainingType)) { if (capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, containingTypeSymbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldContainingType, newContainingType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newContainingType, newDeclaration, cancellationToken); } } continue; } } var oldType = oldSymbol as INamedTypeSymbol; var newType = newSymbol as INamedTypeSymbol; // Deleting a reloadable type is a rude edit, reported the same as for non-reloadable. // Adding a reloadable type is a standard type addition (TODO: unless added to a reloadable type?). // Making reloadable attribute non-reloadable results in a new version of the type that is // not reloadable but does not update the old version in-place. if (syntacticEditKind != EditKind.Delete && oldType != null && newType != null && IsReloadable(oldType)) { if (symbol == newType || processedSymbols.Add(newType)) { if (oldType.Name != newType.Name) { // https://github.com/dotnet/roslyn/issues/54886 ReportUpdateRudeEdit(diagnostics, RudeEditKind.Renamed, newType, newDeclaration, cancellationToken); } else if (oldType.Arity != newType.Arity) { // https://github.com/dotnet/roslyn/issues/54881 ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingTypeParameters, newType, newDeclaration, cancellationToken); } else if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newType, newDeclaration, cancellationToken); } else { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, symbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldType, newType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } continue; } } switch (syntacticEditKind) { case EditKind.Delete: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(oldDeclaration); var activeStatementIndices = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements); var hasActiveStatement = activeStatementIndices.Any(); // TODO: if the member isn't a field/property we should return empty span. // We need to adjust the tracking span design and UpdateUneditedSpans to account for such empty spans. if (hasActiveStatement) { var newSpan = IsDeclarationWithInitializer(oldDeclaration) ? GetDeletedNodeActiveSpan(editScript.Match.Matches, oldDeclaration) : GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); foreach (var index in activeStatementIndices) { Debug.Assert(newActiveStatements[index] is null); newActiveStatements[index] = GetActiveStatementWithSpan(oldActiveStatements[index], editScript.Match.NewRoot.SyntaxTree, newSpan, diagnostics, cancellationToken); newExceptionRegions[index] = ImmutableArray<SourceFileSpan>.Empty; } } syntaxMap = null; editKind = SemanticEditKind.Delete; // Check if the declaration has been moved from one document to another. if (newSymbol != null && !(newSymbol is IMethodSymbol newMethod && newMethod.IsPartialDefinition)) { // Symbol has actually not been deleted but rather moved to another document, another partial type declaration // or replaced with an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) // Report rude edit if the deleted code contains active statements. // TODO (https://github.com/dotnet/roslyn/issues/51177): // Only report rude edit when replacing member with an implicit one if it has an active statement. // We might be able to support moving active members but we would need to // 1) Move AnalyzeChangedMemberBody from Insert to Delete // 2) Handle active statements that moved to a different document in ActiveStatementTrackingService // 3) The debugger's ManagedActiveStatementUpdate might need another field indicating the source file path. if (hasActiveStatement) { ReportDeletedMemberRudeEdit(diagnostics, oldSymbol, newCompilation, RudeEditKind.DeleteActiveStatement, cancellationToken); continue; } if (!newSymbol.IsImplicitlyDeclared) { // Ignore the delete. The new symbol is explicitly declared and thus there will be an insert edit that will issue a semantic update. // Note that this could also be the case for deleting properties of records, but they will be handled when we see // their accessors below. continue; } if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(oldDeclaration, newSymbol.ContainingType, out var isFirst)) { // Defer a constructor edit to cover the property initializer changing DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // If there was no body deleted then we are done since the compiler generated property also has no body if (TryGetDeclarationBody(oldDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. // We only need to do this once though. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newSymbol.ContainingType, semanticEdits, cancellationToken); } } // If a constructor is deleted and replaced by an implicit one the update needs to aggregate updates to all data member initializers, // or if a property is deleted that is part of a records primary constructor, which is effectivelly moving from an explicit to implicit // initializer. if (IsConstructorWithMemberInitializers(oldDeclaration)) { processedSymbols.Remove(oldSymbol); DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration: null, syntaxMap, oldSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); continue; } // there is no insert edit for an implicit declaration, therefore we need to issue an update: editKind = SemanticEditKind.Update; } else { var diagnosticSpan = GetDeletedNodeDiagnosticSpan(editScript.Match.Matches, oldDeclaration); // If we got here for a global statement then the actual edit is a delete of the synthesized Main method if (IsGlobalMain(oldSymbol)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.Delete, diagnosticSpan, edit.OldNode, new[] { GetDisplayName(edit.OldNode, EditKind.Delete) })); continue; } // If the associated member declaration (accessor -> property/indexer/event, parameter -> method) has also been deleted skip // the delete of the symbol as it will be deleted by the delete of the associated member. // // Associated member declarations must be in the same document as the symbol, so we don't need to resolve their symbol. // In some cases the symbol even can't be resolved unambiguously. Consider e.g. resolving a method with its parameter deleted - // we wouldn't know which overload to resolve to. if (TryGetAssociatedMemberDeclaration(oldDeclaration, out var oldAssociatedMemberDeclaration)) { if (HasEdit(editMap, oldAssociatedMemberDeclaration, EditKind.Delete)) { continue; } } else if (oldSymbol.ContainingType != null) { // Check if the symbol being deleted is a member of a type that's also being deleted. // If so, skip the member deletion and only report the containing symbol deletion. var containingSymbolKey = SymbolKey.Create(oldSymbol.ContainingType, cancellationToken); var newContainingSymbol = containingSymbolKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContainingSymbol == null) { continue; } } // deleting symbol is not allowed diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Delete, diagnosticSpan, oldDeclaration, new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldDeclaration, EditKind.Delete), oldSymbol.ToDisplayString(diagnosticSpan.IsEmpty ? s_fullyQualifiedMemberDisplayFormat : s_unqualifiedMemberDisplayFormat)) })); continue; } } break; case EditKind.Insert: { Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(newDeclaration); syntaxMap = null; editKind = SemanticEditKind.Insert; INamedTypeSymbol? oldContainingType; var newContainingType = newSymbol.ContainingType; // Check if the declaration has been moved from one document to another. if (oldSymbol != null) { // Symbol has actually not been inserted but rather moved between documents or partial type declarations, // or is replacing an implicitly generated one (e.g. parameterless constructor, auto-generated record methods, etc.) oldContainingType = oldSymbol.ContainingType; if (oldSymbol.IsImplicitlyDeclared) { // If a user explicitly implements a member of a record then we want to issue an update, not an insert. if (oldSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfNull(oldDeclaration); ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol, capabilities, cancellationToken); if (IsPropertyAccessorDeclarationMatchingPrimaryConstructorParameter(newDeclaration, newContainingType, out var isFirst)) { // If there is no body declared we can skip it entirely because for a property accessor // it matches what the compiler would have previously implicitly implemented. if (TryGetDeclarationBody(newDeclaration) is null) { continue; } // If there was a body, then the backing field of the property will be affected so we // need to issue edits for the synthezied members. Only need to do it once. if (isFirst) { AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits, cancellationToken); } } editKind = SemanticEditKind.Update; } } else if (oldSymbol.DeclaringSyntaxReferences.Length == 1 && newSymbol.DeclaringSyntaxReferences.Length == 1) { Contract.ThrowIfNull(oldDeclaration); // Handles partial methods and explicitly implemented properties that implement positional parameters of records // We ignore partial method definition parts when processing edits (GetSymbolForEdit). // The only declaration in compilation without syntax errors that can have multiple declaring references is a type declaration. // We can therefore ignore any symbols that have more than one declaration. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // Compare the old declaration syntax of the symbol with its new declaration and report rude edits // if it changed in any way that's not allowed. ReportDeclarationInsertDeleteRudeEdits(diagnostics, oldDeclaration, newDeclaration, oldSymbol, newSymbol, capabilities, cancellationToken); var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { // The old symbol's declaration syntax may be located in a different document than the old version of the current document. var oldSyntaxDocument = oldProject.Solution.GetRequiredDocument(oldDeclaration.SyntaxTree); var oldSyntaxModel = await oldSyntaxDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var oldSyntaxText = await oldSyntaxDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); var newBody = TryGetDeclarationBody(newDeclaration); // Skip analysis of active statements. We already report rude edit for removal of code containing // active statements in the old declaration and don't currently support moving active statements. AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldSyntaxModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements: ImmutableArray<UnmappedActiveStatement>.Empty, newActiveStatementSpans: ImmutableArray<LinePositionSpan>.Empty, capabilities: capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isNewConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration); var isRecordPrimaryConstructorParameter = IsRecordPrimaryConstructorParameter(oldDeclaration); if (isNewConstructorWithMemberInitializers || isDeclarationWithInitializer || isRecordPrimaryConstructorParameter) { if (isNewConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isDeclarationWithInitializer) { AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } DeferConstructorEdit(oldSymbol.ContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } editKind = SemanticEditKind.Update; } else { editKind = SemanticEditKind.Update; } } else if (TryGetAssociatedMemberDeclaration(newDeclaration, out var newAssociatedMemberDeclaration) && HasEdit(editMap, newAssociatedMemberDeclaration, EditKind.Insert)) { // If the symbol is an accessor and the containing property/indexer/event declaration has also been inserted skip // the insert of the accessor as it will be inserted by the property/indexer/event. continue; } else if (newSymbol is IParameterSymbol || newSymbol is ITypeParameterSymbol) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.Insert, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); continue; } else if (newContainingType != null && !IsGlobalMain(newSymbol)) { // The edit actually adds a new symbol into an existing or a new type. var containingSymbolKey = SymbolKey.Create(newContainingType, cancellationToken); oldContainingType = containingSymbolKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol as INamedTypeSymbol; if (oldContainingType != null && !CanAddNewMember(newSymbol, capabilities)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } // Check rude edits for each member even if it is inserted into a new type. ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: oldContainingType != null); if (oldContainingType == null) { // Insertion of a new symbol into a new type. // We'll produce a single insert edit for the entire type. continue; } // Report rude edits for changes to data member changes of a type with an explicit layout. // We disallow moving a data member of a partial type with explicit layout even when it actually does not change the layout. // We could compare the exact order of the members but the scenario is unlikely to occur. ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newDeclaration, newModel, ref lazyLayoutAttribute); // If a property or field is added to a record then the implicit constructors change, // and we need to mark a number of other synthesized members as having changed. if (newSymbol is IPropertySymbol or IFieldSymbol && newContainingType.IsRecord) { DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); AddEditsForSynthesizedRecordMembers(newCompilation, newContainingType, semanticEdits, cancellationToken); } } else { // adds a new top-level type, or a global statement where none existed before, which is // therefore inserting the <Program>$ type Contract.ThrowIfFalse(newSymbol is INamedTypeSymbol || IsGlobalMain(newSymbol)); if (!capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newDeclaration, EditKind.Insert), newDeclaration, arguments: new[] { GetDisplayName(newDeclaration, EditKind.Insert) })); } oldContainingType = null; ReportInsertedMemberSymbolRudeEdits(diagnostics, newSymbol, newDeclaration, insertingIntoExistingContainingType: false); } var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); if (isConstructorWithMemberInitializers || IsDeclarationWithInitializer(newDeclaration)) { Contract.ThrowIfNull(newContainingType); Contract.ThrowIfNull(oldContainingType); // TODO (bug https://github.com/dotnet/roslyn/issues/2504) if (isConstructorWithMemberInitializers && editKind == SemanticEditKind.Insert && IsPartial(newContainingType) && HasMemberInitializerContainingLambda(oldContainingType, newSymbol.IsStatic, cancellationToken)) { // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); break; } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isConstructorWithMemberInitializers || editKind == SemanticEditKind.Update) { // Don't add a separate semantic edit. // Edits of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } // A semantic edit to create the field/property is gonna be added. Contract.ThrowIfFalse(editKind == SemanticEditKind.Insert); } } break; case EditKind.Update: { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); Contract.ThrowIfNull(oldSymbol); Contract.ThrowIfNull(newSymbol); editKind = SemanticEditKind.Update; syntaxMap = null; // Partial type declarations and their type parameters. if (oldSymbol.DeclaringSyntaxReferences.Length != 1 && newSymbol.DeclaringSyntaxReferences.Length != 1) { break; } Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldBody = TryGetDeclarationBody(oldDeclaration); if (oldBody != null) { var newBody = TryGetDeclarationBody(newDeclaration); AnalyzeChangedMemberBody( oldDeclaration, newDeclaration, oldBody, newBody, oldModel, newModel, oldSymbol, newSymbol, newText, oldActiveStatements, newActiveStatementSpans, capabilities, newActiveStatements, newExceptionRegions, diagnostics, out syntaxMap, cancellationToken); } // If a constructor changes from including initializers to not including initializers // we don't need to aggregate syntax map from all initializers for the constructor update semantic edit. var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(oldDeclaration) || IsDeclarationWithInitializer(newDeclaration); if (isConstructorWithMemberInitializers || isDeclarationWithInitializer) { if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } if (isDeclarationWithInitializer) { AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); } DeferConstructorEdit(oldSymbol.ContainingType, newSymbol.ContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } } break; default: throw ExceptionUtilities.UnexpectedValue(edit.Kind); } Contract.ThrowIfFalse(editKind is SemanticEditKind.Update or SemanticEditKind.Insert); if (editKind == SemanticEditKind.Update) { Contract.ThrowIfNull(oldSymbol); AnalyzeSymbolUpdate(oldSymbol, newSymbol, edit.NewNode, newCompilation, editScript.Match, capabilities, diagnostics, semanticEdits, syntaxMap, cancellationToken); if (newSymbol is INamedTypeSymbol or IFieldSymbol or IPropertySymbol or IEventSymbol or IParameterSymbol or ITypeParameterSymbol) { continue; } } semanticEdits.Add(new SemanticEditInfo(editKind, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } foreach (var (oldEditNode, newEditNode, diagnosticSpan) in triviaEdits) { Contract.ThrowIfNull(oldModel); Contract.ThrowIfNull(newModel); foreach (var (oldSymbol, newSymbol, editKind) in GetSymbolEdits(EditKind.Update, oldEditNode, newEditNode, oldModel, newModel, editMap, cancellationToken)) { // Trivia edits are only calculated for member bodies and each member has a symbol. Contract.ThrowIfNull(newSymbol); Contract.ThrowIfNull(oldSymbol); if (!processedSymbols.Add(newSymbol)) { // symbol already processed continue; } var (oldDeclaration, newDeclaration) = GetSymbolDeclarationNodes(oldSymbol, newSymbol, oldEditNode, newEditNode); Contract.ThrowIfNull(oldDeclaration); Contract.ThrowIfNull(newDeclaration); var oldContainingType = oldSymbol.ContainingType; var newContainingType = newSymbol.ContainingType; Contract.ThrowIfNull(oldContainingType); Contract.ThrowIfNull(newContainingType); if (IsReloadable(oldContainingType)) { if (processedSymbols.Add(newContainingType)) { if (capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition)) { var containingTypeSymbolKey = SymbolKey.Create(oldContainingType, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Replace, containingTypeSymbolKey, syntaxMap: null, syntaxMapTree: null, IsPartialEdit(oldContainingType, newContainingType, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime, newContainingType, newDeclaration, cancellationToken); } } continue; } // We need to provide syntax map to the compiler if the member is active (see member update above): var isActiveMember = GetOverlappingActiveStatements(oldDeclaration, oldActiveStatements).Any() || IsStateMachineMethod(oldDeclaration) || ContainsLambda(oldDeclaration); var syntaxMap = isActiveMember ? CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration) : null; // only trivia changed: Contract.ThrowIfFalse(IsConstructorWithMemberInitializers(oldDeclaration) == IsConstructorWithMemberInitializers(newDeclaration)); Contract.ThrowIfFalse(IsDeclarationWithInitializer(oldDeclaration) == IsDeclarationWithInitializer(newDeclaration)); var isConstructorWithMemberInitializers = IsConstructorWithMemberInitializers(newDeclaration); var isDeclarationWithInitializer = IsDeclarationWithInitializer(newDeclaration); if (isConstructorWithMemberInitializers || isDeclarationWithInitializer) { // TODO: only create syntax map if any field initializers are active/contain lambdas or this is a partial type syntaxMap ??= CreateSyntaxMapForEquivalentNodes(oldDeclaration, newDeclaration); if (isConstructorWithMemberInitializers) { processedSymbols.Remove(newSymbol); } DeferConstructorEdit(oldContainingType, newContainingType, newDeclaration, syntaxMap, newSymbol.IsStatic, ref instanceConstructorEdits, ref staticConstructorEdits); // Don't add a separate semantic edit. // Updates of data members with initializers and constructors that emit initializers will be aggregated and added later. continue; } ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, diagnosticSpan); // updating generic methods and types if (InGenericContext(oldSymbol, out var oldIsGenericMethod)) { var rudeEdit = oldIsGenericMethod ? RudeEditKind.GenericMethodTriviaUpdate : RudeEditKind.GenericTypeTriviaUpdate; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, diagnosticSpan, newEditNode, new[] { GetDisplayName(newEditNode) })); continue; } var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, editScript.Match.OldRoot.SyntaxTree, editScript.Match.NewRoot.SyntaxTree) ? symbolKey : null)); } } if (instanceConstructorEdits != null) { AddConstructorEdits( instanceConstructorEdits, editScript.Match, oldModel, oldCompilation, newCompilation, processedSymbols, capabilities, isStatic: false, semanticEdits, diagnostics, cancellationToken); } if (staticConstructorEdits != null) { AddConstructorEdits( staticConstructorEdits, editScript.Match, oldModel, oldCompilation, newCompilation, processedSymbols, capabilities, isStatic: true, semanticEdits, diagnostics, cancellationToken); } } finally { instanceConstructorEdits?.Free(); staticConstructorEdits?.Free(); } return semanticEdits.Distinct(SemanticEditInfoComparer.Instance).ToImmutableArray(); // If the symbol has a single declaring reference use its syntax node for further analysis. // Some syntax edits may not be directly associated with the declarations. // For example, in VB an update to AsNew clause of a multi-variable field declaration results in update to multiple symbols associated // with the variable declaration. But we need to analyse each symbol's modified identifier separately. (SyntaxNode? oldDeclaration, SyntaxNode? newDeclaration) GetSymbolDeclarationNodes(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxNode? oldNode, SyntaxNode? newNode) { return ( (oldSymbol != null && oldSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(oldSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : oldNode, (newSymbol != null && newSymbol.DeclaringSyntaxReferences.Length == 1) ? GetSymbolDeclarationSyntax(newSymbol.DeclaringSyntaxReferences.Single(), cancellationToken) : newNode); } } private static bool IsReloadable(INamedTypeSymbol type) { var current = type; while (current != null) { foreach (var attributeData in current.GetAttributes()) { // We assume that the attribute System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute, if it exists, is well formed. // If not an error will be reported during EnC delta emit. if (attributeData.AttributeClass is { Name: CreateNewOnMetadataUpdateAttributeName, ContainingNamespace: { Name: "CompilerServices", ContainingNamespace: { Name: "Runtime", ContainingNamespace: { Name: "System" } } } }) { return true; } } current = current.BaseType; } return false; } private sealed class SemanticEditInfoComparer : IEqualityComparer<SemanticEditInfo> { public static SemanticEditInfoComparer Instance = new(); private static readonly IEqualityComparer<SymbolKey> s_symbolKeyComparer = SymbolKey.GetComparer(); public bool Equals([AllowNull] SemanticEditInfo x, [AllowNull] SemanticEditInfo y) => s_symbolKeyComparer.Equals(x.Symbol, y.Symbol); public int GetHashCode([DisallowNull] SemanticEditInfo obj) => obj.Symbol.GetHashCode(); } private void ReportUpdatedSymbolDeclarationRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, out bool hasGeneratedAttributeChange, out bool hasGeneratedReturnTypeAttributeChange, out bool hasParameterRename, CancellationToken cancellationToken) { var rudeEdit = RudeEditKind.None; hasGeneratedAttributeChange = false; hasGeneratedReturnTypeAttributeChange = false; hasParameterRename = false; if (oldSymbol.Kind != newSymbol.Kind) { rudeEdit = (oldSymbol.Kind == SymbolKind.Field || newSymbol.Kind == SymbolKind.Field) ? RudeEditKind.FieldKindUpdate : RudeEditKind.Update; } else if (oldSymbol.Name != newSymbol.Name) { if (oldSymbol is IParameterSymbol && newSymbol is IParameterSymbol) { if (capabilities.HasFlag(EditAndContinueCapabilities.UpdateParameters)) { hasParameterRename = true; } else { rudeEdit = RudeEditKind.RenamingNotSupportedByRuntime; } } else { rudeEdit = RudeEditKind.Renamed; } // specialize rude edit for accessors and conversion operators: if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { if (oldMethod.AssociatedSymbol != null && newMethod.AssociatedSymbol != null) { if (oldMethod.MethodKind != newMethod.MethodKind) { rudeEdit = RudeEditKind.AccessorKindUpdate; } else { // rude edit will be reported by the associated symbol rudeEdit = RudeEditKind.None; } } else if (oldMethod.MethodKind == MethodKind.Conversion) { rudeEdit = RudeEditKind.ModifiersUpdate; } } } if (oldSymbol.DeclaredAccessibility != newSymbol.DeclaredAccessibility) { rudeEdit = RudeEditKind.ChangingAccessibility; } if (oldSymbol.IsStatic != newSymbol.IsStatic || oldSymbol.IsVirtual != newSymbol.IsVirtual || oldSymbol.IsAbstract != newSymbol.IsAbstract || oldSymbol.IsOverride != newSymbol.IsOverride || oldSymbol.IsExtern != newSymbol.IsExtern) { // Do not report for accessors as the error will be reported on their associated symbol. if (oldSymbol is not IMethodSymbol { AssociatedSymbol: not null }) { rudeEdit = RudeEditKind.ModifiersUpdate; } } if (oldSymbol is IFieldSymbol oldField && newSymbol is IFieldSymbol newField) { if (oldField.IsConst != newField.IsConst || oldField.IsReadOnly != newField.IsReadOnly || oldField.IsVolatile != newField.IsVolatile) { rudeEdit = RudeEditKind.ModifiersUpdate; } // Report rude edit for updating const fields and values of enums. // The latter is only reported whne the enum underlying type does not change to avoid cascading rude edits. if (oldField.IsConst && newField.IsConst && !Equals(oldField.ConstantValue, newField.ConstantValue) && TypesEquivalent(oldField.ContainingType.EnumUnderlyingType, newField.ContainingType.EnumUnderlyingType, exact: false)) { rudeEdit = RudeEditKind.InitializerUpdate; } if (oldField.FixedSize != newField.FixedSize) { rudeEdit = RudeEditKind.FixedSizeFieldUpdate; } AnalyzeType(oldField.Type, newField.Type, ref rudeEdit, ref hasGeneratedAttributeChange); } else if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { if (oldMethod.IsReadOnly != newMethod.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } if (oldMethod.IsInitOnly != newMethod.IsInitOnly) { rudeEdit = RudeEditKind.AccessorKindUpdate; } // Consider: Generalize to compare P/Invokes regardless of how they are defined (using attribute or Declare) if (oldMethod.MethodKind == MethodKind.DeclareMethod || newMethod.MethodKind == MethodKind.DeclareMethod) { var oldImportData = oldMethod.GetDllImportData(); var newImportData = newMethod.GetDllImportData(); if (oldImportData != null && newImportData != null) { // Declare method syntax can't change these. Debug.Assert(oldImportData.BestFitMapping == newImportData.BestFitMapping || oldImportData.CallingConvention == newImportData.CallingConvention || oldImportData.ExactSpelling == newImportData.ExactSpelling || oldImportData.SetLastError == newImportData.SetLastError || oldImportData.ThrowOnUnmappableCharacter == newImportData.ThrowOnUnmappableCharacter); if (oldImportData.ModuleName != newImportData.ModuleName) { rudeEdit = RudeEditKind.DeclareLibraryUpdate; } else if (oldImportData.EntryPointName != newImportData.EntryPointName) { rudeEdit = RudeEditKind.DeclareAliasUpdate; } else if (oldImportData.CharacterSet != newImportData.CharacterSet) { rudeEdit = RudeEditKind.ModifiersUpdate; } } else if (oldImportData is null != newImportData is null) { rudeEdit = RudeEditKind.ModifiersUpdate; } } // VB implements clause if (!oldMethod.ExplicitInterfaceImplementations.SequenceEqual(newMethod.ExplicitInterfaceImplementations, (x, y) => SymbolsEquivalent(x, y))) { rudeEdit = RudeEditKind.ImplementsClauseUpdate; } // VB handles clause if (!AreHandledEventsEqual(oldMethod, newMethod)) { rudeEdit = RudeEditKind.HandlesClauseUpdate; } // Check return type - do not report for accessors, their containing symbol will report the rude edits and attribute updates. if (rudeEdit == RudeEditKind.None && oldMethod.AssociatedSymbol == null && newMethod.AssociatedSymbol == null) { AnalyzeReturnType(oldMethod, newMethod, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } else if (oldSymbol is INamedTypeSymbol oldType && newSymbol is INamedTypeSymbol newType) { if (oldType.TypeKind != newType.TypeKind || oldType.IsRecord != newType.IsRecord) // TODO: https://github.com/dotnet/roslyn/issues/51874 { rudeEdit = RudeEditKind.TypeKindUpdate; } else if (oldType.IsRefLikeType != newType.IsRefLikeType || oldType.IsReadOnly != newType.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } if (rudeEdit == RudeEditKind.None) { AnalyzeBaseTypes(oldType, newType, ref rudeEdit, ref hasGeneratedAttributeChange); if (oldType.DelegateInvokeMethod != null) { Contract.ThrowIfNull(newType.DelegateInvokeMethod); AnalyzeReturnType(oldType.DelegateInvokeMethod, newType.DelegateInvokeMethod, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } } else if (oldSymbol is IPropertySymbol oldProperty && newSymbol is IPropertySymbol newProperty) { AnalyzeReturnType(oldProperty, newProperty, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } else if (oldSymbol is IEventSymbol oldEvent && newSymbol is IEventSymbol newEvent) { // "readonly" modifier can only be applied on the event itself, not on its accessors. if (oldEvent.AddMethod != null && newEvent.AddMethod != null && oldEvent.AddMethod.IsReadOnly != newEvent.AddMethod.IsReadOnly || oldEvent.RemoveMethod != null && newEvent.RemoveMethod != null && oldEvent.RemoveMethod.IsReadOnly != newEvent.RemoveMethod.IsReadOnly) { rudeEdit = RudeEditKind.ModifiersUpdate; } else { AnalyzeReturnType(oldEvent, newEvent, ref rudeEdit, ref hasGeneratedReturnTypeAttributeChange); } } else if (oldSymbol is IParameterSymbol oldParameter && newSymbol is IParameterSymbol newParameter) { if (oldParameter.RefKind != newParameter.RefKind || oldParameter.IsParams != newParameter.IsParams || IsExtensionMethodThisParameter(oldParameter) != IsExtensionMethodThisParameter(newParameter)) { rudeEdit = RudeEditKind.ModifiersUpdate; } else if (oldParameter.HasExplicitDefaultValue != newParameter.HasExplicitDefaultValue || oldParameter.HasExplicitDefaultValue && !Equals(oldParameter.ExplicitDefaultValue, newParameter.ExplicitDefaultValue)) { rudeEdit = RudeEditKind.InitializerUpdate; } else { AnalyzeParameterType(oldParameter, newParameter, ref rudeEdit, ref hasGeneratedAttributeChange); } } else if (oldSymbol is ITypeParameterSymbol oldTypeParameter && newSymbol is ITypeParameterSymbol newTypeParameter) { AnalyzeTypeParameter(oldTypeParameter, newTypeParameter, ref rudeEdit, ref hasGeneratedAttributeChange); } // Do not report modifier update if type kind changed. if (rudeEdit == RudeEditKind.None && oldSymbol.IsSealed != newSymbol.IsSealed) { // Do not report for accessors as the error will be reported on their associated symbol. if (oldSymbol is not IMethodSymbol { AssociatedSymbol: not null }) { rudeEdit = RudeEditKind.ModifiersUpdate; } } if (rudeEdit != RudeEditKind.None) { // so we'll just use the last global statement in the file ReportUpdateRudeEdit(diagnostics, rudeEdit, oldSymbol, newSymbol, newNode, newCompilation, cancellationToken); } } private static void AnalyzeType(ITypeSymbol oldType, ITypeSymbol newType, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange, RudeEditKind rudeEditKind = RudeEditKind.TypeUpdate) { if (!TypesEquivalent(oldType, newType, exact: true)) { if (TypesEquivalent(oldType, newType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = rudeEditKind; } } } private static void AnalyzeBaseTypes(INamedTypeSymbol oldType, INamedTypeSymbol newType, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (oldType.EnumUnderlyingType != null && newType.EnumUnderlyingType != null) { if (!TypesEquivalent(oldType.EnumUnderlyingType, newType.EnumUnderlyingType, exact: true)) { if (TypesEquivalent(oldType.EnumUnderlyingType, newType.EnumUnderlyingType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.EnumUnderlyingTypeUpdate; } } } else if (!BaseTypesEquivalent(oldType, newType, exact: true)) { if (BaseTypesEquivalent(oldType, newType, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.BaseTypeOrInterfaceUpdate; } } } private static void AnalyzeParameterType(IParameterSymbol oldParameter, IParameterSymbol newParameter, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (!ParameterTypesEquivalent(oldParameter, newParameter, exact: true)) { if (ParameterTypesEquivalent(oldParameter, newParameter, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeTypeParameter(ITypeParameterSymbol oldParameter, ITypeParameterSymbol newParameter, ref RudeEditKind rudeEdit, ref bool hasGeneratedAttributeChange) { if (!TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact: true)) { if (TypeParameterConstraintsEquivalent(oldParameter, newParameter, exact: false)) { hasGeneratedAttributeChange = true; } else { rudeEdit = (oldParameter.Variance != newParameter.Variance) ? RudeEditKind.VarianceUpdate : RudeEditKind.ChangingConstraints; } } } private static void AnalyzeReturnType(IMethodSymbol oldMethod, IMethodSymbol newMethod, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldMethod, newMethod, exact: true)) { if (ReturnTypesEquivalent(oldMethod, newMethod, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else if (IsGlobalMain(oldMethod) || IsGlobalMain(newMethod)) { rudeEdit = RudeEditKind.ChangeImplicitMainReturnType; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeReturnType(IEventSymbol oldEvent, IEventSymbol newEvent, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldEvent, newEvent, exact: true)) { if (ReturnTypesEquivalent(oldEvent, newEvent, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static void AnalyzeReturnType(IPropertySymbol oldProperty, IPropertySymbol newProperty, ref RudeEditKind rudeEdit, ref bool hasGeneratedReturnTypeAttributeChange) { if (!ReturnTypesEquivalent(oldProperty, newProperty, exact: true)) { if (ReturnTypesEquivalent(oldProperty, newProperty, exact: false)) { hasGeneratedReturnTypeAttributeChange = true; } else { rudeEdit = RudeEditKind.TypeUpdate; } } } private static bool IsExtensionMethodThisParameter(IParameterSymbol parameter) => parameter is { Ordinal: 0, ContainingSymbol: IMethodSymbol { IsExtensionMethod: true } }; private void AnalyzeSymbolUpdate( ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, Match<SyntaxNode> topMatch, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, ArrayBuilder<SemanticEditInfo> semanticEdits, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { // TODO: fails in VB on delegate parameter https://github.com/dotnet/roslyn/issues/53337 // Contract.ThrowIfFalse(newSymbol.IsImplicitlyDeclared == newDeclaration is null); ReportCustomAttributeRudeEdits(diagnostics, oldSymbol, newSymbol, newNode, newCompilation, capabilities, out var hasAttributeChange, out var hasReturnTypeAttributeChange, cancellationToken); ReportUpdatedSymbolDeclarationRudeEdits(diagnostics, oldSymbol, newSymbol, newNode, newCompilation, capabilities, out var hasGeneratedAttributeChange, out var hasGeneratedReturnTypeAttributeChange, out var hasParameterRename, cancellationToken); hasAttributeChange |= hasGeneratedAttributeChange; hasReturnTypeAttributeChange |= hasGeneratedReturnTypeAttributeChange; if (hasParameterRename) { Debug.Assert(newSymbol is IParameterSymbol); AddParameterUpdateSemanticEdit(semanticEdits, (IParameterSymbol)newSymbol, syntaxMap, cancellationToken); } else if (hasAttributeChange || hasReturnTypeAttributeChange) { AddCustomAttributeSemanticEdits(semanticEdits, oldSymbol, newSymbol, topMatch, syntaxMap, hasAttributeChange, hasReturnTypeAttributeChange, cancellationToken); } // updating generic methods and types if (InGenericContext(oldSymbol, out var oldIsGenericMethod) || InGenericContext(newSymbol, out _)) { var rudeEdit = oldIsGenericMethod ? RudeEditKind.GenericMethodUpdate : RudeEditKind.GenericTypeUpdate; ReportUpdateRudeEdit(diagnostics, rudeEdit, newSymbol, newNode, cancellationToken); } } private static void AddCustomAttributeSemanticEdits( ArrayBuilder<SemanticEditInfo> semanticEdits, ISymbol oldSymbol, ISymbol newSymbol, Match<SyntaxNode> topMatch, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool hasAttributeChange, bool hasReturnTypeAttributeChange, CancellationToken cancellationToken) { // Most symbol types will automatically have an edit added, so we just need to handle a few if (newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newDelegateInvokeMethod } newDelegateType) { if (hasAttributeChange) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newDelegateType, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } if (hasReturnTypeAttributeChange) { // attributes applied on return type of a delegate are applied to both Invoke and BeginInvoke methods semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newDelegateInvokeMethod, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); AddDelegateBeginInvokeEdit(semanticEdits, newDelegateType, syntaxMap, cancellationToken); } } else if (newSymbol is INamedTypeSymbol) { var symbolKey = SymbolKey.Create(newSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol, newSymbol, topMatch.OldRoot.SyntaxTree, topMatch.NewRoot.SyntaxTree) ? symbolKey : null)); } else if (newSymbol is ITypeParameterSymbol) { var containingTypeSymbolKey = SymbolKey.Create(newSymbol.ContainingSymbol, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, containingTypeSymbolKey, syntaxMap, syntaxMapTree: null, IsPartialEdit(oldSymbol.ContainingSymbol, newSymbol.ContainingSymbol, topMatch.OldRoot.SyntaxTree, topMatch.NewRoot.SyntaxTree) ? containingTypeSymbolKey : null)); } else if (newSymbol is IFieldSymbol or IPropertySymbol or IEventSymbol) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newSymbol, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } else if (newSymbol is IParameterSymbol newParameterSymbol) { AddParameterUpdateSemanticEdit(semanticEdits, newParameterSymbol, syntaxMap, cancellationToken); } } private static void AddParameterUpdateSemanticEdit(ArrayBuilder<SemanticEditInfo> semanticEdits, IParameterSymbol newParameterSymbol, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { var newContainingSymbol = newParameterSymbol.ContainingSymbol; semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(newContainingSymbol, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); // attributes applied on parameters of a delegate are applied to both Invoke and BeginInvoke methods if (newContainingSymbol.ContainingSymbol is INamedTypeSymbol { TypeKind: TypeKind.Delegate } newContainingDelegateType) { AddDelegateBeginInvokeEdit(semanticEdits, newContainingDelegateType, syntaxMap, cancellationToken); } } private static void AddDelegateBeginInvokeEdit(ArrayBuilder<SemanticEditInfo> semanticEdits, INamedTypeSymbol delegateType, Func<SyntaxNode, SyntaxNode?>? syntaxMap, CancellationToken cancellationToken) { Debug.Assert(semanticEdits != null); var beginInvokeMethod = delegateType.GetMembers("BeginInvoke").FirstOrDefault(); if (beginInvokeMethod != null) { semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, SymbolKey.Create(beginInvokeMethod, cancellationToken), syntaxMap, syntaxMapTree: null, partialType: null)); } } private void ReportCustomAttributeRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, out bool hasAttributeChange, out bool hasReturnTypeAttributeChange, CancellationToken cancellationToken) { // This is the only case we care about whether to issue an edit or not, because this is the only case where types have their attributes checked // and types are the only things that would otherwise not have edits reported. hasAttributeChange = ReportCustomAttributeRudeEdits(diagnostics, oldSymbol.GetAttributes(), newSymbol.GetAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); hasReturnTypeAttributeChange = false; if (oldSymbol is IMethodSymbol oldMethod && newSymbol is IMethodSymbol newMethod) { hasReturnTypeAttributeChange |= ReportCustomAttributeRudeEdits(diagnostics, oldMethod.GetReturnTypeAttributes(), newMethod.GetReturnTypeAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); } else if (oldSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var oldInvokeMethod } && newSymbol is INamedTypeSymbol { DelegateInvokeMethod: not null and var newInvokeMethod }) { hasReturnTypeAttributeChange |= ReportCustomAttributeRudeEdits(diagnostics, oldInvokeMethod.GetReturnTypeAttributes(), newInvokeMethod.GetReturnTypeAttributes(), oldSymbol, newSymbol, newNode, newCompilation, capabilities, cancellationToken); } } private bool ReportCustomAttributeRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, EditAndContinueCapabilities capabilities, CancellationToken cancellationToken) { using var _ = ArrayBuilder<AttributeData>.GetInstance(out var changedAttributes); FindChangedAttributes(oldAttributes, newAttributes, changedAttributes); if (oldAttributes.HasValue) { FindChangedAttributes(newAttributes, oldAttributes.Value, changedAttributes); } if (changedAttributes.Count == 0) { return false; } // We need diagnostics reported if the runtime doesn't support changing attributes, // but even if it does, only attributes stored in the CustomAttributes table are editable if (!capabilities.HasFlag(EditAndContinueCapabilities.ChangeCustomAttributes) || changedAttributes.Any(IsNonCustomAttribute)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingAttributesNotSupportedByRuntime, oldSymbol, newSymbol, newNode, newCompilation, cancellationToken); // If the runtime doesn't support edits then pretend there weren't changes, so no edits are produced return false; } return true; static void FindChangedAttributes(ImmutableArray<AttributeData>? oldAttributes, ImmutableArray<AttributeData> newAttributes, ArrayBuilder<AttributeData> changedAttributes) { for (var i = 0; i < newAttributes.Length; i++) { var newAttribute = newAttributes[i]; var oldAttribute = FindMatch(newAttribute, oldAttributes); if (oldAttribute is null) { changedAttributes.Add(newAttribute); } } } static AttributeData? FindMatch(AttributeData attribute, ImmutableArray<AttributeData>? oldAttributes) { if (!oldAttributes.HasValue) { return null; } foreach (var match in oldAttributes.Value) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeClass, attribute.AttributeClass)) { if (SymbolEquivalenceComparer.Instance.Equals(match.AttributeConstructor, attribute.AttributeConstructor) && match.ConstructorArguments.SequenceEqual(attribute.ConstructorArguments, TypedConstantComparer.Instance) && match.NamedArguments.SequenceEqual(attribute.NamedArguments, NamedArgumentComparer.Instance)) { return match; } } } return null; } static bool IsNonCustomAttribute(AttributeData attribute) { // TODO: Use a compiler API to get this information rather than hard coding a list: https://github.com/dotnet/roslyn/issues/53410 // This list comes from ShouldEmitAttribute in src\Compilers\CSharp\Portable\Symbols\Attributes\AttributeData.cs // and src\Compilers\VisualBasic\Portable\Symbols\Attributes\AttributeData.vb return attribute.AttributeClass?.ToNameDisplayString() switch { "System.CLSCompliantAttribute" => true, "System.Diagnostics.CodeAnalysis.AllowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" => true, "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" => true, "System.Diagnostics.CodeAnalysis.NotNullAttribute" => true, "System.NonSerializedAttribute" => true, "System.Reflection.AssemblyAlgorithmIdAttribute" => true, "System.Reflection.AssemblyCultureAttribute" => true, "System.Reflection.AssemblyFlagsAttribute" => true, "System.Reflection.AssemblyVersionAttribute" => true, "System.Runtime.CompilerServices.DllImportAttribute" => true, // Already covered by other rude edits, but included for completeness "System.Runtime.CompilerServices.IndexerNameAttribute" => true, "System.Runtime.CompilerServices.MethodImplAttribute" => true, "System.Runtime.CompilerServices.SpecialNameAttribute" => true, "System.Runtime.CompilerServices.TypeForwardedToAttribute" => true, "System.Runtime.InteropServices.ComImportAttribute" => true, "System.Runtime.InteropServices.DefaultParameterValueAttribute" => true, "System.Runtime.InteropServices.FieldOffsetAttribute" => true, "System.Runtime.InteropServices.InAttribute" => true, "System.Runtime.InteropServices.MarshalAsAttribute" => true, "System.Runtime.InteropServices.OptionalAttribute" => true, "System.Runtime.InteropServices.OutAttribute" => true, "System.Runtime.InteropServices.PreserveSigAttribute" => true, "System.Runtime.InteropServices.StructLayoutAttribute" => true, "System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeImportAttribute" => true, "System.Security.DynamicSecurityMethodAttribute" => true, "System.SerializableAttribute" => true, not null => IsSecurityAttribute(attribute.AttributeClass), _ => false }; } static bool IsSecurityAttribute(INamedTypeSymbol namedTypeSymbol) { // Security attributes are any attribute derived from System.Security.Permissions.SecurityAttribute, directly or indirectly var symbol = namedTypeSymbol; while (symbol is not null) { if (symbol.ToNameDisplayString() == "System.Security.Permissions.SecurityAttribute") { return true; } symbol = symbol.BaseType; } return false; } } private static bool CanAddNewMember(ISymbol newSymbol, EditAndContinueCapabilities capabilities) { if (newSymbol is IMethodSymbol or IPropertySymbol) // Properties are just get_ and set_ methods { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } else if (newSymbol is IFieldSymbol field) { if (field.IsStatic) { return capabilities.HasFlag(EditAndContinueCapabilities.AddStaticFieldToExistingType); } return capabilities.HasFlag(EditAndContinueCapabilities.AddInstanceFieldToExistingType); } return true; } private static void AddEditsForSynthesizedRecordMembers(Compilation compilation, INamedTypeSymbol recordType, ArrayBuilder<SemanticEditInfo> semanticEdits, CancellationToken cancellationToken) { foreach (var member in GetRecordUpdatedSynthesizedMembers(compilation, recordType)) { var symbolKey = SymbolKey.Create(member, cancellationToken); semanticEdits.Add(new SemanticEditInfo(SemanticEditKind.Update, symbolKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } private static IEnumerable<ISymbol> GetRecordUpdatedSynthesizedMembers(Compilation compilation, INamedTypeSymbol record) { // All methods that are updated have well known names, and calling GetMembers(string) is // faster than enumerating. // When a new field or property is added the PrintMembers, Equals(R) and GetHashCode() methods are updated // We don't need to worry about Deconstruct because it only changes when a new positional parameter // is added, and those are rude edits (due to adding a constructor parameter). // We don't need to worry about the constructors as they are reported elsewhere. // We have to use SingleOrDefault and check IsImplicitlyDeclared because the user can provide their // own implementation of these methods, and edits to them are handled by normal processing. var result = record.GetMembers(WellKnownMemberNames.PrintMembersMethodName) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, compilation.GetTypeByMetadataName(typeof(StringBuilder).FullName!)) && SymbolEqualityComparer.Default.Equals(m.ReturnType, compilation.GetTypeByMetadataName(typeof(bool).FullName!))); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectEquals) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(m.Parameters[0].Type, m.ContainingType)); if (result is not null) { yield return result; } result = record.GetMembers(WellKnownMemberNames.ObjectGetHashCode) .OfType<IMethodSymbol>() .SingleOrDefault(m => m.IsImplicitlyDeclared && m.Parameters.Length == 0); if (result is not null) { yield return result; } } private void ReportDeletedMemberRudeEdit( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol oldSymbol, Compilation newCompilation, RudeEditKind rudeEditKind, CancellationToken cancellationToken) { var newNode = GetDeleteRudeEditDiagnosticNode(oldSymbol, newCompilation, cancellationToken); diagnostics.Add(new RudeEditDiagnostic( rudeEditKind, GetDiagnosticSpan(newNode, EditKind.Delete), arguments: new[] { string.Format(FeaturesResources.member_kind_and_name, GetDisplayName(oldSymbol), oldSymbol.ToDisplayString(s_unqualifiedMemberDisplayFormat)) })); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, SyntaxNode newNode) { diagnostics.Add(new RudeEditDiagnostic( rudeEdit, GetDiagnosticSpan(newNode, EditKind.Update), newNode, new[] { GetDisplayName(newNode) })); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, ISymbol newSymbol, SyntaxNode? newNode, CancellationToken cancellationToken) { var node = newNode ?? GetRudeEditDiagnosticNode(newSymbol, cancellationToken); var span = (rudeEdit == RudeEditKind.ChangeImplicitMainReturnType) ? GetGlobalStatementDiagnosticSpan(node) : GetDiagnosticSpan(node, EditKind.Update); var arguments = rudeEdit switch { RudeEditKind.TypeKindUpdate or RudeEditKind.ChangeImplicitMainReturnType or RudeEditKind.GenericMethodUpdate or RudeEditKind.GenericTypeUpdate => Array.Empty<string>(), RudeEditKind.ChangingReloadableTypeNotSupportedByRuntime => new[] { CreateNewOnMetadataUpdateAttributeName }, _ => new[] { GetDisplayName(newSymbol) } }; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, span, node, arguments)); } private void ReportUpdateRudeEdit(ArrayBuilder<RudeEditDiagnostic> diagnostics, RudeEditKind rudeEdit, ISymbol oldSymbol, ISymbol newSymbol, SyntaxNode? newNode, Compilation newCompilation, CancellationToken cancellationToken) { if (newSymbol.IsImplicitlyDeclared) { ReportDeletedMemberRudeEdit(diagnostics, oldSymbol, newCompilation, rudeEdit, cancellationToken); } else { ReportUpdateRudeEdit(diagnostics, rudeEdit, newSymbol, newNode, cancellationToken); } } private static SyntaxNode GetRudeEditDiagnosticNode(ISymbol symbol, CancellationToken cancellationToken) { var container = symbol; while (container != null) { if (container.DeclaringSyntaxReferences.Length > 0) { return container.DeclaringSyntaxReferences[0].GetSyntax(cancellationToken); } container = container.ContainingSymbol; } throw ExceptionUtilities.Unreachable; } private static SyntaxNode GetDeleteRudeEditDiagnosticNode(ISymbol oldSymbol, Compilation newCompilation, CancellationToken cancellationToken) { var oldContainer = oldSymbol.ContainingSymbol; while (oldContainer != null) { var containerKey = SymbolKey.Create(oldContainer, cancellationToken); var newContainer = containerKey.Resolve(newCompilation, ignoreAssemblyKey: true, cancellationToken).Symbol; if (newContainer != null) { return GetRudeEditDiagnosticNode(newContainer, cancellationToken); } oldContainer = oldContainer.ContainingSymbol; } throw ExceptionUtilities.Unreachable; } #region Type Layout Update Validation internal void ReportTypeLayoutUpdateRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol newSymbol, SyntaxNode newSyntax, SemanticModel newModel, ref INamedTypeSymbol? lazyLayoutAttribute) { switch (newSymbol.Kind) { case SymbolKind.Field: if (HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Property: if (HasBackingField(newSyntax) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; case SymbolKind.Event: if (HasBackingField((IEventSymbol)newSymbol) && HasExplicitOrSequentialLayout(newSymbol.ContainingType, newModel, ref lazyLayoutAttribute)) { ReportTypeLayoutUpdateRudeEdits(diagnostics, newSymbol, newSyntax); } break; } } private void ReportTypeLayoutUpdateRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, ISymbol symbol, SyntaxNode syntax) { var intoStruct = symbol.ContainingType.TypeKind == TypeKind.Struct; diagnostics.Add(new RudeEditDiagnostic( intoStruct ? RudeEditKind.InsertIntoStruct : RudeEditKind.InsertIntoClassWithLayout, syntax.Span, syntax, new[] { GetDisplayName(syntax, EditKind.Insert), GetDisplayName(TryGetContainingTypeDeclaration(syntax)!, EditKind.Update) })); } private static bool HasBackingField(IEventSymbol @event) { #nullable disable // https://github.com/dotnet/roslyn/issues/39288 return @event.AddMethod.IsImplicitlyDeclared #nullable enable && [email protected]; } private static bool HasExplicitOrSequentialLayout( INamedTypeSymbol type, SemanticModel model, ref INamedTypeSymbol? lazyLayoutAttribute) { if (type.TypeKind == TypeKind.Struct) { return true; } if (type.TypeKind != TypeKind.Class) { return false; } // Fields can't be inserted into a class with explicit or sequential layout var attributes = type.GetAttributes(); if (attributes.Length == 0) { return false; } lazyLayoutAttribute ??= model.Compilation.GetTypeByMetadataName(typeof(StructLayoutAttribute).FullName!); if (lazyLayoutAttribute == null) { return false; } foreach (var attribute in attributes) { RoslynDebug.Assert(attribute.AttributeClass is object); if (attribute.AttributeClass.Equals(lazyLayoutAttribute) && attribute.ConstructorArguments.Length == 1) { var layoutValue = attribute.ConstructorArguments.Single().Value; return (layoutValue is int ? (int)layoutValue : layoutValue is short ? (short)layoutValue : (int)LayoutKind.Auto) != (int)LayoutKind.Auto; } } return false; } #endregion private Func<SyntaxNode, SyntaxNode?> CreateSyntaxMapForEquivalentNodes(SyntaxNode oldDeclaration, SyntaxNode newDeclaration) { return newNode => newDeclaration.FullSpan.Contains(newNode.SpanStart) ? FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode) : null; } private static Func<SyntaxNode, SyntaxNode?> CreateSyntaxMap(IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) => newNode => reverseMap.TryGetValue(newNode, out var oldNode) ? oldNode : null; private Func<SyntaxNode, SyntaxNode?>? CreateAggregateSyntaxMap( IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseTopMatches, IReadOnlyDictionary<SyntaxNode, Func<SyntaxNode, SyntaxNode?>?> changedDeclarations) { return newNode => { // containing declaration if (!TryFindMemberDeclaration(root: null, newNode, out var newDeclarations)) { return null; } foreach (var newDeclaration in newDeclarations) { // The node is in a field, property or constructor declaration that has been changed: if (changedDeclarations.TryGetValue(newDeclaration, out var syntaxMap)) { // If syntax map is not available the declaration was either // 1) updated but is not active // 2) inserted return syntaxMap?.Invoke(newNode); } // The node is in a declaration that hasn't been changed: if (reverseTopMatches.TryGetValue(newDeclaration, out var oldDeclaration)) { return FindDeclarationBodyPartner(newDeclaration, oldDeclaration, newNode); } } return null; }; } #region Constructors and Initializers /// <summary> /// Called when a body of a constructor or an initializer of a member is updated or inserted. /// </summary> private static void DeferConstructorEdit( INamedTypeSymbol oldType, INamedTypeSymbol newType, SyntaxNode? newDeclaration, Func<SyntaxNode, SyntaxNode?>? syntaxMap, bool isStatic, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? instanceConstructorEdits, ref PooledDictionary<INamedTypeSymbol, ConstructorEdit>? staticConstructorEdits) { Dictionary<INamedTypeSymbol, ConstructorEdit> constructorEdits; if (isStatic) { constructorEdits = staticConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } else { constructorEdits = instanceConstructorEdits ??= PooledDictionary<INamedTypeSymbol, ConstructorEdit>.GetInstance(); } if (!constructorEdits.TryGetValue(newType, out var constructorEdit)) { constructorEdits.Add(newType, constructorEdit = new ConstructorEdit(oldType)); } if (newDeclaration != null && !constructorEdit.ChangedDeclarations.ContainsKey(newDeclaration)) { constructorEdit.ChangedDeclarations.Add(newDeclaration, syntaxMap); } } private void AddConstructorEdits( IReadOnlyDictionary<INamedTypeSymbol, ConstructorEdit> updatedTypes, Match<SyntaxNode> topMatch, SemanticModel? oldModel, Compilation oldCompilation, Compilation newCompilation, IReadOnlySet<ISymbol> processedSymbols, EditAndContinueCapabilities capabilities, bool isStatic, [Out] ArrayBuilder<SemanticEditInfo> semanticEdits, [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, CancellationToken cancellationToken) { var oldSyntaxTree = topMatch.OldRoot.SyntaxTree; var newSyntaxTree = topMatch.NewRoot.SyntaxTree; foreach (var (newType, updatesInCurrentDocument) in updatedTypes) { var oldType = updatesInCurrentDocument.OldType; var anyInitializerUpdatesInCurrentDocument = updatesInCurrentDocument.ChangedDeclarations.Keys.Any(IsDeclarationWithInitializer); var isPartialEdit = IsPartialEdit(oldType, newType, oldSyntaxTree, newSyntaxTree); // Create a syntax map that aggregates syntax maps of the constructor body and all initializers in this document. // Use syntax maps stored in update.ChangedDeclarations and fallback to 1:1 map for unchanged members. // // This aggregated map will be combined with similar maps capturing members declared in partial type declarations // located in other documents when the semantic edits are merged across all changed documents of the project. // // We will create an aggregate syntax map even in cases when we don't necessarily need it, // for example if none of the edited declarations are active. It's ok to have a map that we don't need. // This is simpler than detecting whether or not some of the initializers/constructors contain active statements. var aggregateSyntaxMap = CreateAggregateSyntaxMap(topMatch.ReverseMatches, updatesInCurrentDocument.ChangedDeclarations); bool? lazyOldTypeHasMemberInitializerContainingLambda = null; foreach (var newCtor in isStatic ? newType.StaticConstructors : newType.InstanceConstructors) { if (processedSymbols.Contains(newCtor)) { // we already have an edit for the new constructor continue; } var newCtorKey = SymbolKey.Create(newCtor, cancellationToken); var syntaxMapToUse = aggregateSyntaxMap; SyntaxNode? newDeclaration = null; ISymbol? oldCtor; if (!newCtor.IsImplicitlyDeclared) { // Constructors have to have a single declaration syntax, they can't be partial newDeclaration = GetSymbolDeclarationSyntax(newCtor.DeclaringSyntaxReferences.Single(), cancellationToken); // Implicit record constructors are represented by the record declaration itself. // https://github.com/dotnet/roslyn/issues/54403 var isPrimaryRecordConstructor = IsRecordDeclaration(newDeclaration); // Constructor that doesn't contain initializers had a corresponding semantic edit produced previously // or was not edited. In either case we should not produce a semantic edit for it. if (!isPrimaryRecordConstructor && !IsConstructorWithMemberInitializers(newDeclaration)) { continue; } // If no initializer updates were made in the type we only need to produce semantic edits for constructors // whose body has been updated, otherwise we need to produce edits for all constructors that include initializers. // If changes were made to initializers or constructors of a partial type in another document they will be merged // when aggregating semantic edits from all changed documents. Rude edits resulting from those changes, if any, will // be reported in the document they were made in. if (!isPrimaryRecordConstructor && !anyInitializerUpdatesInCurrentDocument && !updatesInCurrentDocument.ChangedDeclarations.ContainsKey(newDeclaration)) { continue; } // To avoid costly SymbolKey resolution we first try to match the constructor in the current document // and special case parameter-less constructor. // In the case of records, newDeclaration will point to the record declaration, take the slow path. if (!isPrimaryRecordConstructor && topMatch.TryGetOldNode(newDeclaration, out var oldDeclaration)) { Contract.ThrowIfNull(oldModel); oldCtor = oldModel.GetDeclaredSymbol(oldDeclaration, cancellationToken); Contract.ThrowIfFalse(oldCtor is IMethodSymbol { MethodKind: MethodKind.Constructor or MethodKind.StaticConstructor }); } else if (!isPrimaryRecordConstructor && newCtor.Parameters.Length == 0) { oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } else { var resolution = newCtorKey.Resolve(oldCompilation, ignoreAssemblyKey: true, cancellationToken); // There may be semantic errors in the compilation that result in multiple candidates. // Pick the first candidate. oldCtor = resolution.Symbol; } if (oldCtor == null && HasMemberInitializerContainingLambda(oldType, isStatic, ref lazyOldTypeHasMemberInitializerContainingLambda, cancellationToken)) { // TODO (bug https://github.com/dotnet/roslyn/issues/2504) // rude edit: Adding a constructor to a type with a field or property initializer that contains an anonymous function diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertConstructorToTypeWithInitializersWithLambdas, GetDiagnosticSpan(newDeclaration, EditKind.Insert))); continue; } // Report an error if the updated constructor's declaration is in the current document // and its body edit is disallowed (e.g. contains stackalloc). if (oldCtor != null && newDeclaration.SyntaxTree == newSyntaxTree && anyInitializerUpdatesInCurrentDocument) { // attribute rude edit to one of the modified members var firstSpan = updatesInCurrentDocument.ChangedDeclarations.Keys.Where(IsDeclarationWithInitializer).Aggregate( (min: int.MaxValue, span: default(TextSpan)), (accumulate, node) => (node.SpanStart < accumulate.min) ? (node.SpanStart, node.Span) : accumulate).span; Contract.ThrowIfTrue(firstSpan.IsEmpty); ReportMemberBodyUpdateRudeEdits(diagnostics, newDeclaration, firstSpan); } // When explicitly implementing the copy constructor of a record the parameter name if the runtime doesn't support // updating parameters, otherwise the debugger would show the incorrect name in the autos/locals/watch window if (!capabilities.HasFlag(EditAndContinueCapabilities.UpdateParameters) && oldCtor != null && !isPrimaryRecordConstructor && oldCtor.DeclaringSyntaxReferences.Length == 0 && newCtor.Parameters.Length == 1 && newType.IsRecord && oldCtor.GetParameters().First().Name != newCtor.GetParameters().First().Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ExplicitRecordMethodParameterNamesMustMatch, GetDiagnosticSpan(newDeclaration, EditKind.Update), arguments: new[] { oldCtor.ToDisplayString(SymbolDisplayFormats.NameFormat) })); continue; } } else { if (newCtor.Parameters.Length == 1) { // New constructor is implicitly declared with a parameter, so its the copy constructor of a record Debug.Assert(oldType.IsRecord); Debug.Assert(newType.IsRecord); // We only need an edit for this if the number of properties or fields on the record has changed. Changes to // initializers, or whether the property is part of the primary constructor, will still come through this code // path because they need an edit to the other constructor, but not the copy construcor. if (oldType.GetMembers().OfType<IPropertySymbol>().Count() == newType.GetMembers().OfType<IPropertySymbol>().Count() && oldType.GetMembers().OfType<IFieldSymbol>().Count() == newType.GetMembers().OfType<IFieldSymbol>().Count()) { continue; } oldCtor = oldType.InstanceConstructors.Single(c => c.Parameters.Length == 1 && SymbolEqualityComparer.Default.Equals(c.Parameters[0].Type, c.ContainingType)); // The copy constructor does not have a syntax map syntaxMapToUse = null; // Since there is no syntax map, we don't need to handle anything special to merge them for partial types. // The easiest way to do this is just to pretend this isn't a partial edit. isPartialEdit = false; } else { // New constructor is implicitly declared so it must be parameterless. // // Instance constructor: // Its presence indicates there are no other instance constructors in the new type and therefore // there must be a single parameterless instance constructor in the old type (constructors with parameters can't be removed). // // Static constructor: // Static constructor is always parameterless and not implicitly generated if there are no static initializers. oldCtor = TryGetParameterlessConstructor(oldType, isStatic); } Contract.ThrowIfFalse(isStatic || oldCtor != null); } if (oldCtor != null) { AnalyzeSymbolUpdate(oldCtor, newCtor, newDeclaration, newCompilation, topMatch, capabilities, diagnostics, semanticEdits, syntaxMapToUse, cancellationToken); semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Update, newCtorKey, syntaxMapToUse, syntaxMapTree: isPartialEdit ? newSyntaxTree : null, partialType: isPartialEdit ? SymbolKey.Create(newType, cancellationToken) : null)); } else { semanticEdits.Add(new SemanticEditInfo( SemanticEditKind.Insert, newCtorKey, syntaxMap: null, syntaxMapTree: null, partialType: null)); } } } } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, ref bool? lazyHasMemberInitializerContainingLambda, CancellationToken cancellationToken) { if (lazyHasMemberInitializerContainingLambda == null) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) lazyHasMemberInitializerContainingLambda = HasMemberInitializerContainingLambda(type, isStatic, cancellationToken); } return lazyHasMemberInitializerContainingLambda.Value; } private bool HasMemberInitializerContainingLambda(INamedTypeSymbol type, bool isStatic, CancellationToken cancellationToken) { // checking the old type for existing lambdas (it's ok for the new initializers to contain lambdas) foreach (var member in type.GetMembers()) { if (member.IsStatic == isStatic && (member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Property) && member.DeclaringSyntaxReferences.Length > 0) // skip generated fields (e.g. VB auto-property backing fields) { var syntax = GetSymbolDeclarationSyntax(member.DeclaringSyntaxReferences.Single(), cancellationToken); if (IsDeclarationWithInitializer(syntax) && ContainsLambda(syntax)) { return true; } } } return false; } private static ISymbol? TryGetParameterlessConstructor(INamedTypeSymbol type, bool isStatic) { var oldCtors = isStatic ? type.StaticConstructors : type.InstanceConstructors; if (isStatic) { return type.StaticConstructors.FirstOrDefault(); } else { return type.InstanceConstructors.FirstOrDefault(m => m.Parameters.Length == 0); } } private static bool IsPartialEdit(ISymbol? oldSymbol, ISymbol? newSymbol, SyntaxTree oldSyntaxTree, SyntaxTree newSyntaxTree) { // If any of the partial declarations of the new or the old type are in another document // the edit will need to be merged with other partial edits with matching partial type static bool IsNotInDocument(SyntaxReference reference, SyntaxTree syntaxTree) => reference.SyntaxTree != syntaxTree; return oldSymbol?.Kind == SymbolKind.NamedType && oldSymbol.DeclaringSyntaxReferences.Length > 1 && oldSymbol.DeclaringSyntaxReferences.Any(IsNotInDocument, oldSyntaxTree) || newSymbol?.Kind == SymbolKind.NamedType && newSymbol.DeclaringSyntaxReferences.Length > 1 && newSymbol.DeclaringSyntaxReferences.Any(IsNotInDocument, newSyntaxTree); } #endregion #region Lambdas and Closures private void ReportLambdaAndClosureRudeEdits( SemanticModel oldModel, SyntaxNode oldMemberBody, SemanticModel newModel, SyntaxNode newMemberBody, ISymbol newMember, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas, BidirectionalMap<SyntaxNode> map, EditAndContinueCapabilities capabilities, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool syntaxMapRequired, CancellationToken cancellationToken) { syntaxMapRequired = false; if (matchedLambdas != null) { var anySignatureErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { // Any unmatched lambdas would have contained an active statement and a rude edit would be reported in syntax analysis phase. // Skip the rest of lambda and closure analysis if such lambdas are present. if (newLambdaInfo.Match == null || newLambdaInfo.NewBody == null) { return; } ReportLambdaSignatureRudeEdits(diagnostics, oldModel, oldLambdaBody, newModel, newLambdaInfo.NewBody, capabilities, out var hasErrors, cancellationToken); anySignatureErrors |= hasErrors; } ArrayBuilder<SyntaxNode>? lazyNewErroneousClauses = null; foreach (var (oldQueryClause, newQueryClause) in map.Forward) { if (!QueryClauseLambdasTypeEquivalent(oldModel, oldQueryClause, newModel, newQueryClause, cancellationToken)) { lazyNewErroneousClauses ??= ArrayBuilder<SyntaxNode>.GetInstance(); lazyNewErroneousClauses.Add(newQueryClause); } } if (lazyNewErroneousClauses != null) { foreach (var newQueryClause in from clause in lazyNewErroneousClauses orderby clause.SpanStart group clause by GetContainingQueryExpression(clause) into clausesByQuery select clausesByQuery.First()) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingQueryLambdaType, GetDiagnosticSpan(newQueryClause, EditKind.Update), newQueryClause, new[] { GetDisplayName(newQueryClause, EditKind.Update) })); } lazyNewErroneousClauses.Free(); anySignatureErrors = true; } // only dig into captures if lambda signatures match if (anySignatureErrors) { return; } } using var oldLambdaBodyEnumerator = GetLambdaBodies(oldMemberBody).GetEnumerator(); using var newLambdaBodyEnumerator = GetLambdaBodies(newMemberBody).GetEnumerator(); var oldHasLambdas = oldLambdaBodyEnumerator.MoveNext(); var newHasLambdas = newLambdaBodyEnumerator.MoveNext(); // Exit early if there are no lambdas in the method to avoid expensive data flow analysis: if (!oldHasLambdas && !newHasLambdas) { return; } var oldCaptures = GetCapturedVariables(oldModel, oldMemberBody); var newCaptures = GetCapturedVariables(newModel, newMemberBody); // { new capture index -> old capture index } using var _1 = ArrayBuilder<int>.GetInstance(newCaptures.Length, fillWithValue: 0, out var reverseCapturesMap); // { new capture index -> new closure scope or null for "this" } using var _2 = ArrayBuilder<SyntaxNode?>.GetInstance(newCaptures.Length, fillWithValue: null, out var newCapturesToClosureScopes); // Can be calculated from other maps but it's simpler to just calculate it upfront. // { old capture index -> old closure scope or null for "this" } using var _3 = ArrayBuilder<SyntaxNode?>.GetInstance(oldCaptures.Length, fillWithValue: null, out var oldCapturesToClosureScopes); CalculateCapturedVariablesMaps( oldCaptures, oldMemberBody, newCaptures, newMember, newMemberBody, map, reverseCapturesMap, newCapturesToClosureScopes, oldCapturesToClosureScopes, diagnostics, out var anyCaptureErrors, cancellationToken); if (anyCaptureErrors) { return; } // Every captured variable accessed in the new lambda has to be // accessed in the old lambda as well and vice versa. // // An added lambda can only reference captured variables that // // This requirement ensures that: // - Lambda methods are generated to the same frame as before, so they can be updated in-place. // - "Parent" links between closure scopes are preserved. using var _11 = PooledDictionary<ISymbol, int>.GetInstance(out var oldCapturesIndex); using var _12 = PooledDictionary<ISymbol, int>.GetInstance(out var newCapturesIndex); BuildIndex(oldCapturesIndex, oldCaptures); BuildIndex(newCapturesIndex, newCaptures); if (matchedLambdas != null) { var mappedLambdasHaveErrors = false; foreach (var (oldLambdaBody, newLambdaInfo) in matchedLambdas) { var newLambdaBody = newLambdaInfo.NewBody; // The map now contains only matched lambdas. Any unmatched ones would have contained an active statement and // a rude edit would be reported in syntax analysis phase. RoslynDebug.Assert(newLambdaInfo.Match != null && newLambdaBody != null); var accessedOldCaptures = GetAccessedCaptures(oldLambdaBody, oldModel, oldCaptures, oldCapturesIndex); var accessedNewCaptures = GetAccessedCaptures(newLambdaBody, newModel, newCaptures, newCapturesIndex); // Requirement: // (new(ReadInside) \/ new(WrittenInside)) /\ new(Captured) == (old(ReadInside) \/ old(WrittenInside)) /\ old(Captured) for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newAccessed = accessedNewCaptures[newCaptureIndex]; var oldAccessed = accessedOldCaptures[reverseCapturesMap[newCaptureIndex]]; if (newAccessed != oldAccessed) { var newCapture = newCaptures[newCaptureIndex]; var rudeEdit = newAccessed ? RudeEditKind.AccessingCapturedVariableInLambda : RudeEditKind.NotAccessingCapturedVariableInLambda; var arguments = new[] { newCapture.Name, GetDisplayName(GetLambda(newLambdaBody)) }; if (newCapture.IsThisParameter() || oldAccessed) { // changed accessed to "this", or captured variable accessed in old lambda is not accessed in the new lambda diagnostics.Add(new RudeEditDiagnostic(rudeEdit, GetDiagnosticSpan(GetLambda(newLambdaBody), EditKind.Update), null, arguments)); } else if (newAccessed) { // captured variable accessed in new lambda is not accessed in the old lambda var hasUseSites = false; foreach (var useSite in GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(newLambdaBody), newCapture, newModel, cancellationToken)) { hasUseSites = true; diagnostics.Add(new RudeEditDiagnostic(rudeEdit, useSite.Span, null, arguments)); } Debug.Assert(hasUseSites); } mappedLambdasHaveErrors = true; } } } if (mappedLambdasHaveErrors) { return; } } // Report rude edits for lambdas added to the method. // We already checked that no new captures are introduced or removed. // We also need to make sure that no new parent frame links are introduced. // // We could implement the same analysis as the compiler does when rewriting lambdas - // to determine what closure scopes are connected at runtime via parent link, // and then disallow adding a lambda that connects two previously unconnected // groups of scopes. // // However even if we implemented that logic here, it would be challenging to // present the result of the analysis to the user in a short comprehensible error message. // // In practice, we believe the common scenarios are (in order of commonality): // 1) adding a static lambda // 2) adding a lambda that accesses only "this" // 3) adding a lambda that accesses variables from the same scope // 4) adding a lambda that accesses "this" and variables from a single scope // 5) adding a lambda that accesses variables from different scopes that are linked // 6) adding a lambda that accesses variables from unlinked scopes // // We currently allow #1, #2, and #3 and report a rude edit for the other cases. // In future we might be able to enable more. var containingTypeDeclaration = TryGetContainingTypeDeclaration(newMemberBody); var isInInterfaceDeclaration = containingTypeDeclaration != null && IsInterfaceDeclaration(containingTypeDeclaration); var newHasLambdaBodies = newHasLambdas; while (newHasLambdaBodies) { var (newLambda, newLambdaBody1, newLambdaBody2) = newLambdaBodyEnumerator.Current; if (!map.Reverse.ContainsKey(newLambda)) { if (!CanAddNewLambda(newLambda, capabilities, matchedLambdas)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertNotSupportedByRuntime, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda, new string[] { GetDisplayName(newLambda, EditKind.Insert) })); } // TODO: https://github.com/dotnet/roslyn/issues/37128 // Local functions are emitted directly to the type containing the containing method. // Although local functions are non-virtual the Core CLR currently does not support adding any method to an interface. if (isInInterfaceDeclaration && IsLocalFunction(newLambda)) { diagnostics.Add(new RudeEditDiagnostic(RudeEditKind.InsertLocalFunctionIntoInterfaceMethod, GetDiagnosticSpan(newLambda, EditKind.Insert), newLambda)); } ReportMultiScopeCaptures(newLambdaBody1, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); if (newLambdaBody2 != null) { ReportMultiScopeCaptures(newLambdaBody2, newModel, newCaptures, newCaptures, newCapturesToClosureScopes, newCapturesIndex, reverseCapturesMap, diagnostics, isInsert: true, cancellationToken: cancellationToken); } } newHasLambdaBodies = newLambdaBodyEnumerator.MoveNext(); } // Similarly for addition. We don't allow removal of lambda that has captures from multiple scopes. var oldHasMoreLambdas = oldHasLambdas; while (oldHasMoreLambdas) { var (oldLambda, oldLambdaBody1, oldLambdaBody2) = oldLambdaBodyEnumerator.Current; if (!map.Forward.ContainsKey(oldLambda)) { ReportMultiScopeCaptures(oldLambdaBody1, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); if (oldLambdaBody2 != null) { ReportMultiScopeCaptures(oldLambdaBody2, oldModel, oldCaptures, newCaptures, oldCapturesToClosureScopes, oldCapturesIndex, reverseCapturesMap, diagnostics, isInsert: false, cancellationToken: cancellationToken); } } oldHasMoreLambdas = oldLambdaBodyEnumerator.MoveNext(); } syntaxMapRequired = newHasLambdas; } private IEnumerable<(SyntaxNode lambda, SyntaxNode lambdaBody1, SyntaxNode? lambdaBody2)> GetLambdaBodies(SyntaxNode body) { foreach (var node in body.DescendantNodesAndSelf()) { if (TryGetLambdaBodies(node, out var body1, out var body2)) { yield return (node, body1, body2); } } } private bool CanAddNewLambda(SyntaxNode newLambda, EditAndContinueCapabilities capabilities, IReadOnlyDictionary<SyntaxNode, LambdaInfo>? matchedLambdas) { // New local functions mean new methods in existing classes if (IsLocalFunction(newLambda)) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // New lambdas sometimes mean creating new helper classes, and sometimes mean new methods in exising helper classes // Unfortunately we are limited here in what we can do here. See: https://github.com/dotnet/roslyn/issues/52759 // If there is already a lambda in the method then the new lambda would result in a new method in the existing helper class. // This check is redundant with the below, once the limitation in the referenced issue is resolved if (matchedLambdas is { Count: > 0 }) { return capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } // If there is already a lambda in the class then the new lambda would result in a new method in the existing helper class. // If there isn't already a lambda in the class then the new lambda would result in a new helper class. // Unfortunately right now we can't determine which of these is true so we have to just check both capabilities instead. return capabilities.HasFlag(EditAndContinueCapabilities.NewTypeDefinition) && capabilities.HasFlag(EditAndContinueCapabilities.AddMethodToExistingType); } private void ReportMultiScopeCaptures( SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, ImmutableArray<ISymbol> newCaptures, ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, PooledDictionary<ISymbol, int> capturesIndex, ArrayBuilder<int> reverseCapturesMap, ArrayBuilder<RudeEditDiagnostic> diagnostics, bool isInsert, CancellationToken cancellationToken) { if (captures.Length == 0) { return; } var accessedCaptures = GetAccessedCaptures(lambdaBody, model, captures, capturesIndex); var firstAccessedCaptureIndex = -1; for (var i = 0; i < captures.Length; i++) { if (accessedCaptures[i]) { if (firstAccessedCaptureIndex == -1) { firstAccessedCaptureIndex = i; } else if (newCapturesToClosureScopes[firstAccessedCaptureIndex] != newCapturesToClosureScopes[i]) { // the lambda accesses variables from two different scopes: TextSpan errorSpan; RudeEditKind rudeEdit; if (isInsert) { if (captures[i].IsThisParameter()) { errorSpan = GetDiagnosticSpan(GetLambda(lambdaBody), EditKind.Insert); } else { errorSpan = GetVariableUseSites(GetLambdaBodyExpressionsAndStatements(lambdaBody), captures[i], model, cancellationToken).First().Span; } rudeEdit = RudeEditKind.InsertLambdaWithMultiScopeCapture; } else { errorSpan = newCaptures[reverseCapturesMap.IndexOf(i)].Locations.Single().SourceSpan; rudeEdit = RudeEditKind.DeleteLambdaWithMultiScopeCapture; } diagnostics.Add(new RudeEditDiagnostic( rudeEdit, errorSpan, null, new[] { GetDisplayName(GetLambda(lambdaBody)), captures[firstAccessedCaptureIndex].Name, captures[i].Name })); break; } } } } private BitVector GetAccessedCaptures(SyntaxNode lambdaBody, SemanticModel model, ImmutableArray<ISymbol> captures, PooledDictionary<ISymbol, int> capturesIndex) { var result = BitVector.Create(captures.Length); foreach (var expressionOrStatement in GetLambdaBodyExpressionsAndStatements(lambdaBody)) { var dataFlow = model.AnalyzeDataFlow(expressionOrStatement); MarkVariables(ref result, dataFlow.ReadInside, capturesIndex); MarkVariables(ref result, dataFlow.WrittenInside, capturesIndex); } return result; } private static void MarkVariables(ref BitVector mask, ImmutableArray<ISymbol> variables, Dictionary<ISymbol, int> index) { foreach (var variable in variables) { if (index.TryGetValue(variable, out var newCaptureIndex)) { mask[newCaptureIndex] = true; } } } private static void BuildIndex<TKey>(Dictionary<TKey, int> index, ImmutableArray<TKey> array) where TKey : notnull { for (var i = 0; i < array.Length; i++) { index.Add(array[i], i); } } /// <summary> /// Returns node that represents a declaration of the symbol whose <paramref name="reference"/> is passed in. /// </summary> protected abstract SyntaxNode GetSymbolDeclarationSyntax(SyntaxReference reference, CancellationToken cancellationToken); private static TextSpan GetThisParameterDiagnosticSpan(ISymbol member) => member.Locations.First().SourceSpan; private static TextSpan GetVariableDiagnosticSpan(ISymbol local) { // Note that in VB implicit value parameter in property setter doesn't have a location. // In C# its location is the location of the setter. // See https://github.com/dotnet/roslyn/issues/14273 return local.Locations.FirstOrDefault()?.SourceSpan ?? local.ContainingSymbol.Locations.First().SourceSpan; } private static (SyntaxNode? Node, int Ordinal) GetParameterKey(IParameterSymbol parameter, CancellationToken cancellationToken) { var containingLambda = parameter.ContainingSymbol as IMethodSymbol; if (containingLambda?.MethodKind is MethodKind.LambdaMethod or MethodKind.LocalFunction) { var oldContainingLambdaSyntax = containingLambda.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); return (oldContainingLambdaSyntax, parameter.Ordinal); } else { return (Node: null, parameter.Ordinal); } } private static bool TryMapParameter((SyntaxNode? Node, int Ordinal) parameterKey, IReadOnlyDictionary<SyntaxNode, SyntaxNode> map, out (SyntaxNode? Node, int Ordinal) mappedParameterKey) { var containingLambdaSyntax = parameterKey.Node; if (containingLambdaSyntax == null) { // method parameter: no syntax, same ordinal (can't change since method signatures must match) mappedParameterKey = parameterKey; return true; } if (map.TryGetValue(containingLambdaSyntax, out var mappedContainingLambdaSyntax)) { // parameter of an existing lambda: same ordinal (can't change since lambda signatures must match), mappedParameterKey = (mappedContainingLambdaSyntax, parameterKey.Ordinal); return true; } // no mapping mappedParameterKey = default; return false; } private void CalculateCapturedVariablesMaps( ImmutableArray<ISymbol> oldCaptures, SyntaxNode oldMemberBody, ImmutableArray<ISymbol> newCaptures, ISymbol newMember, SyntaxNode newMemberBody, BidirectionalMap<SyntaxNode> map, [Out] ArrayBuilder<int> reverseCapturesMap, // {new capture index -> old capture index} [Out] ArrayBuilder<SyntaxNode?> newCapturesToClosureScopes, // {new capture index -> new closure scope} [Out] ArrayBuilder<SyntaxNode?> oldCapturesToClosureScopes, // {old capture index -> old closure scope} [Out] ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool hasErrors, CancellationToken cancellationToken) { hasErrors = false; // Validate that all variables that are/were captured in the new/old body were captured in // the old/new one and their type and scope haven't changed. // // Frames are created based upon captured variables and their scopes. If the scopes haven't changed the frames won't either. // // In future we can relax some of these limitations. // - If a newly captured variable's scope is already a closure then it is ok to lift this variable to the existing closure, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the local variable to the lifted field. // // Consider the following edit: // Gen0 Gen1 // ... ... // { { // int x = 1, y = 2; int x = 1, y = 2; // F(() => x); F(() => x); // AS-->W(y) AS-->W(y) // F(() => y); // } } // ... ... // // - If an "uncaptured" variable's scope still defines other captured variables it is ok to cease capturing the variable, // unless any lambda (or the containing member) that can access the variable is active. If it was active we would need // to copy the value of the lifted field to the local variable (consider reverse edit in the example above). // // - While building the closure tree for the new version the compiler can recreate // the closure tree of the previous version and then map // closure scopes in the new version to the previous ones, keeping empty closures around. using var _1 = PooledDictionary<SyntaxNode, int>.GetInstance(out var oldLocalCapturesBySyntax); using var _2 = PooledDictionary<(SyntaxNode? Node, int Ordinal), int>.GetInstance(out var oldParameterCapturesByLambdaAndOrdinal); for (var i = 0; i < oldCaptures.Length; i++) { var oldCapture = oldCaptures[i]; if (oldCapture.Kind == SymbolKind.Parameter) { oldParameterCapturesByLambdaAndOrdinal.Add(GetParameterKey((IParameterSymbol)oldCapture, cancellationToken), i); } else { oldLocalCapturesBySyntax.Add(oldCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken), i); } } for (var newCaptureIndex = 0; newCaptureIndex < newCaptures.Length; newCaptureIndex++) { var newCapture = newCaptures[newCaptureIndex]; int oldCaptureIndex; if (newCapture.Kind == SymbolKind.Parameter) { var newParameterCapture = (IParameterSymbol)newCapture; var newParameterKey = GetParameterKey(newParameterCapture, cancellationToken); if (!TryMapParameter(newParameterKey, map.Reverse, out var oldParameterKey) || !oldParameterCapturesByLambdaAndOrdinal.TryGetValue(oldParameterKey, out oldCaptureIndex)) { // parameter has not been captured prior the edit: diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old parameter capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldParameterCapturesByLambdaAndOrdinal.Remove(oldParameterKey); } else { var newCaptureSyntax = newCapture.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); // variable doesn't exists in the old method or has not been captured prior the edit: if (!map.Reverse.TryGetValue(newCaptureSyntax, out var mappedOldSyntax) || !oldLocalCapturesBySyntax.TryGetValue(mappedOldSyntax, out oldCaptureIndex)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.CapturingVariable, newCapture.Locations.First().SourceSpan, null, new[] { newCapture.Name })); hasErrors = true; continue; } // Remove the old capture so that at the end we can use this hashset // to identify old captures that don't have a corresponding capture in the new version: oldLocalCapturesBySyntax.Remove(mappedOldSyntax); } reverseCapturesMap[newCaptureIndex] = oldCaptureIndex; // the type and scope of parameters can't change if (newCapture.Kind == SymbolKind.Parameter) { continue; } var oldCapture = oldCaptures[oldCaptureIndex]; // Parameter capture can't be changed to local capture and vice versa // because parameters can't be introduced or deleted during EnC // (we checked above for changes in lambda signatures). // Also range variables can't be mapped to other variables since they have // different kinds of declarator syntax nodes. Debug.Assert(oldCapture.Kind == newCapture.Kind); // Range variables don't have types. Each transparent identifier (range variable use) // might have a different type. Changing these types is ok as long as the containing lambda // signatures remain unchanged, which we validate for all lambdas in general. // // The scope of a transparent identifier is the containing lambda body. Since we verify that // each lambda body accesses the same captured variables (including range variables) // the corresponding scopes are guaranteed to be preserved as well. if (oldCapture.Kind == SymbolKind.RangeVariable) { continue; } // rename: // Note that the name has to match exactly even in VB, since we can't rename a field. // Consider: We could allow rename by emitting some special debug info for the field. if (newCapture.Name != oldCapture.Name) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.RenamingCapturedVariable, newCapture.Locations.First().SourceSpan, null, new[] { oldCapture.Name, newCapture.Name })); hasErrors = true; continue; } // type check var oldTypeOpt = GetType(oldCapture); var newTypeOpt = GetType(newCapture); if (!TypesEquivalent(oldTypeOpt, newTypeOpt, exact: false)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableType, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name, oldTypeOpt.ToDisplayString(ErrorDisplayFormat) })); hasErrors = true; continue; } // scope check: var oldScopeOpt = GetCapturedVariableScope(oldCapture, oldMemberBody, cancellationToken); var newScopeOpt = GetCapturedVariableScope(newCapture, newMemberBody, cancellationToken); if (!AreEquivalentClosureScopes(oldScopeOpt, newScopeOpt, map.Reverse)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.ChangingCapturedVariableScope, GetVariableDiagnosticSpan(newCapture), null, new[] { newCapture.Name })); hasErrors = true; continue; } newCapturesToClosureScopes[newCaptureIndex] = newScopeOpt; oldCapturesToClosureScopes[oldCaptureIndex] = oldScopeOpt; } // What's left in oldCapturesBySyntax are captured variables in the previous version // that have no corresponding captured variables in the new version. // Report a rude edit for all such variables. if (oldParameterCapturesByLambdaAndOrdinal.Count > 0) { // syntax-less parameters are not included: var newMemberParametersWithSyntax = newMember.GetParameters(); // uncaptured parameters: foreach (var ((oldContainingLambdaSyntax, ordinal), oldCaptureIndex) in oldParameterCapturesByLambdaAndOrdinal) { var oldCapture = oldCaptures[oldCaptureIndex]; TextSpan span; if (ordinal < 0) { // this parameter: span = GetThisParameterDiagnosticSpan(newMember); } else if (oldContainingLambdaSyntax != null) { // lambda: span = GetLambdaParameterDiagnosticSpan(oldContainingLambdaSyntax, ordinal); } else if (oldCapture.IsImplicitValueParameter()) { // value parameter of a property/indexer setter, event adder/remover: span = newMember.Locations.First().SourceSpan; } else { // method or property: span = GetVariableDiagnosticSpan(newMemberParametersWithSyntax[ordinal]); } diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, span, null, new[] { oldCapture.Name })); } hasErrors = true; } if (oldLocalCapturesBySyntax.Count > 0) { // uncaptured or deleted variables: foreach (var entry in oldLocalCapturesBySyntax) { var oldCaptureNode = entry.Key; var oldCaptureIndex = entry.Value; var name = oldCaptures[oldCaptureIndex].Name; if (map.Forward.TryGetValue(oldCaptureNode, out var newCaptureNode)) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.NotCapturingVariable, newCaptureNode.Span, null, new[] { name })); } else { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.DeletingCapturedVariable, GetDeletedNodeDiagnosticSpan(map.Forward, oldCaptureNode), null, new[] { name })); } } hasErrors = true; } } private void ReportLambdaSignatureRudeEdits( ArrayBuilder<RudeEditDiagnostic> diagnostics, SemanticModel oldModel, SyntaxNode oldLambdaBody, SemanticModel newModel, SyntaxNode newLambdaBody, EditAndContinueCapabilities capabilities, out bool hasSignatureErrors, CancellationToken cancellationToken) { hasSignatureErrors = false; var newLambda = GetLambda(newLambdaBody); var oldLambda = GetLambda(oldLambdaBody); Debug.Assert(IsNestedFunction(newLambda) == IsNestedFunction(oldLambda)); // queries are analyzed separately if (!IsNestedFunction(newLambda)) { return; } if (IsLocalFunction(oldLambda) != IsLocalFunction(newLambda)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.SwitchBetweenLambdaAndLocalFunction, newLambda); hasSignatureErrors = true; return; } var oldLambdaSymbol = GetLambdaExpressionSymbol(oldModel, oldLambda, cancellationToken); var newLambdaSymbol = GetLambdaExpressionSymbol(newModel, newLambda, cancellationToken); // signature validation: if (!ParameterTypesEquivalent(oldLambdaSymbol.Parameters, newLambdaSymbol.Parameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingLambdaParameters, newLambda); hasSignatureErrors = true; } else if (!ReturnTypesEquivalent(oldLambdaSymbol, newLambdaSymbol, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingLambdaReturnType, newLambda); hasSignatureErrors = true; } else if (!TypeParametersEquivalent(oldLambdaSymbol.TypeParameters, newLambdaSymbol.TypeParameters, exact: false)) { ReportUpdateRudeEdit(diagnostics, RudeEditKind.ChangingTypeParameters, newLambda); hasSignatureErrors = true; } if (hasSignatureErrors) { return; } // custom attributes ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol, newLambdaSymbol, newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); for (var i = 0; i < oldLambdaSymbol.Parameters.Length; i++) { ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol.Parameters[i], newLambdaSymbol.Parameters[i], newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); } for (var i = 0; i < oldLambdaSymbol.TypeParameters.Length; i++) { ReportCustomAttributeRudeEdits(diagnostics, oldLambdaSymbol.TypeParameters[i], newLambdaSymbol.TypeParameters[i], newLambda, newModel.Compilation, capabilities, out _, out _, cancellationToken); } } private static ITypeSymbol GetType(ISymbol localOrParameter) => localOrParameter.Kind switch { SymbolKind.Parameter => ((IParameterSymbol)localOrParameter).Type, SymbolKind.Local => ((ILocalSymbol)localOrParameter).Type, _ => throw ExceptionUtilities.UnexpectedValue(localOrParameter.Kind), }; private SyntaxNode GetCapturedVariableScope(ISymbol localOrParameter, SyntaxNode memberBody, CancellationToken cancellationToken) { Debug.Assert(localOrParameter.Kind != SymbolKind.RangeVariable); if (localOrParameter.Kind == SymbolKind.Parameter) { var member = localOrParameter.ContainingSymbol; // lambda parameters and C# constructor parameters are lifted to their own scope: if ((member as IMethodSymbol)?.MethodKind == MethodKind.AnonymousFunction || HasParameterClosureScope(member)) { var result = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); Debug.Assert(IsLambda(result)); return result; } return memberBody; } var node = localOrParameter.DeclaringSyntaxReferences.Single().GetSyntax(cancellationToken); while (true) { RoslynDebug.Assert(node is object); if (IsClosureScope(node)) { return node; } node = node.Parent; } } private static bool AreEquivalentClosureScopes(SyntaxNode oldScopeOpt, SyntaxNode newScopeOpt, IReadOnlyDictionary<SyntaxNode, SyntaxNode> reverseMap) { if (oldScopeOpt == null || newScopeOpt == null) { return oldScopeOpt == newScopeOpt; } return reverseMap.TryGetValue(newScopeOpt, out var mappedScope) && mappedScope == oldScopeOpt; } #endregion #region State Machines private void ReportStateMachineRudeEdits( Compilation oldCompilation, ISymbol oldMember, SyntaxNode newBody, ArrayBuilder<RudeEditDiagnostic> diagnostics) { // Only methods, local functions and anonymous functions can be async/iterators machines, // but don't assume so to be resiliant against errors in code. if (oldMember is not IMethodSymbol oldMethod) { return; } var stateMachineAttributeQualifiedName = oldMethod.IsAsync ? "System.Runtime.CompilerServices.AsyncStateMachineAttribute" : "System.Runtime.CompilerServices.IteratorStateMachineAttribute"; // We assume that the attributes, if exist, are well formed. // If not an error will be reported during EnC delta emit. // Report rude edit if the type is not found in the compilation. // Consider: This diagnostic is cached in the document analysis, // so it could happen that the attribute type is added later to // the compilation and we continue to report the diagnostic. // We could report rude edit when adding these types or flush all // (or specific) document caches. This is not a common scenario though, // since the attribute has been long defined in the BCL. if (oldCompilation.GetTypeByMetadataName(stateMachineAttributeQualifiedName) == null) { diagnostics.Add(new RudeEditDiagnostic( RudeEditKind.UpdatingStateMachineMethodMissingAttribute, GetBodyDiagnosticSpan(newBody, EditKind.Update), newBody, new[] { stateMachineAttributeQualifiedName })); } } #endregion #endregion #region Helpers private static SyntaxNode? TryGetNode(SyntaxNode root, int position) => root.FullSpan.Contains(position) ? root.FindToken(position).Parent : null; internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SyntaxList<T> list) where T : SyntaxNode { foreach (var node in list) { nodes.Add(node); } } internal static void AddNodes<T>(ArrayBuilder<SyntaxNode> nodes, SeparatedSyntaxList<T>? list) where T : SyntaxNode { if (list.HasValue) { foreach (var node in list.Value) { nodes.Add(node); } } } private sealed class TypedConstantComparer : IEqualityComparer<TypedConstant> { public static TypedConstantComparer Instance = new TypedConstantComparer(); public bool Equals(TypedConstant x, TypedConstant y) => x.Kind.Equals(y.Kind) && x.IsNull.Equals(y.IsNull) && SymbolEquivalenceComparer.Instance.Equals(x.Type, y.Type) && x.Kind switch { TypedConstantKind.Array => x.Values.SequenceEqual(y.Values, TypedConstantComparer.Instance), _ => object.Equals(x.Value, y.Value) }; public int GetHashCode(TypedConstant obj) => obj.GetHashCode(); } private sealed class NamedArgumentComparer : IEqualityComparer<KeyValuePair<string, TypedConstant>> { public static NamedArgumentComparer Instance = new NamedArgumentComparer(); public bool Equals(KeyValuePair<string, TypedConstant> x, KeyValuePair<string, TypedConstant> y) => x.Key.Equals(y.Key) && TypedConstantComparer.Instance.Equals(x.Value, y.Value); public int GetHashCode(KeyValuePair<string, TypedConstant> obj) => obj.GetHashCode(); } #pragma warning disable format private static bool IsGlobalMain(ISymbol symbol) => symbol is IMethodSymbol { Name: WellKnownMemberNames.TopLevelStatementsEntryPointMethodName, ContainingType.Name: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName }; #pragma warning restore format private static bool InGenericContext(ISymbol symbol, out bool isGenericMethod) { var current = symbol; while (true) { if (current is IMethodSymbol { Arity: > 0 }) { isGenericMethod = true; return true; } if (current is INamedTypeSymbol { Arity: > 0 }) { isGenericMethod = false; return true; } current = current.ContainingSymbol; if (current == null) { isGenericMethod = false; return false; } } } #endregion #region Testing internal TestAccessor GetTestAccessor() => new(this); internal readonly struct TestAccessor { private readonly AbstractEditAndContinueAnalyzer _abstractEditAndContinueAnalyzer; public TestAccessor(AbstractEditAndContinueAnalyzer abstractEditAndContinueAnalyzer) => _abstractEditAndContinueAnalyzer = abstractEditAndContinueAnalyzer; internal void ReportTopLevelSyntacticRudeEdits(ArrayBuilder<RudeEditDiagnostic> diagnostics, EditScript<SyntaxNode> syntacticEdits, Dictionary<SyntaxNode, EditKind> editMap) => _abstractEditAndContinueAnalyzer.ReportTopLevelSyntacticRudeEdits(diagnostics, syntacticEdits, editMap); internal BidirectionalMap<SyntaxNode> ComputeMap( Match<SyntaxNode> bodyMatch, ArrayBuilder<ActiveNode> activeNodes, ref Dictionary<SyntaxNode, LambdaInfo>? lazyActiveOrMatchedLambdas, ArrayBuilder<RudeEditDiagnostic> diagnostics) { return _abstractEditAndContinueAnalyzer.ComputeMap(bodyMatch, activeNodes, ref lazyActiveOrMatchedLambdas, diagnostics); } internal Match<SyntaxNode> ComputeBodyMatch( SyntaxNode oldBody, SyntaxNode newBody, ActiveNode[] activeNodes, ArrayBuilder<RudeEditDiagnostic> diagnostics, out bool oldHasStateMachineSuspensionPoint, out bool newHasStateMachineSuspensionPoint) { return _abstractEditAndContinueAnalyzer.ComputeBodyMatch(oldBody, newBody, activeNodes, diagnostics, out oldHasStateMachineSuspensionPoint, out newHasStateMachineSuspensionPoint); } } #endregion } }
1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/TypeKeywordRecommender.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 TypeKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public TypeKeywordRecommender() : base(SyntaxKind.TypeKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsTypeAttributeContext(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 TypeKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public TypeKeywordRecommender() : base(SyntaxKind.TypeKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsTypeAttributeContext(cancellationToken); } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/UsingDebugInfoTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { using System; using Debugging; using static MethodDebugInfoValidation; public class UsingDebugInfoTests : ExpressionCompilerTestBase { #region Grouped import strings [Fact] public void SimplestCase() { var source = @" using System; class C { void M() { } } "; var comp = CreateCompilation(source); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "C.M").ImportRecordGroups.Verify(@" { Namespace: string='System' }"); }); } [Fact, WorkItem(21386, "https://github.com/dotnet/roslyn/issues/21386")] public void Gaps() { var source = @" using System; namespace N1 { namespace N2 { using System.Collections; namespace N3 { class C { void M() { } } } } } "; var comp = CreateCompilation(source); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "N1.N2.N3.C.M").ImportRecordGroups.Verify(@" { } { Namespace: string='System.Collections' } { } { Namespace: string='System' }"); }); } [Fact] public void NestedScopes() { var source = @" using System; class C { void M() { int i = 1; { int j = 2; } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); CompileAndVerify(comp).VerifyIL("C.M", @" { // Code size 8 (0x8) .maxstack 1 .locals init (int V_0, //i int V_1) //j IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: nop IL_0004: ldc.i4.2 IL_0005: stloc.1 IL_0006: nop IL_0007: ret } "); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "C.M", ilOffset: 0x0004).ImportRecordGroups.Verify(@" { Namespace: string='System' }"); }); } [Fact] public void NestedNamespaces() { var source = @" using System; namespace A { using System.IO; using System.Text; class C { void M() { } } } "; var comp = CreateCompilation(source); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "A.C.M").ImportRecordGroups.Verify(@" { Namespace: string='System.IO' Namespace: string='System.Text' } { Namespace: string='System' }"); }); } [Fact] public void Forward() { var source = @" using System; namespace A { using System.IO; using System.Text; class C { // One of these methods will forward to the other since they're adjacent. void M1() { } void M2() { } } } "; var comp = CreateCompilation(source); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "A.C.M1").ImportRecordGroups.Verify(@" { Namespace: string='System.IO' Namespace: string='System.Text' } { Namespace: string='System' }"); GetMethodDebugInfo(runtime, "A.C.M2").ImportRecordGroups.Verify(@" { Namespace: string='System.IO' Namespace: string='System.Text' } { Namespace: string='System' }"); }); } [Fact] [WorkItem(30030, "https://github.com/dotnet/roslyn/issues/30030")] public void ImportKinds() { var source = @" extern alias A; using S = System; namespace B { using F = S.IO.File; using System.Text; class C { void M() { } } } "; var aliasedRef = CreateEmptyCompilation("", assemblyName: "Lib").EmitToImageReference(aliases: ImmutableArray.Create("A")); var comp = CreateCompilation(source, new[] { aliasedRef }); WithRuntimeInstance(comp, runtime => { var info = GetMethodDebugInfo(runtime, "B.C.M"); info.ImportRecordGroups.Verify(@" { Namespace: string='System.Text' Type: alias='F' type='System.IO.File' } { Assembly: alias='A' Namespace: alias='S' string='System' }"); info.ExternAliasRecords.Verify( "A = 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'"); }); } [WorkItem(1084059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084059")] [Fact] public void ImportKinds_StaticType() { var libSource = @" namespace N { public static class Static { } } "; var source = @" extern alias A; using static System.Math; namespace B { using static A::N.Static; class C { void M() { } } } "; var aliasedRef = CreateCompilation(libSource, assemblyName: "Lib").EmitToImageReference(aliases: ImmutableArray.Create("A")); var comp = CreateCompilation(source, new[] { aliasedRef }); WithRuntimeInstance(comp, runtime => { var info = GetMethodDebugInfo(runtime, "B.C.M"); info.ImportRecordGroups.Verify(@" { Type: type='N.Static' } { Assembly: alias='A' Type: type='System.Math' }"); info.ExternAliasRecords.Verify( "A = 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'"); }); } [Fact] [WorkItem(30030, "https://github.com/dotnet/roslyn/issues/30030")] public void ForwardToModule() { var source = @" extern alias A; namespace B { using System; class C { void M1() { } } } namespace D { using System.Text; // Different using to prevent normal forwarding. class E { void M2() { } } } "; var aliasedRef = CreateEmptyCompilation("", assemblyName: "Lib").EmitToImageReference(aliases: ImmutableArray.Create("A")); var comp = CreateCompilation(source, new[] { aliasedRef }); WithRuntimeInstance(comp, runtime => { var debugInfo1 = GetMethodDebugInfo(runtime, "B.C.M1"); debugInfo1.ImportRecordGroups.Verify(@" { Namespace: string='System' } { Assembly: alias='A' }"); debugInfo1.ExternAliasRecords.Verify( "A = 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'"); var debugInfo2 = GetMethodDebugInfo(runtime, "D.E.M2"); debugInfo2.ImportRecordGroups.Verify(@" { Namespace: string='System.Text' } { Assembly: alias='A' }"); debugInfo2.ExternAliasRecords.Verify( "A = 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'"); }); } #endregion #region Invalid PDBs [Fact] public void BadPdb_ForwardChain() { const int methodToken1 = 0x600057a; // Forwards to 2 const int methodToken2 = 0x600055d; // Forwards to 3 const int methodToken3 = 0x6000540; // Has a using const string importString = "USystem"; var getMethodCustomDebugInfo = new Func<int, int, byte[]>((token, _) => { switch (token) { case methodToken1: return new MethodDebugInfoBytes.Builder().AddForward(methodToken2).Build().Bytes.ToArray(); case methodToken2: return new MethodDebugInfoBytes.Builder().AddForward(methodToken3).Build().Bytes.ToArray(); case methodToken3: return new MethodDebugInfoBytes.Builder(new[] { new[] { importString } }).Build().Bytes.ToArray(); default: throw null; } }); var getMethodImportStrings = new Func<int, int, ImmutableArray<string>>((token, _) => { switch (token) { case methodToken3: return ImmutableArray.Create(importString); default: throw null; } }); ImmutableArray<string> externAliasStrings; var importStrings = CustomDebugInfoReader.GetCSharpGroupedImportStrings(methodToken1, 0, getMethodCustomDebugInfo, getMethodImportStrings, out externAliasStrings); Assert.True(importStrings.IsDefault); Assert.True(externAliasStrings.IsDefault); importStrings = CustomDebugInfoReader.GetCSharpGroupedImportStrings(methodToken2, 0, getMethodCustomDebugInfo, getMethodImportStrings, out externAliasStrings); Assert.Equal(importString, importStrings.Single().Single()); Assert.Equal(0, externAliasStrings.Length); importStrings = CustomDebugInfoReader.GetCSharpGroupedImportStrings(methodToken2, 0, getMethodCustomDebugInfo, getMethodImportStrings, out externAliasStrings); Assert.Equal(importString, importStrings.Single().Single()); Assert.Equal(0, externAliasStrings.Length); } [Fact] public void BadPdb_Cycle() { const int methodToken1 = 0x600057a; // Forwards to itself var getMethodCustomDebugInfo = new Func<int, int, byte[]>((token, _) => { switch (token) { case methodToken1: return new MethodDebugInfoBytes.Builder().AddForward(methodToken1).Build().Bytes.ToArray(); default: throw null; } }); var getMethodImportStrings = new Func<int, int, ImmutableArray<string>>((token, _) => { return ImmutableArray<string>.Empty; }); ImmutableArray<string> externAliasStrings; var importStrings = CustomDebugInfoReader.GetCSharpGroupedImportStrings(methodToken1, 0, getMethodCustomDebugInfo, getMethodImportStrings, out externAliasStrings); Assert.True(importStrings.IsDefault); Assert.True(externAliasStrings.IsDefault); } [WorkItem(999086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999086")] [Fact] public void BadPdb_InvalidAliasSyntax() { var source = @" public class C { public static void Main() { } } "; var comp = CreateCompilation(source); var peImage = comp.EmitToArray(); var symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports( peImage, "Main", "USystem", // Valid. "UACultureInfo TSystem.Globalization.CultureInfo, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", // Invalid - skipped. "ASI USystem.IO"); // Valid. var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "C.Main"); var compContext = evalContext.CreateCompilationContext(); // Used to throw. var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); Assert.Equal("SI", imports.UsingAliases.Keys.Single()); Assert.Equal(0, imports.ExternAliases.Length); } [WorkItem(999086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999086")] [Fact] public void BadPdb_DotInAlias() { var source = @" public class C { public static void Main() { } } "; var comp = CreateCompilation(source); var peImage = comp.EmitToArray(); var symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports( peImage, "Main", "USystem", // Valid. "AMy.Alias TSystem.Globalization.CultureInfo, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", // Invalid - skipped. "ASI USystem.IO"); // Valid. var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "C.Main"); var compContext = evalContext.CreateCompilationContext(); // Used to throw. var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); Assert.Equal("SI", imports.UsingAliases.Keys.Single()); Assert.Equal(0, imports.ExternAliases.Length); } [WorkItem(1007917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1007917")] [Fact] public void BadPdb_NestingLevel_TooMany() { var source = @" public class C { public static void Main() { } } "; var comp = CreateCompilation(source); var peImage = comp.EmitToArray(); ISymUnmanagedReader symReader; using (var peReader = new PEReader(peImage)) { var metadataReader = peReader.GetMetadataReader(); var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main")); var methodToken = metadataReader.GetToken(methodHandle); symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "USystem", "USystem.IO" } }, suppressUsingInfo: true).AddUsingInfo(1, 1).Build() }, }.ToImmutableDictionary()); } var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "C.Main"); var compContext = evalContext.CreateCompilationContext(); var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal("System.IO", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); // Note: some information is preserved. Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); } [WorkItem(1007917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1007917")] [Fact] public void BadPdb_NestingLevel_TooFew() { var source = @" namespace N { public class C { public static void Main() { } } } "; var comp = CreateCompilation(source); var peImage = comp.EmitToArray(); ISymUnmanagedReader symReader; using (var peReader = new PEReader(peImage)) { var metadataReader = peReader.GetMetadataReader(); var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main")); var methodToken = metadataReader.GetToken(methodHandle); symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "USystem" } }, suppressUsingInfo: true).AddUsingInfo(1).Build() }, }.ToImmutableDictionary()); } var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "N.C.Main"); var compContext = evalContext.CreateCompilationContext(); var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); // Note: some information is preserved. Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); } [WorkItem(1084059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084059")] [Fact] public void BadPdb_NonStaticTypeImport() { var source = @" namespace N { public class C { public static void Main() { } } } "; var comp = CreateCompilation(source); var peImage = comp.EmitToArray(); ISymUnmanagedReader symReader; using (var peReader = new PEReader(peImage)) { var metadataReader = peReader.GetMetadataReader(); var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main")); var methodToken = metadataReader.GetToken(methodHandle); symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "TSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" } }, suppressUsingInfo: true).AddUsingInfo(1).Build() }, }.ToImmutableDictionary()); } var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "N.C.Main"); var compContext = evalContext.CreateCompilationContext(); var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal(0, imports.Usings.Length); // Note: the import is dropped Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); } #endregion Invalid PDBs #region Binder chain [Fact] public void ImportsForSimpleUsing() { var source = @" using System; class C { int M() { return 1; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); var actualNamespace = imports.Usings.Single().NamespaceOrType; Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind); Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind); Assert.Equal("System", actualNamespace.ToTestDisplayString()); }); } [Fact] public void ImportsForMultipleUsings() { var source = @" using System; using System.IO; using System.Text; class C { int M() { return 1; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); var usings = imports.Usings.Select(u => u.NamespaceOrType).ToArray(); Assert.Equal(3, usings.Length); var expectedNames = new[] { "System", "System.IO", "System.Text" }; for (int i = 0; i < usings.Length; i++) { var actualNamespace = usings[i]; Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind); Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind); Assert.Equal(expectedNames[i], actualNamespace.ToTestDisplayString()); } }); } [Fact] public void ImportsForNestedNamespaces() { var source = @" using System; namespace A { using System.IO; class C { int M() { return 1; } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "A.C.M").AsEnumerable().ToArray(); Assert.Equal(2, importsList.Length); var expectedNames = new[] { "System.IO", "System" }; // Innermost-to-outermost for (int i = 0; i < importsList.Length; i++) { var imports = importsList[i]; Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); var actualNamespace = imports.Usings.Single().NamespaceOrType; Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind); Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind); Assert.Equal(expectedNames[i], actualNamespace.ToTestDisplayString()); } }); } [Fact] public void ImportsForNamespaceAlias() { var source = @" using S = System; class C { int M() { return 1; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(0, imports.ExternAliases.Length); var usingAliases = imports.UsingAliases; Assert.Equal(1, usingAliases.Count); Assert.Equal("S", usingAliases.Keys.Single()); var aliasSymbol = usingAliases.Values.Single().Alias; Assert.Equal("S", aliasSymbol.Name); var namespaceSymbol = aliasSymbol.Target; Assert.Equal(SymbolKind.Namespace, namespaceSymbol.Kind); Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)namespaceSymbol).Extent.Kind); Assert.Equal("System", namespaceSymbol.ToTestDisplayString()); }); } [WorkItem(1084059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084059")] [Fact] public void ImportsForStaticType() { var source = @" using static System.Math; class C { int M() { return 1; } } "; var comp = CreateCompilation(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); var actualType = imports.Usings.Single().NamespaceOrType; Assert.Equal(SymbolKind.NamedType, actualType.Kind); Assert.Equal("System.Math", actualType.ToTestDisplayString()); }); } [Fact] public void ImportsForTypeAlias() { var source = @" using I = System.Int32; class C { int M() { return 1; } } "; var comp = CreateCompilation(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(0, imports.ExternAliases.Length); var usingAliases = imports.UsingAliases; Assert.Equal(1, usingAliases.Count); Assert.Equal("I", usingAliases.Keys.Single()); var aliasSymbol = usingAliases.Values.Single().Alias; Assert.Equal("I", aliasSymbol.Name); var typeSymbol = aliasSymbol.Target; Assert.Equal(SymbolKind.NamedType, typeSymbol.Kind); Assert.Equal(SpecialType.System_Int32, ((NamedTypeSymbol)typeSymbol).SpecialType); }); } [Fact] public void ImportsForVerbatimIdentifiers() { var source = @" using @namespace; using @object = @namespace; using @string = @namespace.@class<@namespace.@interface>.@struct; namespace @namespace { public class @class<T> { public struct @struct { } } public interface @interface { } } class C { int M() { return 1; } } "; var comp = CreateCompilation(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.ExternAliases.Length); var @using = imports.Usings.Single(); var importedNamespace = @using.NamespaceOrType; Assert.Equal(SymbolKind.Namespace, importedNamespace.Kind); Assert.Equal("namespace", importedNamespace.Name); var usingAliases = imports.UsingAliases; const string keyword1 = "object"; const string keyword2 = "string"; AssertEx.SetEqual(usingAliases.Keys, keyword1, keyword2); var namespaceAlias = usingAliases[keyword1]; var typeAlias = usingAliases[keyword2]; Assert.Equal(keyword1, namespaceAlias.Alias.Name); var aliasedNamespace = namespaceAlias.Alias.Target; Assert.Equal(SymbolKind.Namespace, aliasedNamespace.Kind); Assert.Equal("@namespace", aliasedNamespace.ToTestDisplayString()); Assert.Equal(keyword2, typeAlias.Alias.Name); var aliasedType = typeAlias.Alias.Target; Assert.Equal(SymbolKind.NamedType, aliasedType.Kind); Assert.Equal("@namespace.@class<@namespace.@interface>.@struct", aliasedType.ToTestDisplayString()); }); } [Fact] public void ImportsForGenericTypeAlias() { var source = @" using I = System.Collections.Generic.IEnumerable<string>; class C { int M() { return 1; } } "; var comp = CreateCompilation(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(0, imports.ExternAliases.Length); var usingAliases = imports.UsingAliases; Assert.Equal(1, usingAliases.Count); Assert.Equal("I", usingAliases.Keys.Single()); var aliasSymbol = usingAliases.Values.Single().Alias; Assert.Equal("I", aliasSymbol.Name); var typeSymbol = aliasSymbol.Target; Assert.Equal(SymbolKind.NamedType, typeSymbol.Kind); Assert.Equal("System.Collections.Generic.IEnumerable<System.String>", typeSymbol.ToTestDisplayString()); }); } [Fact] public void ImportsForExternAlias() { var source = @" extern alias X; class C { int M() { X::System.Xml.Linq.LoadOptions.None.ToString(); return 1; } } "; var comp = CreateCompilation(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("X")) }); comp.VerifyDiagnostics(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(0, imports.UsingAliases.Count); var externAliases = imports.ExternAliases; Assert.Equal(1, externAliases.Length); var aliasSymbol = externAliases.Single().Alias; Assert.Equal("X", aliasSymbol.Name); var targetSymbol = aliasSymbol.Target; Assert.Equal(SymbolKind.Namespace, targetSymbol.Kind); Assert.True(((NamespaceSymbol)targetSymbol).IsGlobalNamespace); Assert.Equal("System.Xml.Linq", targetSymbol.ContainingAssembly.Name); }); } [Fact] public void ImportsForUsingsConsumingExternAlias() { var source = @" extern alias X; using SXL = X::System.Xml.Linq; using LO = X::System.Xml.Linq.LoadOptions; using X::System.Xml; class C { int M() { X::System.Xml.Linq.LoadOptions.None.ToString(); return 1; } } "; var comp = CreateCompilation(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("X")) }); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(1, imports.ExternAliases.Length); var @using = imports.Usings.Single(); var importedNamespace = @using.NamespaceOrType; Assert.Equal(SymbolKind.Namespace, importedNamespace.Kind); Assert.Equal("System.Xml", importedNamespace.ToTestDisplayString()); var usingAliases = imports.UsingAliases; Assert.Equal(2, usingAliases.Count); AssertEx.SetEqual(usingAliases.Keys, "SXL", "LO"); var typeAlias = usingAliases["SXL"].Alias; Assert.Equal("SXL", typeAlias.Name); Assert.Equal("System.Xml.Linq", typeAlias.Target.ToTestDisplayString()); var namespaceAlias = usingAliases["LO"].Alias; Assert.Equal("LO", namespaceAlias.Name); Assert.Equal("System.Xml.Linq.LoadOptions", namespaceAlias.Target.ToTestDisplayString()); }); } [Fact] public void ImportsForUsingsConsumingExternAliasAndGlobal() { var source = @" extern alias X; using A = X::System.Xml.Linq; using B = global::System.Xml.Linq; class C { int M() { A.LoadOptions.None.ToString(); B.LoadOptions.None.ToString(); return 1; } } "; var comp = CreateCompilation(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("global", "X")) }); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(1, imports.ExternAliases.Length); var usingAliases = imports.UsingAliases; Assert.Equal(2, usingAliases.Count); AssertEx.SetEqual(usingAliases.Keys, "A", "B"); var aliasA = usingAliases["A"].Alias; Assert.Equal("A", aliasA.Name); Assert.Equal("System.Xml.Linq", aliasA.Target.ToTestDisplayString()); var aliasB = usingAliases["B"].Alias; Assert.Equal("B", aliasB.Name); Assert.Equal(aliasA.Target, aliasB.Target); }); } private static ImportChain GetImports(RuntimeInstance runtime, string methodName) { var evalContext = CreateMethodContext(runtime, methodName); var compContext = evalContext.CreateCompilationContext(); return compContext.NamespaceBinder.ImportChain; } #endregion Binder chain [Fact] public void NoSymbols() { var source = @"using N; class A { static void M() { } } namespace N { class B { static void M() { } } }"; ResultProperties resultProperties; string error; // With symbols, type reference without namespace qualifier. var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "A.M", expr: "typeof(B)", resultProperties: out resultProperties, error: out error, includeSymbols: true); Assert.Null(error); // Without symbols, type reference without namespace qualifier. testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "A.M", expr: "typeof(B)", resultProperties: out resultProperties, error: out error, includeSymbols: false); Assert.Equal("error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)", error); // With symbols, type reference inside namespace. testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "N.B.M", expr: "typeof(B)", resultProperties: out resultProperties, error: out error, includeSymbols: true); Assert.Null(error); // Without symbols, type reference inside namespace. testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "N.B.M", expr: "typeof(B)", resultProperties: out resultProperties, error: out error, includeSymbols: false); Assert.Null(error); } [WorkItem(2441, "https://github.com/dotnet/roslyn/issues/2441")] [Fact] public void AssemblyQualifiedNameResolutionWithUnification() { var source1 = @" using SI = System.Int32; public class C1 { void M() { } } "; var source2 = @" public class C2 : C1 { } "; var comp1 = CreateEmptyCompilation(source1, new[] { MscorlibRef_v20 }, TestOptions.DebugDll); var module1 = comp1.ToModuleInstance(); var comp2 = CreateEmptyCompilation(source2, new[] { MscorlibRef_v4_0_30316_17626, module1.GetReference() }, TestOptions.DebugDll); var module2 = comp2.ToModuleInstance(); var runtime = CreateRuntimeInstance(new[] { module1, module2, MscorlibRef_v4_0_30316_17626.ToModuleInstance(), ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance() }); var context = CreateMethodContext(runtime, "C1.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("typeof(SI)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""int"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret } "); } } internal static class ImportChainExtensions { internal static Imports Single(this ImportChain importChain) { return importChain.AsEnumerable().Single(); } internal static IEnumerable<Imports> AsEnumerable(this ImportChain importChain) { for (var chain = importChain; chain != null; chain = chain.ParentOpt) { yield return chain.Imports; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { using System; using Debugging; using static MethodDebugInfoValidation; public class UsingDebugInfoTests : ExpressionCompilerTestBase { #region Grouped import strings [Fact] public void SimplestCase() { var source = @" using System; class C { void M() { } } "; var comp = CreateCompilation(source); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "C.M").ImportRecordGroups.Verify(@" { Namespace: string='System' }"); }); } [Fact, WorkItem(21386, "https://github.com/dotnet/roslyn/issues/21386")] public void Gaps() { var source = @" using System; namespace N1 { namespace N2 { using System.Collections; namespace N3 { class C { void M() { } } } } } "; var comp = CreateCompilation(source); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "N1.N2.N3.C.M").ImportRecordGroups.Verify(@" { } { Namespace: string='System.Collections' } { } { Namespace: string='System' }"); }); } [Fact] public void NestedScopes() { var source = @" using System; class C { void M() { int i = 1; { int j = 2; } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); CompileAndVerify(comp).VerifyIL("C.M", @" { // Code size 8 (0x8) .maxstack 1 .locals init (int V_0, //i int V_1) //j IL_0000: nop IL_0001: ldc.i4.1 IL_0002: stloc.0 IL_0003: nop IL_0004: ldc.i4.2 IL_0005: stloc.1 IL_0006: nop IL_0007: ret } "); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "C.M", ilOffset: 0x0004).ImportRecordGroups.Verify(@" { Namespace: string='System' }"); }); } [Fact] public void NestedNamespaces() { var source = @" using System; namespace A { using System.IO; using System.Text; class C { void M() { } } } "; var comp = CreateCompilation(source); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "A.C.M").ImportRecordGroups.Verify(@" { Namespace: string='System.IO' Namespace: string='System.Text' } { Namespace: string='System' }"); }); } [Fact] public void Forward() { var source = @" using System; namespace A { using System.IO; using System.Text; class C { // One of these methods will forward to the other since they're adjacent. void M1() { } void M2() { } } } "; var comp = CreateCompilation(source); WithRuntimeInstance(comp, runtime => { GetMethodDebugInfo(runtime, "A.C.M1").ImportRecordGroups.Verify(@" { Namespace: string='System.IO' Namespace: string='System.Text' } { Namespace: string='System' }"); GetMethodDebugInfo(runtime, "A.C.M2").ImportRecordGroups.Verify(@" { Namespace: string='System.IO' Namespace: string='System.Text' } { Namespace: string='System' }"); }); } [Fact] [WorkItem(30030, "https://github.com/dotnet/roslyn/issues/30030")] public void ImportKinds() { var source = @" extern alias A; using S = System; namespace B { using F = S.IO.File; using System.Text; class C { void M() { } } } "; var aliasedRef = CreateEmptyCompilation("", assemblyName: "Lib").EmitToImageReference(aliases: ImmutableArray.Create("A")); var comp = CreateCompilation(source, new[] { aliasedRef }); WithRuntimeInstance(comp, runtime => { var info = GetMethodDebugInfo(runtime, "B.C.M"); info.ImportRecordGroups.Verify(@" { Namespace: string='System.Text' Type: alias='F' type='System.IO.File' } { Assembly: alias='A' Namespace: alias='S' string='System' }"); info.ExternAliasRecords.Verify( "A = 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'"); }); } [WorkItem(1084059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084059")] [Fact] public void ImportKinds_StaticType() { var libSource = @" namespace N { public static class Static { } } "; var source = @" extern alias A; using static System.Math; namespace B { using static A::N.Static; class C { void M() { } } } "; var aliasedRef = CreateCompilation(libSource, assemblyName: "Lib").EmitToImageReference(aliases: ImmutableArray.Create("A")); var comp = CreateCompilation(source, new[] { aliasedRef }); WithRuntimeInstance(comp, runtime => { var info = GetMethodDebugInfo(runtime, "B.C.M"); info.ImportRecordGroups.Verify(@" { Type: type='N.Static' } { Assembly: alias='A' Type: type='System.Math' }"); info.ExternAliasRecords.Verify( "A = 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'"); }); } [Fact] [WorkItem(30030, "https://github.com/dotnet/roslyn/issues/30030")] public void ForwardToModule() { var source = @" extern alias A; namespace B { using System; class C { void M1() { } } } namespace D { using System.Text; // Different using to prevent normal forwarding. class E { void M2() { } } } "; var aliasedRef = CreateEmptyCompilation("", assemblyName: "Lib").EmitToImageReference(aliases: ImmutableArray.Create("A")); var comp = CreateCompilation(source, new[] { aliasedRef }); WithRuntimeInstance(comp, runtime => { var debugInfo1 = GetMethodDebugInfo(runtime, "B.C.M1"); debugInfo1.ImportRecordGroups.Verify(@" { Namespace: string='System' } { Assembly: alias='A' }"); debugInfo1.ExternAliasRecords.Verify( "A = 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'"); var debugInfo2 = GetMethodDebugInfo(runtime, "D.E.M2"); debugInfo2.ImportRecordGroups.Verify(@" { Namespace: string='System.Text' } { Assembly: alias='A' }"); debugInfo2.ExternAliasRecords.Verify( "A = 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'"); }); } #endregion #region Invalid PDBs [Fact] public void BadPdb_ForwardChain() { const int methodToken1 = 0x600057a; // Forwards to 2 const int methodToken2 = 0x600055d; // Forwards to 3 const int methodToken3 = 0x6000540; // Has a using const string importString = "USystem"; var getMethodCustomDebugInfo = new Func<int, int, byte[]>((token, _) => { switch (token) { case methodToken1: return new MethodDebugInfoBytes.Builder().AddForward(methodToken2).Build().Bytes.ToArray(); case methodToken2: return new MethodDebugInfoBytes.Builder().AddForward(methodToken3).Build().Bytes.ToArray(); case methodToken3: return new MethodDebugInfoBytes.Builder(new[] { new[] { importString } }).Build().Bytes.ToArray(); default: throw null; } }); var getMethodImportStrings = new Func<int, int, ImmutableArray<string>>((token, _) => { switch (token) { case methodToken3: return ImmutableArray.Create(importString); default: throw null; } }); ImmutableArray<string> externAliasStrings; var importStrings = CustomDebugInfoReader.GetCSharpGroupedImportStrings(methodToken1, 0, getMethodCustomDebugInfo, getMethodImportStrings, out externAliasStrings); Assert.True(importStrings.IsDefault); Assert.True(externAliasStrings.IsDefault); importStrings = CustomDebugInfoReader.GetCSharpGroupedImportStrings(methodToken2, 0, getMethodCustomDebugInfo, getMethodImportStrings, out externAliasStrings); Assert.Equal(importString, importStrings.Single().Single()); Assert.Equal(0, externAliasStrings.Length); importStrings = CustomDebugInfoReader.GetCSharpGroupedImportStrings(methodToken2, 0, getMethodCustomDebugInfo, getMethodImportStrings, out externAliasStrings); Assert.Equal(importString, importStrings.Single().Single()); Assert.Equal(0, externAliasStrings.Length); } [Fact] public void BadPdb_Cycle() { const int methodToken1 = 0x600057a; // Forwards to itself var getMethodCustomDebugInfo = new Func<int, int, byte[]>((token, _) => { switch (token) { case methodToken1: return new MethodDebugInfoBytes.Builder().AddForward(methodToken1).Build().Bytes.ToArray(); default: throw null; } }); var getMethodImportStrings = new Func<int, int, ImmutableArray<string>>((token, _) => { return ImmutableArray<string>.Empty; }); ImmutableArray<string> externAliasStrings; var importStrings = CustomDebugInfoReader.GetCSharpGroupedImportStrings(methodToken1, 0, getMethodCustomDebugInfo, getMethodImportStrings, out externAliasStrings); Assert.True(importStrings.IsDefault); Assert.True(externAliasStrings.IsDefault); } [WorkItem(999086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999086")] [Fact] public void BadPdb_InvalidAliasSyntax() { var source = @" public class C { public static void Main() { } } "; var comp = CreateCompilation(source); var peImage = comp.EmitToArray(); var symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports( peImage, "Main", "USystem", // Valid. "UACultureInfo TSystem.Globalization.CultureInfo, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", // Invalid - skipped. "ASI USystem.IO"); // Valid. var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "C.Main"); var compContext = evalContext.CreateCompilationContext(); // Used to throw. var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); Assert.Equal("SI", imports.UsingAliases.Keys.Single()); Assert.Equal(0, imports.ExternAliases.Length); } [WorkItem(999086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/999086")] [Fact] public void BadPdb_DotInAlias() { var source = @" public class C { public static void Main() { } } "; var comp = CreateCompilation(source); var peImage = comp.EmitToArray(); var symReader = ExpressionCompilerTestHelpers.ConstructSymReaderWithImports( peImage, "Main", "USystem", // Valid. "AMy.Alias TSystem.Globalization.CultureInfo, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", // Invalid - skipped. "ASI USystem.IO"); // Valid. var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "C.Main"); var compContext = evalContext.CreateCompilationContext(); // Used to throw. var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); Assert.Equal("SI", imports.UsingAliases.Keys.Single()); Assert.Equal(0, imports.ExternAliases.Length); } [WorkItem(1007917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1007917")] [Fact] public void BadPdb_NestingLevel_TooMany() { var source = @" public class C { public static void Main() { } } "; var comp = CreateCompilation(source); var peImage = comp.EmitToArray(); ISymUnmanagedReader symReader; using (var peReader = new PEReader(peImage)) { var metadataReader = peReader.GetMetadataReader(); var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main")); var methodToken = metadataReader.GetToken(methodHandle); symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "USystem", "USystem.IO" } }, suppressUsingInfo: true).AddUsingInfo(1, 1).Build() }, }.ToImmutableDictionary()); } var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "C.Main"); var compContext = evalContext.CreateCompilationContext(); var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal("System.IO", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); // Note: some information is preserved. Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); } [WorkItem(1007917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1007917")] [Fact] public void BadPdb_NestingLevel_TooFew() { var source = @" namespace N { public class C { public static void Main() { } } } "; var comp = CreateCompilation(source); var peImage = comp.EmitToArray(); ISymUnmanagedReader symReader; using (var peReader = new PEReader(peImage)) { var metadataReader = peReader.GetMetadataReader(); var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main")); var methodToken = metadataReader.GetToken(methodHandle); symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "USystem" } }, suppressUsingInfo: true).AddUsingInfo(1).Build() }, }.ToImmutableDictionary()); } var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "N.C.Main"); var compContext = evalContext.CreateCompilationContext(); var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal("System", imports.Usings.Single().NamespaceOrType.ToTestDisplayString()); // Note: some information is preserved. Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); } [WorkItem(1084059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084059")] [Fact] public void BadPdb_NonStaticTypeImport() { var source = @" namespace N { public class C { public static void Main() { } } } "; var comp = CreateCompilation(source); var peImage = comp.EmitToArray(); ISymUnmanagedReader symReader; using (var peReader = new PEReader(peImage)) { var metadataReader = peReader.GetMetadataReader(); var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, "Main")); var methodToken = metadataReader.GetToken(methodHandle); symReader = new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken, new MethodDebugInfoBytes.Builder(new [] { new[] { "TSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" } }, suppressUsingInfo: true).AddUsingInfo(1).Build() }, }.ToImmutableDictionary()); } var module = ModuleInstance.Create(peImage, symReader); var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef }); var evalContext = CreateMethodContext(runtime, "N.C.Main"); var compContext = evalContext.CreateCompilationContext(); var imports = compContext.NamespaceBinder.ImportChain.Single(); Assert.Equal(0, imports.Usings.Length); // Note: the import is dropped Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); } #endregion Invalid PDBs #region Binder chain [Fact] public void ImportsForSimpleUsing() { var source = @" using System; class C { int M() { return 1; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); var actualNamespace = imports.Usings.Single().NamespaceOrType; Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind); Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind); Assert.Equal("System", actualNamespace.ToTestDisplayString()); }); } [Fact] public void ImportsForMultipleUsings() { var source = @" using System; using System.IO; using System.Text; class C { int M() { return 1; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); var usings = imports.Usings.Select(u => u.NamespaceOrType).ToArray(); Assert.Equal(3, usings.Length); var expectedNames = new[] { "System", "System.IO", "System.Text" }; for (int i = 0; i < usings.Length; i++) { var actualNamespace = usings[i]; Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind); Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind); Assert.Equal(expectedNames[i], actualNamespace.ToTestDisplayString()); } }); } [Fact] public void ImportsForNestedNamespaces() { var source = @" using System; namespace A { using System.IO; class C { int M() { return 1; } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "A.C.M").AsEnumerable().ToArray(); Assert.Equal(2, importsList.Length); var expectedNames = new[] { "System.IO", "System" }; // Innermost-to-outermost for (int i = 0; i < importsList.Length; i++) { var imports = importsList[i]; Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); var actualNamespace = imports.Usings.Single().NamespaceOrType; Assert.Equal(SymbolKind.Namespace, actualNamespace.Kind); Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)actualNamespace).Extent.Kind); Assert.Equal(expectedNames[i], actualNamespace.ToTestDisplayString()); } }); } [Fact] public void ImportsForNamespaceAlias() { var source = @" using S = System; class C { int M() { return 1; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(0, imports.ExternAliases.Length); var usingAliases = imports.UsingAliases; Assert.Equal(1, usingAliases.Count); Assert.Equal("S", usingAliases.Keys.Single()); var aliasSymbol = usingAliases.Values.Single().Alias; Assert.Equal("S", aliasSymbol.Name); var namespaceSymbol = aliasSymbol.Target; Assert.Equal(SymbolKind.Namespace, namespaceSymbol.Kind); Assert.Equal(NamespaceKind.Module, ((NamespaceSymbol)namespaceSymbol).Extent.Kind); Assert.Equal("System", namespaceSymbol.ToTestDisplayString()); }); } [WorkItem(1084059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084059")] [Fact] public void ImportsForStaticType() { var source = @" using static System.Math; class C { int M() { return 1; } } "; var comp = CreateCompilation(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.UsingAliases.Count); Assert.Equal(0, imports.ExternAliases.Length); var actualType = imports.Usings.Single().NamespaceOrType; Assert.Equal(SymbolKind.NamedType, actualType.Kind); Assert.Equal("System.Math", actualType.ToTestDisplayString()); }); } [Fact] public void ImportsForTypeAlias() { var source = @" using I = System.Int32; class C { int M() { return 1; } } "; var comp = CreateCompilation(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(0, imports.ExternAliases.Length); var usingAliases = imports.UsingAliases; Assert.Equal(1, usingAliases.Count); Assert.Equal("I", usingAliases.Keys.Single()); var aliasSymbol = usingAliases.Values.Single().Alias; Assert.Equal("I", aliasSymbol.Name); var typeSymbol = aliasSymbol.Target; Assert.Equal(SymbolKind.NamedType, typeSymbol.Kind); Assert.Equal(SpecialType.System_Int32, ((NamedTypeSymbol)typeSymbol).SpecialType); }); } [Fact] public void ImportsForVerbatimIdentifiers() { var source = @" using @namespace; using @object = @namespace; using @string = @namespace.@class<@namespace.@interface>.@struct; namespace @namespace { public class @class<T> { public struct @struct { } } public interface @interface { } } class C { int M() { return 1; } } "; var comp = CreateCompilation(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.ExternAliases.Length); var @using = imports.Usings.Single(); var importedNamespace = @using.NamespaceOrType; Assert.Equal(SymbolKind.Namespace, importedNamespace.Kind); Assert.Equal("namespace", importedNamespace.Name); var usingAliases = imports.UsingAliases; const string keyword1 = "object"; const string keyword2 = "string"; AssertEx.SetEqual(usingAliases.Keys, keyword1, keyword2); var namespaceAlias = usingAliases[keyword1]; var typeAlias = usingAliases[keyword2]; Assert.Equal(keyword1, namespaceAlias.Alias.Name); var aliasedNamespace = namespaceAlias.Alias.Target; Assert.Equal(SymbolKind.Namespace, aliasedNamespace.Kind); Assert.Equal("@namespace", aliasedNamespace.ToTestDisplayString()); Assert.Equal(keyword2, typeAlias.Alias.Name); var aliasedType = typeAlias.Alias.Target; Assert.Equal(SymbolKind.NamedType, aliasedType.Kind); Assert.Equal("@namespace.@class<@namespace.@interface>.@struct", aliasedType.ToTestDisplayString()); }); } [Fact] public void ImportsForGenericTypeAlias() { var source = @" using I = System.Collections.Generic.IEnumerable<string>; class C { int M() { return 1; } } "; var comp = CreateCompilation(source); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(0, imports.ExternAliases.Length); var usingAliases = imports.UsingAliases; Assert.Equal(1, usingAliases.Count); Assert.Equal("I", usingAliases.Keys.Single()); var aliasSymbol = usingAliases.Values.Single().Alias; Assert.Equal("I", aliasSymbol.Name); var typeSymbol = aliasSymbol.Target; Assert.Equal(SymbolKind.NamedType, typeSymbol.Kind); Assert.Equal("System.Collections.Generic.IEnumerable<System.String>", typeSymbol.ToTestDisplayString()); }); } [Fact] public void ImportsForExternAlias() { var source = @" extern alias X; class C { int M() { X::System.Xml.Linq.LoadOptions.None.ToString(); return 1; } } "; var comp = CreateCompilation(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("X")) }); comp.VerifyDiagnostics(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(0, imports.UsingAliases.Count); var externAliases = imports.ExternAliases; Assert.Equal(1, externAliases.Length); var aliasSymbol = externAliases.Single().Alias; Assert.Equal("X", aliasSymbol.Name); var targetSymbol = aliasSymbol.Target; Assert.Equal(SymbolKind.Namespace, targetSymbol.Kind); Assert.True(((NamespaceSymbol)targetSymbol).IsGlobalNamespace); Assert.Equal("System.Xml.Linq", targetSymbol.ContainingAssembly.Name); }); } [Fact] public void ImportsForUsingsConsumingExternAlias() { var source = @" extern alias X; using SXL = X::System.Xml.Linq; using LO = X::System.Xml.Linq.LoadOptions; using X::System.Xml; class C { int M() { X::System.Xml.Linq.LoadOptions.None.ToString(); return 1; } } "; var comp = CreateCompilation(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("X")) }); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(1, imports.ExternAliases.Length); var @using = imports.Usings.Single(); var importedNamespace = @using.NamespaceOrType; Assert.Equal(SymbolKind.Namespace, importedNamespace.Kind); Assert.Equal("System.Xml", importedNamespace.ToTestDisplayString()); var usingAliases = imports.UsingAliases; Assert.Equal(2, usingAliases.Count); AssertEx.SetEqual(usingAliases.Keys, "SXL", "LO"); var typeAlias = usingAliases["SXL"].Alias; Assert.Equal("SXL", typeAlias.Name); Assert.Equal("System.Xml.Linq", typeAlias.Target.ToTestDisplayString()); var namespaceAlias = usingAliases["LO"].Alias; Assert.Equal("LO", namespaceAlias.Name); Assert.Equal("System.Xml.Linq.LoadOptions", namespaceAlias.Target.ToTestDisplayString()); }); } [Fact] public void ImportsForUsingsConsumingExternAliasAndGlobal() { var source = @" extern alias X; using A = X::System.Xml.Linq; using B = global::System.Xml.Linq; class C { int M() { A.LoadOptions.None.ToString(); B.LoadOptions.None.ToString(); return 1; } } "; var comp = CreateCompilation(source, new[] { SystemXmlLinqRef.WithAliases(ImmutableArray.Create("global", "X")) }); comp.GetDiagnostics().Where(d => d.Severity > DiagnosticSeverity.Info).Verify(); WithRuntimeInstance(comp, runtime => { var importsList = GetImports(runtime, "C.M"); var imports = importsList.Single(); Assert.Equal(0, imports.Usings.Length); Assert.Equal(1, imports.ExternAliases.Length); var usingAliases = imports.UsingAliases; Assert.Equal(2, usingAliases.Count); AssertEx.SetEqual(usingAliases.Keys, "A", "B"); var aliasA = usingAliases["A"].Alias; Assert.Equal("A", aliasA.Name); Assert.Equal("System.Xml.Linq", aliasA.Target.ToTestDisplayString()); var aliasB = usingAliases["B"].Alias; Assert.Equal("B", aliasB.Name); Assert.Equal(aliasA.Target, aliasB.Target); }); } private static ImportChain GetImports(RuntimeInstance runtime, string methodName) { var evalContext = CreateMethodContext(runtime, methodName); var compContext = evalContext.CreateCompilationContext(); return compContext.NamespaceBinder.ImportChain; } #endregion Binder chain [Fact] public void NoSymbols() { var source = @"using N; class A { static void M() { } } namespace N { class B { static void M() { } } }"; ResultProperties resultProperties; string error; // With symbols, type reference without namespace qualifier. var testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "A.M", expr: "typeof(B)", resultProperties: out resultProperties, error: out error, includeSymbols: true); Assert.Null(error); // Without symbols, type reference without namespace qualifier. testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "A.M", expr: "typeof(B)", resultProperties: out resultProperties, error: out error, includeSymbols: false); Assert.Equal("error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?)", error); // With symbols, type reference inside namespace. testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "N.B.M", expr: "typeof(B)", resultProperties: out resultProperties, error: out error, includeSymbols: true); Assert.Null(error); // Without symbols, type reference inside namespace. testData = Evaluate( source, OutputKind.DynamicallyLinkedLibrary, methodName: "N.B.M", expr: "typeof(B)", resultProperties: out resultProperties, error: out error, includeSymbols: false); Assert.Null(error); } [WorkItem(2441, "https://github.com/dotnet/roslyn/issues/2441")] [Fact] public void AssemblyQualifiedNameResolutionWithUnification() { var source1 = @" using SI = System.Int32; public class C1 { void M() { } } "; var source2 = @" public class C2 : C1 { } "; var comp1 = CreateEmptyCompilation(source1, new[] { MscorlibRef_v20 }, TestOptions.DebugDll); var module1 = comp1.ToModuleInstance(); var comp2 = CreateEmptyCompilation(source2, new[] { MscorlibRef_v4_0_30316_17626, module1.GetReference() }, TestOptions.DebugDll); var module2 = comp2.ToModuleInstance(); var runtime = CreateRuntimeInstance(new[] { module1, module2, MscorlibRef_v4_0_30316_17626.ToModuleInstance(), ExpressionCompilerTestHelpers.IntrinsicAssemblyReference.ToModuleInstance() }); var context = CreateMethodContext(runtime, "C1.M"); string error; var testData = new CompilationTestData(); context.CompileExpression("typeof(SI)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL(@" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""int"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret } "); } } internal static class ImportChainExtensions { internal static Imports Single(this ImportChain importChain) { return importChain.AsEnumerable().Single(); } internal static IEnumerable<Imports> AsEnumerable(this ImportChain importChain) { for (var chain = importChain; chain != null; chain = chain.ParentOpt) { yield return chain.Imports; } } } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Compilers/Core/Portable/DiagnosticAnalyzer/SymbolDeclaredCompilationEvent.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.Diagnostics { /// <summary> /// An event for each declaration in the program (namespace, type, method, field, parameter, etc). /// Note that some symbols may have multiple declarations (namespaces, partial types) and may therefore /// have multiple events. /// </summary> internal sealed class SymbolDeclaredCompilationEvent : CompilationEvent { private readonly Lazy<ImmutableArray<SyntaxReference>> _lazyCachedDeclaringReferences; public SymbolDeclaredCompilationEvent(Compilation compilation, ISymbol symbol, SemanticModel? semanticModelWithCachedBoundNodes = null) : base(compilation) { Symbol = symbol; SemanticModelWithCachedBoundNodes = semanticModelWithCachedBoundNodes; _lazyCachedDeclaringReferences = new Lazy<ImmutableArray<SyntaxReference>>(() => symbol.DeclaringSyntaxReferences); } public ISymbol Symbol { get; } public SemanticModel? SemanticModelWithCachedBoundNodes { get; } // PERF: We avoid allocations in re-computing syntax references for declared symbol during event processing by caching them directly on this member. public ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => _lazyCachedDeclaringReferences.Value; public override string ToString() { var name = Symbol.Name; if (name == "") name = "<empty>"; var loc = DeclaringSyntaxReferences.Length != 0 ? " @ " + string.Join(", ", System.Linq.Enumerable.Select(DeclaringSyntaxReferences, r => r.GetLocation().GetLineSpan())) : null; return "SymbolDeclaredCompilationEvent(" + name + " " + Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) + loc + ")"; } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics { /// <summary> /// An event for each declaration in the program (namespace, type, method, field, parameter, etc). /// Note that some symbols may have multiple declarations (namespaces, partial types) and may therefore /// have multiple events. /// </summary> internal sealed class SymbolDeclaredCompilationEvent : CompilationEvent { private readonly Lazy<ImmutableArray<SyntaxReference>> _lazyCachedDeclaringReferences; public SymbolDeclaredCompilationEvent(Compilation compilation, ISymbol symbol, SemanticModel? semanticModelWithCachedBoundNodes = null) : base(compilation) { Symbol = symbol; SemanticModelWithCachedBoundNodes = semanticModelWithCachedBoundNodes; _lazyCachedDeclaringReferences = new Lazy<ImmutableArray<SyntaxReference>>(() => symbol.DeclaringSyntaxReferences); } public ISymbol Symbol { get; } public SemanticModel? SemanticModelWithCachedBoundNodes { get; } // PERF: We avoid allocations in re-computing syntax references for declared symbol during event processing by caching them directly on this member. public ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => _lazyCachedDeclaringReferences.Value; public override string ToString() { var name = Symbol.Name; if (name == "") name = "<empty>"; var loc = DeclaringSyntaxReferences.Length != 0 ? " @ " + string.Join(", ", System.Linq.Enumerable.Select(DeclaringSyntaxReferences, r => r.GetLocation().GetLineSpan())) : null; return "SymbolDeclaredCompilationEvent(" + name + " " + Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat) + loc + ")"; } } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpGenerateFromUsage.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; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpGenerateFromUsage : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpGenerateFromUsage(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpGenerateFromUsage)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateLocal)] public void GenerateLocal() { SetUpEditor( @"class Program { static void Main(string[] args) { string s = $$xyz; } }"); VisualStudio.Editor.Verify.CodeAction("Generate local 'xyz'", applyFix: true); VisualStudio.Editor.Verify.TextContains( @"class Program { static void Main(string[] args) { string xyz = null; string s = xyz; } }"); } } }
// Licensed to the .NET Foundation under one or more 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; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpGenerateFromUsage : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpGenerateFromUsage(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpGenerateFromUsage)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateLocal)] public void GenerateLocal() { SetUpEditor( @"class Program { static void Main(string[] args) { string s = $$xyz; } }"); VisualStudio.Editor.Verify.CodeAction("Generate local 'xyz'", applyFix: true); VisualStudio.Editor.Verify.TextContains( @"class Program { static void Main(string[] args) { string xyz = null; string s = xyz; } }"); } } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Workspaces/Core/Portable/SymbolKey/SymbolKey.MethodSymbolKey.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; namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class ReducedExtensionMethodSymbolKey { public static void Create(IMethodSymbol symbol, SymbolKeyWriter visitor) { Debug.Assert(symbol.Equals(symbol.ConstructedFrom)); visitor.WriteSymbolKey(symbol.ReducedFrom); visitor.WriteSymbolKey(symbol.ReceiverType); } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var reducedFromResolution = reader.ReadSymbolKey(out var reducedFromFailureReason); if (reducedFromFailureReason != null) { failureReason = $"({nameof(ReducedExtensionMethodSymbolKey)} {nameof(reducedFromResolution)} failed -> {reducedFromFailureReason})"; return default; } var receiverTypeResolution = reader.ReadSymbolKey(out var receiverTypeFailureReason); if (receiverTypeFailureReason != null) { failureReason = $"({nameof(ReducedExtensionMethodSymbolKey)} {nameof(receiverTypeResolution)} failed -> {receiverTypeFailureReason})"; return default; } using var result = PooledArrayBuilder<IMethodSymbol>.GetInstance(); foreach (var reducedFrom in reducedFromResolution.OfType<IMethodSymbol>()) { foreach (var receiverType in receiverTypeResolution.OfType<ITypeSymbol>()) { result.AddIfNotNull(reducedFrom.ReduceExtensionMethod(receiverType)); } } return CreateResolution(result, $"({nameof(ReducedExtensionMethodSymbolKey)} failed)", out failureReason); } } } internal partial struct SymbolKey { private static class ConstructedMethodSymbolKey { public static void Create(IMethodSymbol symbol, SymbolKeyWriter visitor) { visitor.WriteSymbolKey(symbol.ConstructedFrom); visitor.WriteSymbolKeyArray(symbol.TypeArguments); } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var constructedFrom = reader.ReadSymbolKey(out var constructedFromFailureReason); if (constructedFromFailureReason != null) { failureReason = $"({nameof(ConstructedMethodSymbolKey)} {nameof(constructedFrom)} failed -> {constructedFromFailureReason})"; return default; } using var typeArguments = reader.ReadSymbolKeyArray<ITypeSymbol>(out var typeArgumentsFailureReason); if (typeArgumentsFailureReason != null) { failureReason = $"({nameof(ConstructedMethodSymbolKey)} {nameof(typeArguments)} failed -> {typeArgumentsFailureReason})"; return default; } if (constructedFrom.SymbolCount == 0 || typeArguments.IsDefault) { failureReason = $"({nameof(ConstructedMethodSymbolKey)} {nameof(typeArguments)} failed -> 'constructedFrom.SymbolCount == 0 || typeArguments.IsDefault')"; return default; } var typeArgumentArray = typeArguments.Builder.ToArray(); using var result = PooledArrayBuilder<IMethodSymbol>.GetInstance(); foreach (var method in constructedFrom.OfType<IMethodSymbol>()) { if (method.TypeParameters.Length == typeArgumentArray.Length) { result.AddIfNotNull(method.Construct(typeArgumentArray)); } } return CreateResolution(result, $"({nameof(ConstructedMethodSymbolKey)} could not successfully construct)", out failureReason); } } } internal partial struct SymbolKey { private static class MethodSymbolKey { public static void Create(IMethodSymbol symbol, SymbolKeyWriter visitor) { Debug.Assert(symbol.Equals(symbol.ConstructedFrom)); visitor.WriteString(symbol.MetadataName); visitor.WriteSymbolKey(symbol.ContainingSymbol); visitor.WriteInteger(symbol.Arity); visitor.WriteBoolean(symbol.PartialDefinitionPart != null); visitor.WriteRefKindArray(symbol.Parameters); // Mark that we're writing out the signature of a method. This way if we hit a // method type parameter in our parameter-list or return type, we won't recurse // into it, but will instead only write out the type parameter ordinal. This // happens with cases like Goo<T>(T t); visitor.PushMethod(symbol); visitor.WriteParameterTypesArray(symbol.OriginalDefinition.Parameters); if (symbol.MethodKind == MethodKind.Conversion) { visitor.WriteSymbolKey(symbol.ReturnType); } else { visitor.WriteSymbolKey(null); } // Done writing the signature of this method. Remove it from the set of methods // we're writing signatures for. visitor.PopMethod(symbol); } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var metadataName = reader.ReadString()!; var containingType = reader.ReadSymbolKey(out var containingTypeFailureReason); var arity = reader.ReadInteger(); var isPartialMethodImplementationPart = reader.ReadBoolean(); using var parameterRefKinds = reader.ReadRefKindArray(); // For each method that we look at, we'll have to resolve the parameter list and // return type in the context of that method. i.e. if we have Goo<T>(IList<T> list) // then we'll need to have marked that we're on the Goo<T> method so that we know // 'T' in IList<T> resolves to. // // Because of this, we keep track of where we are in the reader. Before resolving // every parameter list, we'll mark which method we're on and we'll rewind to this // point. var beforeParametersPosition = reader.Position; using var methods = GetMembersOfNamedType<IMethodSymbol>(containingType, metadataName: null); using var result = PooledArrayBuilder<IMethodSymbol>.GetInstance(); foreach (var candidate in methods) { var method = Resolve(reader, metadataName, arity, isPartialMethodImplementationPart, parameterRefKinds, beforeParametersPosition, candidate); // Note: after finding the first method that matches we stop. That's necessary // as we cache results while searching. We don't want to override these positive // matches with a negative ones if we were to continue searching. if (method != null) { result.AddIfNotNull(method); break; } } if (reader.Position == beforeParametersPosition) { // We didn't find any candidates. We still need to stream through this // method signature so the reader is in a proper position. // Push an null-method to our stack so that any method-type-parameters // can at least be read (if not resolved) properly. reader.PushMethod(method: null); // read out the values. We don't actually need to use them, but we have // to effectively read past them in the string. using (reader.ReadSymbolKeyArray<ITypeSymbol>(out _)) { _ = reader.ReadSymbolKey(out _); } reader.PopMethod(method: null); } if (containingTypeFailureReason != null) { failureReason = $"({nameof(MethodSymbolKey)} {nameof(containingType)} failed -> {containingTypeFailureReason})"; return default; } return CreateResolution(result, $"({nameof(MethodSymbolKey)} '{metadataName}' not found)", out failureReason); } private static IMethodSymbol? Resolve( SymbolKeyReader reader, string metadataName, int arity, bool isPartialMethodImplementationPart, PooledArrayBuilder<RefKind> parameterRefKinds, int beforeParametersPosition, IMethodSymbol method) { if (method.Arity == arity && method.MetadataName == metadataName && ParameterRefKindsMatch(method.Parameters, parameterRefKinds)) { // Method looks like a potential match. It has the right arity, name and // refkinds match. We now need to do the more complicated work of checking // the parameters (and possibly the return type). This is more complicated // because those symbols might refer to method type parameters. In order // for resolution to work on those type parameters, we have to keep track // in the reader that we're resolving this method. // Restore our position to right before the list of parameters. Also, push // this method into our method-resolution-stack so that we can properly resolve // method type parameter ordinals. reader.Position = beforeParametersPosition; reader.PushMethod(method); var result = Resolve(reader, isPartialMethodImplementationPart, method); reader.PopMethod(method); if (result != null) { return result; } } return null; } private static IMethodSymbol? Resolve( SymbolKeyReader reader, bool isPartialMethodImplementationPart, IMethodSymbol method) { using var originalParameterTypes = reader.ReadSymbolKeyArray<ITypeSymbol>(out _); var returnType = (ITypeSymbol?)reader.ReadSymbolKey(out _).GetAnySymbol(); if (reader.ParameterTypesMatch(method.OriginalDefinition.Parameters, originalParameterTypes)) { if (returnType == null || reader.Comparer.Equals(returnType, method.ReturnType)) { if (isPartialMethodImplementationPart) { method = method.PartialImplementationPart ?? method; } Debug.Assert(method != null); return method; } } 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.Diagnostics; namespace Microsoft.CodeAnalysis { internal partial struct SymbolKey { private static class ReducedExtensionMethodSymbolKey { public static void Create(IMethodSymbol symbol, SymbolKeyWriter visitor) { Debug.Assert(symbol.Equals(symbol.ConstructedFrom)); visitor.WriteSymbolKey(symbol.ReducedFrom); visitor.WriteSymbolKey(symbol.ReceiverType); } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var reducedFromResolution = reader.ReadSymbolKey(out var reducedFromFailureReason); if (reducedFromFailureReason != null) { failureReason = $"({nameof(ReducedExtensionMethodSymbolKey)} {nameof(reducedFromResolution)} failed -> {reducedFromFailureReason})"; return default; } var receiverTypeResolution = reader.ReadSymbolKey(out var receiverTypeFailureReason); if (receiverTypeFailureReason != null) { failureReason = $"({nameof(ReducedExtensionMethodSymbolKey)} {nameof(receiverTypeResolution)} failed -> {receiverTypeFailureReason})"; return default; } using var result = PooledArrayBuilder<IMethodSymbol>.GetInstance(); foreach (var reducedFrom in reducedFromResolution.OfType<IMethodSymbol>()) { foreach (var receiverType in receiverTypeResolution.OfType<ITypeSymbol>()) { result.AddIfNotNull(reducedFrom.ReduceExtensionMethod(receiverType)); } } return CreateResolution(result, $"({nameof(ReducedExtensionMethodSymbolKey)} failed)", out failureReason); } } } internal partial struct SymbolKey { private static class ConstructedMethodSymbolKey { public static void Create(IMethodSymbol symbol, SymbolKeyWriter visitor) { visitor.WriteSymbolKey(symbol.ConstructedFrom); visitor.WriteSymbolKeyArray(symbol.TypeArguments); } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var constructedFrom = reader.ReadSymbolKey(out var constructedFromFailureReason); if (constructedFromFailureReason != null) { failureReason = $"({nameof(ConstructedMethodSymbolKey)} {nameof(constructedFrom)} failed -> {constructedFromFailureReason})"; return default; } using var typeArguments = reader.ReadSymbolKeyArray<ITypeSymbol>(out var typeArgumentsFailureReason); if (typeArgumentsFailureReason != null) { failureReason = $"({nameof(ConstructedMethodSymbolKey)} {nameof(typeArguments)} failed -> {typeArgumentsFailureReason})"; return default; } if (constructedFrom.SymbolCount == 0 || typeArguments.IsDefault) { failureReason = $"({nameof(ConstructedMethodSymbolKey)} {nameof(typeArguments)} failed -> 'constructedFrom.SymbolCount == 0 || typeArguments.IsDefault')"; return default; } var typeArgumentArray = typeArguments.Builder.ToArray(); using var result = PooledArrayBuilder<IMethodSymbol>.GetInstance(); foreach (var method in constructedFrom.OfType<IMethodSymbol>()) { if (method.TypeParameters.Length == typeArgumentArray.Length) { result.AddIfNotNull(method.Construct(typeArgumentArray)); } } return CreateResolution(result, $"({nameof(ConstructedMethodSymbolKey)} could not successfully construct)", out failureReason); } } } internal partial struct SymbolKey { private static class MethodSymbolKey { public static void Create(IMethodSymbol symbol, SymbolKeyWriter visitor) { Debug.Assert(symbol.Equals(symbol.ConstructedFrom)); visitor.WriteString(symbol.MetadataName); visitor.WriteSymbolKey(symbol.ContainingSymbol); visitor.WriteInteger(symbol.Arity); visitor.WriteBoolean(symbol.PartialDefinitionPart != null); visitor.WriteRefKindArray(symbol.Parameters); // Mark that we're writing out the signature of a method. This way if we hit a // method type parameter in our parameter-list or return type, we won't recurse // into it, but will instead only write out the type parameter ordinal. This // happens with cases like Goo<T>(T t); visitor.PushMethod(symbol); visitor.WriteParameterTypesArray(symbol.OriginalDefinition.Parameters); if (symbol.MethodKind == MethodKind.Conversion) { visitor.WriteSymbolKey(symbol.ReturnType); } else { visitor.WriteSymbolKey(null); } // Done writing the signature of this method. Remove it from the set of methods // we're writing signatures for. visitor.PopMethod(symbol); } public static SymbolKeyResolution Resolve(SymbolKeyReader reader, out string? failureReason) { var metadataName = reader.ReadString()!; var containingType = reader.ReadSymbolKey(out var containingTypeFailureReason); var arity = reader.ReadInteger(); var isPartialMethodImplementationPart = reader.ReadBoolean(); using var parameterRefKinds = reader.ReadRefKindArray(); // For each method that we look at, we'll have to resolve the parameter list and // return type in the context of that method. i.e. if we have Goo<T>(IList<T> list) // then we'll need to have marked that we're on the Goo<T> method so that we know // 'T' in IList<T> resolves to. // // Because of this, we keep track of where we are in the reader. Before resolving // every parameter list, we'll mark which method we're on and we'll rewind to this // point. var beforeParametersPosition = reader.Position; using var methods = GetMembersOfNamedType<IMethodSymbol>(containingType, metadataName: null); using var result = PooledArrayBuilder<IMethodSymbol>.GetInstance(); foreach (var candidate in methods) { var method = Resolve(reader, metadataName, arity, isPartialMethodImplementationPart, parameterRefKinds, beforeParametersPosition, candidate); // Note: after finding the first method that matches we stop. That's necessary // as we cache results while searching. We don't want to override these positive // matches with a negative ones if we were to continue searching. if (method != null) { result.AddIfNotNull(method); break; } } if (reader.Position == beforeParametersPosition) { // We didn't find any candidates. We still need to stream through this // method signature so the reader is in a proper position. // Push an null-method to our stack so that any method-type-parameters // can at least be read (if not resolved) properly. reader.PushMethod(method: null); // read out the values. We don't actually need to use them, but we have // to effectively read past them in the string. using (reader.ReadSymbolKeyArray<ITypeSymbol>(out _)) { _ = reader.ReadSymbolKey(out _); } reader.PopMethod(method: null); } if (containingTypeFailureReason != null) { failureReason = $"({nameof(MethodSymbolKey)} {nameof(containingType)} failed -> {containingTypeFailureReason})"; return default; } return CreateResolution(result, $"({nameof(MethodSymbolKey)} '{metadataName}' not found)", out failureReason); } private static IMethodSymbol? Resolve( SymbolKeyReader reader, string metadataName, int arity, bool isPartialMethodImplementationPart, PooledArrayBuilder<RefKind> parameterRefKinds, int beforeParametersPosition, IMethodSymbol method) { if (method.Arity == arity && method.MetadataName == metadataName && ParameterRefKindsMatch(method.Parameters, parameterRefKinds)) { // Method looks like a potential match. It has the right arity, name and // refkinds match. We now need to do the more complicated work of checking // the parameters (and possibly the return type). This is more complicated // because those symbols might refer to method type parameters. In order // for resolution to work on those type parameters, we have to keep track // in the reader that we're resolving this method. // Restore our position to right before the list of parameters. Also, push // this method into our method-resolution-stack so that we can properly resolve // method type parameter ordinals. reader.Position = beforeParametersPosition; reader.PushMethod(method); var result = Resolve(reader, isPartialMethodImplementationPart, method); reader.PopMethod(method); if (result != null) { return result; } } return null; } private static IMethodSymbol? Resolve( SymbolKeyReader reader, bool isPartialMethodImplementationPart, IMethodSymbol method) { using var originalParameterTypes = reader.ReadSymbolKeyArray<ITypeSymbol>(out _); var returnType = (ITypeSymbol?)reader.ReadSymbolKey(out _).GetAnySymbol(); if (reader.ParameterTypesMatch(method.OriginalDefinition.Parameters, originalParameterTypes)) { if (returnType == null || reader.Comparer.Equals(returnType, method.ReturnType)) { if (isPartialMethodImplementationPart) { method = method.PartialImplementationPart ?? method; } Debug.Assert(method != null); return method; } } return null; } } } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/EditorFeatures/CSharpTest/EditAndContinue/ActiveStatementTests.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.CSharp.Syntax; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.CSharp.UnitTests; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class ActiveStatementTests : EditingTestBase { #region Update [Fact] public void Update_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { <AS:1>Goo(2);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } [Fact] public void Update_Inner_NewCommentAtEndOfActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1>// } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } /// <summary> /// CreateNewOnMetadataUpdate has no effect in presence of active statements (in break mode). /// </summary> [Fact] public void Update_Inner_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main() { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main() { while (true) { <AS:1>Goo(2);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } [Fact] public void Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { <AS:1>Goo(1);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a + 1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Update_Leaf_NewCommentAtEndOfActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0>// } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } /// <summary> /// CreateNewOnMetadataUpdate has no effect in presence of active statements (in break mode). /// </summary> [Fact] public void Update_Leaf_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main(string[] args) { while (true) { <AS:1>Goo(1);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a + 1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemantics(active, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Goo"), preserveLocalVariables: true) }); } [WorkItem(846588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846588")] [Fact] public void Update_Leaf_Block() { var src1 = @" class C : System.IDisposable { public void Dispose() {} static void Main(string[] args) { using (<AS:0>C x = null</AS:0>) {} } }"; var src2 = @" class C : System.IDisposable { public void Dispose() {} static void Main(string[] args) { using (<AS:0>C x = new C()</AS:0>) {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Delete in Method Body [Fact] public void Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { } <AS:1>}</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } // TODO (tomat): considering a change [Fact] public void Delete_Inner_MultipleParents() { var src1 = @" class C : IDisposable { unsafe static void Main(string[] args) { { <AS:1>Goo(1);</AS:1> } if (true) { <AS:2>Goo(2);</AS:2> } else { <AS:3>Goo(3);</AS:3> } int x = 1; switch (x) { case 1: case 2: <AS:4>Goo(4);</AS:4> break; default: <AS:5>Goo(5);</AS:5> break; } checked { <AS:6>Goo(4);</AS:6> } unchecked { <AS:7>Goo(7);</AS:7> } while (true) <AS:8>Goo(8);</AS:8> do <AS:9>Goo(9);</AS:9> while (true); for (int i = 0; i < 10; i++) <AS:10>Goo(10);</AS:10> foreach (var i in new[] { 1, 2}) <AS:11>Goo(11);</AS:11> using (var z = new C()) <AS:12>Goo(12);</AS:12> fixed (char* p = ""s"") <AS:13>Goo(13);</AS:13> label: <AS:14>Goo(14);</AS:14> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C : IDisposable { unsafe static void Main(string[] args) { { <AS:1>}</AS:1> if (true) { <AS:2>}</AS:2> else { <AS:3>}</AS:3> int x = 1; switch (x) { case 1: case 2: <AS:4>break;</AS:4> default: <AS:5>break;</AS:5> } checked { <AS:6>}</AS:6> unchecked { <AS:7>}</AS:7> <AS:8>while (true)</AS:8> { } do { } <AS:9>while (true);</AS:9> for (int i = 0; i < 10; <AS:10>i++</AS:10>) { } foreach (var i <AS:11>in</AS:11> new[] { 1, 2 }) { } using (<AS:12>var z = new C()</AS:12>) { } fixed (<AS:13>char* p = ""s""</AS:13>) { } label: <AS:14>{</AS:14> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "case 2:", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "default:", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "while (true)", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "do", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "for (int i = 0; i < 10; i++ )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "foreach (var i in new[] { 1, 2 })", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "using ( var z = new C() )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "fixed ( char* p = \"s\" )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "label", FeaturesResources.code)); } [Fact] public void Delete_Leaf1() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>}</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf2() { var src1 = @" class C { static void Goo(int a) { Console.WriteLine(1); Console.WriteLine(2); <AS:0>Console.WriteLine(3);</AS:0> Console.WriteLine(4); } }"; var src2 = @" class C { static void Goo(int a) { Console.WriteLine(1); Console.WriteLine(2); <AS:0>Console.WriteLine(4);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf_InTry() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { <AS:0>Console.WriteLine(a);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { <AS:0>}</AS:0> catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf_InTry2() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { try { <AS:0>Console.WriteLine(a);</AS:0> } catch { } } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { try { <AS:0>}</AS:0> catch { } } catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Inner_CommentActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { //Goo(1); <AS:1>}</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [WorkItem(755959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755959")] [Fact] public void Delete_Leaf_CommentActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { //Console.WriteLine(a); <AS:0>}</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_EntireNamespace() { var src1 = @" namespace N { class C { static void Main(String[] args) { <AS:0>Console.WriteLine(1);</AS:0> } } }"; var src2 = @"<AS:0></AS:0>"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.Delete, null, FeaturesResources.namespace_), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "N.C"))); } #endregion #region Constructors [WorkItem(740949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/740949")] [Fact] public void Updated_Inner_Constructor() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5*2);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo f = new Goo(5*2);")); } [WorkItem(741249, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/741249")] [Fact] public void Updated_Leaf_Constructor() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a*2;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_Constructor_Parameter() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a)</AS:0> { this.value = a; } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int b)</AS:0> { this.value = b; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Goo..ctor")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_Constructor_Parameter_DefaultValue() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a = 5)</AS:0> { this.value = a; } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a = 42)</AS:0> { this.value = a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InitializerUpdate, "int a = 42", FeaturesResources.parameter)); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_ConstructorChaining1() { var src1 = @" using System; class Test { static void Main(string[] args) { <AS:1>B b = new B(2, 3);</AS:1> } } class B : A { public B(int x, int y) : <AS:0>base(x + y, x - y)</AS:0> { } } class A { public A(int x, int y) : this(5 + x, y, 0) { } public A(int x, int y, int z) { } }"; var src2 = @" using System; class Test { static void Main(string[] args) { <AS:1>B b = new B(2, 3);</AS:1> } } class B : A { public B(int x, int y) : <AS:0>base(x + y + 5, x - y)</AS:0> { } } class A { public A(int x, int y) : this(x, y, 0) { } public A(int x, int y, int z) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_ConstructorChaining2() { var src1 = @" using System; class Test { static void Main(string[] args) { <AS:2>B b = new B(2, 3);</AS:2> } } class B : A { public B(int x, int y) : <AS:1>base(x + y, x - y)</AS:1> { } } class A { public A(int x, int y) : <AS:0>this(x, y, 0)</AS:0> { } public A(int x, int y, int z) { } }"; var src2 = @" using System; class Test { static void Main(string[] args) { <AS:2>B b = new B(2, 3);</AS:2> } } class B : A { public B(int x, int y) : <AS:1>base(x + y, x - y)</AS:1> { } } class A { public A(int x, int y) : <AS:0>this(5 + x, y, 0)</AS:0> { } public A(int x, int y, int z) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void InstanceConstructorWithoutInitializer() { var src1 = @" class C { int a = 5; <AS:0>public C(int a)</AS:0> { } static void Main(string[] args) { <AS:1>C c = new C(3);</AS:1> } }"; var src2 = @" class C { int a = 42; <AS:0>public C(int a)</AS:0> { } static void Main(string[] args) { <AS:1>C c = new C(3);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update1() { var src1 = @" class D { public D(int d) {} } class C : D { int a = 5; public C(int a) : <AS:2>this(true)</AS:2> { } public C(bool b) : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:3>C c = new C(3);</AS:3> } }"; var src2 = @" class D { public D(int d) {} } class C : D { int a = 5; public C(int a) : <AS:2>this(false)</AS:2> { } public C(bool b) : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:3>C c = new C(3);</AS:3> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "this(false)")); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update2() { var src1 = @" class D { public D(int d) {} } class C : D { public C() : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class D { public D(int d) {} } class C : D { <AS:1>public C()</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "public C()")); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update3() { var src1 = @" class D { public D(int d) <AS:0>{</AS:0> } } class C : D { <AS:1>public C()</AS:1> {} }"; var src2 = @" class D { public D(int d) <AS:0>{</AS:0> } } class C : D { public C() : <AS:1>base(1)</AS:1> {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "base(1)")); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update1() { var src1 = @" class D { public D(int d) { } } class C : D { public C() : <AS:0>base(1)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update2() { var src1 = @" class D { public D() { } public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D() { } public D(int d) { } } class C : D { <AS:0>public C()</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update3() { var src1 = @" class D { public D() { } public D(int d) { } } class C : D { <AS:0>public C()</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D() { } public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update1() { var src1 = @" class C { public C() : this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> }) { } }"; var src2 = @" class C { public C() : base((a, b) => { <AS:0>Console.WriteLine(a - b);</AS:0> }) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update2() { var src1 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var src2 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update3() { var src1 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var src2 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a - b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory] [InlineData("class ")] [InlineData("struct")] public void InstanceConstructor_DeleteParameterless(string typeKind) { var src1 = "partial " + typeKind + " C { public C() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var src2 = "<AS:0>partial " + typeKind + " C</AS:0> { }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "partial " + typeKind + " C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } #endregion #region Field and Property Initializers [Theory] [InlineData("class ")] [InlineData("struct")] public void InstancePropertyInitializer_Leaf_Update(string typeKind) { var src1 = @" " + typeKind + @" C { int a { get; } = <AS:0>1</AS:0>; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { int a { get; } = <AS:0>2</AS:0>; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory] [InlineData("class ")] [InlineData("struct")] public void InstancePropertyInitializer_Leaf_Update_SynthesizedConstructor(string typeKind) { var src1 = @" " + typeKind + @" C { int a { get; } = <AS:0>1</AS:0>; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { int a { get; } = <AS:0>2</AS:0>; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Theory] [InlineData("class ")] [InlineData("struct")] public void InstanceFieldInitializer_Leaf_Update1(string typeKind) { var src1 = @" " + typeKind + @" C { <AS:0>int a = 1</AS:0>, b = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { <AS:0>int a = 2</AS:0>, b = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory] [InlineData("class ")] [InlineData("struct")] public void InstanceFieldInitializer_Leaf_Update1_SynthesizedConstructor(string typeKind) { var src1 = @" " + typeKind + @" C { <AS:0>int a = 1</AS:0>, b = 2; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { <AS:0>int a = 2</AS:0>, b = 2; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Update1() { var src1 = @" class C { <AS:1>int a = F(1)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>int a = F(2)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "int a = F(2)")); } [Fact] public void InstanceFieldInitializer_Internal_Update2() { var src1 = @" class C { int a = F(1), <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { int a = F(1), <AS:1>b = F(3)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "b = F(3)")); } [Fact] public void InstancePropertyInitializer_Internal_Delete1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; int b { get; } = 2; }"; var src2 = @" class C { int a { get { return 1; } } int b { get; } = <AS:0>2</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyInitializer_Internal_Delete2() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; static int s { get; } = 2; int b { get; } = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class C { int a { get; } static int s { get; } = 2; int b { get; } = <AS:0>3</AS:0>; public C() { } static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Delete1() { var src1 = @" class C { <AS:1>int a = F(1)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { int a, <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Delete2() { var src1 = @" class C { int a = F(1), <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>int a, b;</AS:1> public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyAndFieldInitializers_Delete1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; static int s { get; } = 2; int b = 2; }"; var src2 = @" class C { int a { get; } static int s { get; } = 2; <AS:0>int b = 3;</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyAndFieldInitializers_Delete2() { var src1 = @" class C { int a = <AS:0>1</AS:0>; static int s { get; } = 2; int b { get; } = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class C { int a; static int s { get; } = 2; int b { get; } = <AS:0>3</AS:0>; public C() { } static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_SingleDeclarator() { var src1 = @" class C { <AS:1>public static readonly int a = F(1);</AS:1> public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>public static readonly int <TS:1>a = F(1)</TS:1>;</AS:1> public C() {} public static int F(int a) { <TS:0><AS:0>return a + 1;</AS:0></TS:0> } static void Main(string[] args) { <TS:2><AS:2>C c = new C();</AS:2></TS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Lambda1() { var src1 = @" class C { Func<int, int> a = z => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var src2 = @" class C { Func<int, int> a = F(z => <AS:0>z + 1</AS:0>); static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void PropertyInitializer_Lambda1() { var src1 = @" class C { Func<int, int> a { get; } = z => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var src2 = @" class C { Func<int, int> a { get; } = F(z => <AS:0>z + 1</AS:0>); static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Lambda2() { var src1 = @" class C { Func<int, Func<int>> a = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var src2 = @" class C { Func<int, Func<int>> a = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void PropertyInitializer_Lambda2() { var src1 = @" class C { Func<int, Func<int>> a { get; } = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var src2 = @" class C { Func<int, Func<int>> a { get; } = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_InsertConst1() { var src1 = @" class C { <AS:0>int a = 1</AS:0>; public C() {} }"; var src2 = @" class C { <AS:0>const int a = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a = 1 ;]@24 -> [const int a = 1;]@24"); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1", FeaturesResources.const_field)); } [Fact] public void LocalInitializer_InsertConst1() { var src1 = @" class C { public void M() { <AS:0>int a = 1</AS:0>; } }"; var src2 = @" class C { public void M() { const int a = 1; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_InsertConst2() { var src1 = @" class C { int <AS:0>a = 1</AS:0>, b = 2; public C() {} }"; var src2 = @" class C { <AS:0>const int a = 1, b = 2;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1, b = 2", FeaturesResources.const_field), Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1, b = 2", FeaturesResources.const_field)); } [Fact] public void LocalInitializer_InsertConst2() { var src1 = @" class C { public void M() { int <AS:0>a = 1</AS:0>, b = 2; } }"; var src2 = @" class C { public void M() { const int a = 1, b = 2; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete1() { var src1 = @" class C { <AS:0>int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { int a; <AS:0>int b = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LocalInitializer_Delete1() { var src1 = @" class C { public void M() { <AS:0>int a = 1</AS:0>; } }"; var src2 = @" class C { public void M() { int a; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete2() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { <AS:0>int b = 1;</AS:0> int c; int a; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LocalInitializer_Delete2() { var src1 = @" class C { public void M() { int b = 1; int c; <AS:0>int a = 1;</AS:0> } }"; var src2 = @" class C { public void M() { int b = 1; int c; int a; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete3() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { <AS:0>int b = 1;</AS:0> int c; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void LocalInitializer_Delete3() { var src1 = @" class C { public void M() { int b = 1; int c; <AS:0>int a = 1;</AS:0> } }"; var src2 = @" class C { public void M() { int b = 1; int c; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance1() { var src1 = @" class C { <AS:0>int a = 1;</AS:0> static int b = 1; int c = 1; public C() {} }"; var src2 = @" class C { int a; static int b = 1; <AS:0>int c = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance2() { var src1 = @" class C { static int c = 1; <AS:0>static int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { <AS:0>static int c = 1;</AS:0> static int a; int b = 1; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance3() { var src1 = @" class C { <AS:0>static int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { <AS:0>static int a;</AS:0> int b = 1; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteMove1() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { int c; <AS:0>int b = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Move, "int c", FeaturesResources.field), Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void LocalInitializer_DeleteReorder1() { var src1 = @" class C { public void M() { int b = 1; <AS:0>int a = 1;</AS:0> int c; } }"; var src2 = @" class C { public void M() { int c; <AS:0>int b = 1;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldToProperty1() { var src1 = @" class C { int a = <AS:0>1</AS:0>; }"; // The placement of the active statement is not ideal, but acceptable. var src2 = @" <AS:0>class C</AS:0> { int a { get; } = 1; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void PropertyToField1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; }"; // The placement of the active statement is not ideal, but acceptable. var src2 = @" <AS:0>class C</AS:0> { int a = 1; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.auto_property, "a"))); } #endregion #region Lock Statement [Fact] public void LockBody_Update() { var src1 = @" class Test { private static object F() { <AS:0>return new object();</AS:0> } static void Main(string[] args) { <AS:1>lock (F())</AS:1> { System.Console.Write(0); } } }"; var src2 = @" class Test { private static object F() { <AS:0>return new object();</AS:0> } static void Main(string[] args) { <AS:1>lock (F())</AS:1> { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755749")] [Fact] public void Lock_Insert_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { <AS:0>System.Console.Write(5);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (lockThis)", CSharpFeaturesResources.lock_statement)); } [WorkItem(755749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755749")] [Fact] public void Lock_Insert_Leaf2() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { { System.Console.Write(5); <AS:0>}</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (lockThis)", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Insert_Leaf3() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { { System.Console.Write(5); } <AS:0>System.Console.Write(10);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Insert_Leaf4() { var src1 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (a) { lock (b) { lock (c) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (b) { lock (d) { lock (a) { lock (e) { <AS:0>System.Console.Write();</AS:0> } } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (d)", CSharpFeaturesResources.lock_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (e)", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Insert_Leaf5() { var src1 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (a) { lock (c) { lock (b) { lock (e) { <AS:0>System.Console.Write();</AS:0> } } } } } }"; var src2 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (b) { lock (d) { lock (a) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (d)", CSharpFeaturesResources.lock_statement)); } [WorkItem(755752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755752")] [Fact] public void Lock_Update_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (""test"") { <AS:0>System.Console.Write(5);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (\"test\")", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Update_Leaf2() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (""test"") { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Delete_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Update_Lambda1() { var src1 = @" class C { static void Main(string[] args) { lock (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void Main(string[] args) { lock (F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Update_Lambda2() { var src1 = @" class C { static void Main(string[] args) { lock (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void Main(string[] args) { lock (G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (G(a => a))", CSharpFeaturesResources.lock_statement)); } #endregion #region Fixed Statement [Fact] public void FixedBody_Update() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { unsafe { char* px2; fixed (<AS:1>char* pj = &F()</AS:1>) { System.Console.WriteLine(0); } } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { unsafe { char* px2; fixed (<AS:1>char* pj = &F()</AS:1>) { System.Console.WriteLine(1); } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Insert_Leaf() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* pj = &value)", CSharpFeaturesResources.fixed_statement)); } [Fact] public void Fixed_Insert_Leaf2() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>}</AS:0> } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { px2 = null; } <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Insert_Leaf3() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> fixed (int* pj = &value) { } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* pj = &value)", CSharpFeaturesResources.fixed_statement)); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Reorder_Leaf1() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* a = &value) { fixed (int* b = &value) { <AS:0>px2 = null;</AS:0> } } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* b = &value) { fixed (int* a = &value) { <AS:0>px2 = null;</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755746")] [Fact] public void Fixed_Update_Leaf1() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* p = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* p = &value)", CSharpFeaturesResources.fixed_statement)); } [WorkItem(755746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755746")] [Fact] public void Fixed_Update_Leaf2() { var src1 = @" class Test { public static int value1 = 10; public static int value2 = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* a = &value1) { fixed (int* b = &value1) { fixed (int* c = &value1) { <AS:0>px2 = null;</AS:0> } } } } } }"; var src2 = @" class Test { public static int value1 = 10; public static int value2 = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* c = &value1) { fixed (int* d = &value1) { fixed (int* a = &value2) { fixed (int* e = &value1) { <AS:0>px2 = null;</AS:0> } } } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* a = &value2)", CSharpFeaturesResources.fixed_statement), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* d = &value1)", CSharpFeaturesResources.fixed_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* e = &value1)", CSharpFeaturesResources.fixed_statement)); } [Fact] public void Fixed_Delete_Leaf() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Fixed_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Fixed_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (byte* p = &G(a => a))", CSharpFeaturesResources.fixed_statement)); } #endregion #region ForEach Statement [Fact] public void ForEachBody_Update_ExpressionActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c in <AS:1>F()</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c in <AS:1>F()</AS:1>) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_ExpressionActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) in <AS:1>F()</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) in <AS:1>F()</AS:1>) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_InKeywordActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c <AS:1>in</AS:1> F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c <AS:1>in</AS:1> F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_InKeywordActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) <AS:1>in</AS:1> F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) <AS:1>in</AS:1> F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_VariableActive() { var src1 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_VariableActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>(string s, int i)</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>(string s, int i)</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_ForeachKeywordActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> (char c in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> (char c in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_ForeachKeywordActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> ((string s, int i) in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> ((string s, int i) in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Update() { var src1 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>object c</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // not ideal, but good enough: edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "object c"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach ( object c in F())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEachDeconstructionVariable_Update() { var src1 = @" class Test { private static (int, (bool, double))[] F() { <AS:0>return new[] { (1, (true, 2.0)) };</AS:0> } static void Main(string[] args) { foreach (<AS:1>(int i, (bool b, double d))</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (int, (bool, double))[] F() { <AS:0>return new[] { (1, (true, 2.0)) };</AS:0> } static void Main(string[] args) { foreach (<AS:1>(int i, (var b, double d))</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "(int i, (var b, double d))"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach ( (int i, (var b, double d)) in F())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Reorder_Leaf() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Reorder_Leaf() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { foreach ((var a1, var a2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Update_Leaf() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var b in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var c in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var a in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEachVariable_Update_Leaf() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { foreach ((var a1, var a2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var c in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach ((int b1, bool b2) in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach ((var a1, var a2) in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Delete_Leaf1() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf1() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Delete_Leaf2() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf2() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Delete_Leaf3() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf3() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Lambda1() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { Action a = () => { <AS:0>System.Console.Write();</AS:0> }; <AS:1>a();</AS:1> } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { Action a = () => { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } }; } <AS:1>a();</AS:1> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var a in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var b in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { foreach (var a in G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach (var a in G(a => a))", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Update_Nullable() { var src1 = @" class C { static void F() { var arr = new int?[] { 0 }; foreach (var s in arr) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void F() { var arr = new int[] { 0 }; foreach (var s in arr) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_DeleteBody() { var src1 = @" class C { static void F() { foreach (var s in new[] { 1 }) <AS:0>G();</AS:0> } } "; var src2 = @" class C { static void F() { foreach (var s in new[] { 1 }) <AS:0>;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_DeleteBody() { var src1 = @" class C { static void F() { foreach ((var a1, var a2) in new[] { (1,1) }) <AS:0>G();</AS:0> } } "; var src2 = @" class C { static void F() { foreach ((var a1, var a2) in new[] { (1,1) }) <AS:0>;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region For Statement [Fact] public void ForStatement_Initializer1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(2)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "i = F(2)")); } [Fact] public void ForStatement_Initializer2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>, F(1); i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>, F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Initializer_Delete() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (; <AS:1>i < 10</AS:1>; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "for (; i < 10 ; i++)", FeaturesResources.code)); } [Fact] public void ForStatement_Declarator1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>var i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>var i = F(2)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "var i = F(2)")); } [Fact] public void ForStatement_Declarator2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(1); i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Declarator3() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Condition1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(10)</AS:1>; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(20)</AS:1>; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "i < F(20)")); } [Fact] public void ForStatement_Condition_Delete() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(10)</AS:1>; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; ; <AS:1>i++</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "for (int i = 1; ; i++ )", FeaturesResources.code)); } [Fact] public void ForStatement_Incrementors1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(20); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Incrementors2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(2)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(2)")); } [Fact] public void ForStatement_Incrementors3() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>, i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Incrementors4() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>, i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); i++, <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Using Statement and Local Declaration [Fact] public void UsingStatement_Expression_Update_Leaf() { var src1 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; static void Main(string[] args) { using (a) { using (b) { <AS:0>System.Console.Write();</AS:0> } } } }"; var src2 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; static void Main(string[] args) { using (a) { using (c) { using (b) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Using with an expression generates code that stores the value of the expression in a compiler-generated temp. // This temp is not initialized when using is added around an active statement so the disposal is a no-op. // The user might expect that the object the field points to is disposed at the end of the using block, but it isn't. edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "using (c)", CSharpFeaturesResources.using_statement)); } [Fact] public void UsingStatement_Declaration_Update_Leaf() { var src1 = @" class Test { static void Main(string[] args) { using (var a = new Disposable()) { using (var b = new Disposable()) { <AS:0>System.Console.Write();</AS:0> } } } }"; var src2 = @" class Test { static void Main(string[] args) { using (var a = new Disposable()) { using (var c = new Disposable()) { using (var b = new Disposable()) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using with a declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_Leaf1() { var src1 = @" class Test { static void Main(string[] args) { using var a = new Disposable(), b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { using var a = new Disposable(), c = new Disposable(), b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using local declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_Leaf2() { var src1 = @" class Test { static void Main(string[] args) { using var a = new Disposable(); using var b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { using var a = new Disposable(); using var c = new Disposable(); using var b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using local declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Update_NonLeaf1() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingStatement_Update_NonLeaf2() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (Disposable a = new Disposable(1), b = Disposable(2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (Disposable a = new Disposable(1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingStatement_Update_NonLeaf_Lambda() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(() => 1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(() => 2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_NonLeaf1() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(1); using Disposable b = new Disposable(2), c = new Disposable(3); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(1); using Disposable b = new Disposable(20), c = new Disposable(3); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingLocalDeclaration_Update_NonLeaf_Lambda() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(() => 1); { using var x = new Disposable(1); } using Disposable b = new Disposable(() => 2), c = new Disposable(() => 3); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(() => 10); { using var x = new Disposable(2); } Console.WriteLine(1); using Disposable b = new Disposable(() => 20), c = new Disposable(() => 30); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Expression_InLambdaBody1() { var src1 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; public static System.IDisposable d = null; static void Main(string[] args) { using (a) { Action a = () => { using (b) { <AS:0>System.Console.Write();</AS:0> } }; } <AS:1>a();</AS:1> } }"; var src2 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; public static System.IDisposable d = null; static void Main(string[] args) { using (d) { Action a = () => { using (c) { using (b) { <AS:0>System.Console.Write();</AS:0> } } }; } <AS:1>a();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "using (c)", CSharpFeaturesResources.using_statement)); } [Fact] public void UsingStatement_Expression_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { using (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { using (F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Expression_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { using (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { using (G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "using (G(a => a))", CSharpFeaturesResources.using_statement)); } #endregion #region Conditional Block Statements (If, Switch, While, Do) [Fact] public void IfBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void IfBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (!B())</AS:1> { System.Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "if (!B())")); } [Fact] public void IfBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>if (B(() => 1))</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>if (B(() => 2))</AS:1> { System.Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void WhileBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void WhileBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (!B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "while (!B())")); } [Fact] public void WhileBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>while (B(() => 1))</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>while (B(() => 2))</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B());</AS:1> } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (B());</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B());</AS:1> } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (!B());</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "while (!B());")); } [Fact] public void DoWhileBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B(() => 1));</AS:1> } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (B(() => 2));</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Delete() { var src1 = @" class C { static void F() { do <AS:0>G();</AS:0> while (true); } } "; var src2 = @" class C { static void F() { do <AS:0>;</AS:0> while (true); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchCase_Update1() { var src1 = @" class C { public static string F() <AS:0>{</AS:0> return null; } public static void Main() { <AS:1>switch (F())</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(1); break; } } }"; var src2 = @" class C { public static string F() <AS:0>{</AS:0> return null; } public static void Main() { <AS:1>switch (F())</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(2); break; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchCase_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>switch (B(() => 1))</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(1); break; } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>switch (B(() => 2))</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(2); break; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Switch Statement When Clauses, Patterns [Fact] public void SwitchWhenClause_PatternUpdate1() { var src1 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; case byte a when G5(a): return 10; case double b when G2(b): return 20; case C { X: 2 } when G4(9): return 30; case C { X: 2, Y: C { X: 1 } } c1 when G3(c1): return 40; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; case byte a when G5(a): return 10; case double b when G2(b): return 20; case C { X: 2 } when G4(9): return 30; case C { X: 2, Y: C { X: 2 } } c1 when G3(c1): return 40; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_PatternInsert() { var src1 = @" class C { public static int Main() { switch (F()) { case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_PatternDelete() { var src1 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenDelete() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1: case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenAdd() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1: case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenUpdate() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1 * 2): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchWhenClause_UpdateGoverningExpression() { var src1 = @" class C { public static int Main() { switch (F(1)) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F(2)) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F(2))", CSharpFeaturesResources.switch_statement)); } [Fact] public void Switch_PropertyPattern_Update_NonLeaf() { var src1 = @" class C { public int X { get => <AS:0>1</AS:0>; } public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C { X: 1 }: return 1; } return 0; } }"; var src2 = @" class C { public int X { get => <AS:0>1</AS:0>; } public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C { X: 2 }: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (obj)")); } [Fact] public void Switch_PositionalPattern_Update_NonLeaf() { var src1 = @" class C { public void Deconstruct(out int x) => <AS:0>x = X</AS:0>; public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C ( x: 1 ): return 1; } return 0; } }"; var src2 = @" class C { public void Deconstruct(out int x) => <AS:0>x = X</AS:0>; public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C ( x: 2 ): return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (obj)")); } [Fact] public void Switch_VarPattern_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case var (x, y): return 1; case 2: return 2; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case var (x, y): return 1; case 3: return 2; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (G())")); } [Fact] public void Switch_DiscardPattern_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case bool _: return 1; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case int _: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (G())")); } [Fact] public void Switch_NoPatterns_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case 1: return 1; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case 2: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Switch Expression [Fact] public void SwitchExpression() { var src1 = @" class C { public static int Main() { Console.WriteLine(1); <AS:4>return F() switch { int a <AS:0>when F1()</AS:0> => <AS:1>F2()</AS:1>, bool b => <AS:2>F3()</AS:2>, _ => <AS:3>F4()</AS:3> };</AS:4> } }"; var src2 = @" class C { public static int Main() { Console.WriteLine(2); <AS:4>return F() switch { int a <AS:0>when F1()</AS:0> => <AS:1>F2()</AS:1>, bool b => <AS:2>F3()</AS:2>, _ => <AS:3>F4()</AS:3> };</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchExpression_Lambda1() { var src1 = @" class C { public static int Main() => <AS:1>F() switch { 0 => new Func<int>(() => <AS:0>1</AS:0>)(), _ => 2}</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>F() switch { 0 => new Func<int>(() => <AS:0>3</AS:0>)(), _ => 2}</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchExpression_Lambda2() { var src1 = @" class C { public static int Main() => <AS:1>F() switch { i => new Func<int>(() => <AS:0>i + 1</AS:0>)(), _ => 2}</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>F() switch { i => new Func<int>(() => <AS:0>i + 3</AS:0>)(), _ => 2}</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_MemberExpressionBody() { var src1 = @" class C { public static int Main() => <AS:0>F() switch { 0 => 1, _ => 2}</AS:0>; }"; var src2 = @" class C { public static int Main() => <AS:0>G() switch { 0 => 10, _ => 20}</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_LambdaBody() { var src1 = @" class C { public static Func<int> M() => () => <AS:0>F() switch { 0 => 1, _ => 2}</AS:0>; }"; var src2 = @" class C { public static Func<int> M() => () => <AS:0>G() switch { 0 => 10, _ => 20}</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_QueryLambdaBody() { var src1 = @" class C { public static IEnumerable<int> M() { return from a in new[] { 1 } where <AS:0>F() <AS:1>switch { 0 => true, _ => false}</AS:0>/**/</AS:1> select a; } }"; var src2 = @" class C { public static IEnumerable<int> M() { return from a in new[] { 2 } where <AS:0>F() <AS:1>switch { 0 => true, _ => false}</AS:0>/**/</AS:1> select a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_NestedInGoverningExpression() { var src1 = @" class C { public static int Main() => <AS:1>(F() switch { 0 => 1, _ => 2 }) switch { 1 => <AS:0>10</AS:0>, _ => 20 }</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>(G() switch { 0 => 10, _ => 20 }) switch { 10 => <AS:0>100</AS:0>, _ => 200 }</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "(G() switch { 0 => 10, _ => 20 }) switch { 10 => 100 , _ => 200 }")); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_NestedInArm() { var src1 = @" class C { public static int Main() => F1() switch { 1 when F2() <AS:0>switch { 0 => true, _ => false }</AS:0> => F3() <AS:1>switch { 0 => 1, _ => 2 }</AS:1>, _ => 20 }; }"; var src2 = @" class C { public static int Main() => F1() switch { 1 when F2() <AS:0>switch { 0 => true, _ => false }</AS:0> => F3() <AS:1>switch { 0 => 1, _ => 2 }</AS:1>, _ => 20 }; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete1() { var src1 = @" class C { public static int Main() { return Method() switch { true => G(), _ => F2() switch { 1 => <AS:0>0</AS:0>, _ => 2 } }; } }"; var src2 = @" class C { public static int Main() { return Method() switch { true => G(), _ => <AS:0>1</AS:0> }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete2() { var src1 = @" class C { public static int Main() { return F1() switch { 1 => 0, _ => F2() switch { 1 => <AS:0>0</AS:0>, _ => 2 } }; } }"; var src2 = @" class C { public static int Main() { return F1() switch { 1 => <AS:0>0</AS:0>, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete3() { var src1 = @" class C { public static int Main() { return F1() switch { 1 when F2() switch { 1 => <AS:0>true</AS:0>, _ => false } => 0, _ => 2 }; } }"; var src2 = @" class C { public static int Main() { return F1() switch { 1 <AS:0>when F3()</AS:0> => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Try [Fact] public void Try_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } catch { } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "try", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch (IOException) { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "try", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Update_Inner2() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> Console.WriteLine(2); } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFinally_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>finally { }</ER:1.0> Console.WriteLine(2); } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch (IOException) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFinally_DeleteStatement_Inner() { var src1 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>Console.WriteLine(1);</AS:1> } <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var src2 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>}</AS:1> finally { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void TryFinally_DeleteStatement_Leaf() { var src1 = @" class C { static void Main(string[] args) { <ER:0.0>try { Console.WriteLine(0); } finally { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { Console.WriteLine(0); } finally { <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Try_DeleteStatement_Inner() { var src1 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>Console.WriteLine(1);</AS:1> } <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var src2 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>}</AS:1> <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void Try_DeleteStatement_Leaf() { var src1 = @" class C { static void Main() { try { <AS:0>Console.WriteLine(1);</AS:0> } finally { Console.WriteLine(2); } } }"; var src2 = @" class C { static void Main() { try { <AS:0>}</AS:0> finally { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Catch [Fact] public void Catch_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } catch { <AS:1>Goo();</AS:1> } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } catch { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Console.WriteLine(1);", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_InFilter_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (Exception) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch (IOException) { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(2))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "when (Goo(2))"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Leaf1() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(1))</AS:0> { }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(2))</AS:0> { }</ER:0.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Leaf2() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(1))</AS:0> { }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (Exception) <AS:0>when (Goo(1))</AS:0> { }<ER:0.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } #endregion #region Finally [Fact] public void Finally_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } finally { <AS:1>Goo();</AS:1> } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } finally { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { <ER:1.0>try { } finally { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <ER:0.0>try { } finally { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Console.WriteLine(1);", CSharpFeaturesResources.finally_clause)); } #endregion #region Try-Catch-Finally [Fact] public void TryCatchFinally() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (Exception) { try { try { } finally { try { <AS:1>Goo();</AS:1> } catch { } } } catch (Exception) { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "try", CSharpFeaturesResources.try_block), Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.try_block), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact, WorkItem(23865, "https://github.com/dotnet/roslyn/issues/23865")] public void TryCatchFinally_Regions() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: this is incorrect, we need to report a rude edit: edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(23865, "https://github.com/dotnet/roslyn/issues/23865")] public void TryCatchFinally2_Regions() { var src1 = @" class C { static void Main(string[] args) { try { try { try { try { <AS:1>Goo();</AS:1> } <ER:1.3>catch { }</ER:1.3> } <ER:1.2>catch (Exception) { }</ER:1.2> } <ER:1.1>finally { }</ER:1.1> } <ER:1.0>catch (IOException) { } finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { try { try { try { <AS:1>Goo();</AS:1> } <ER:1.3>catch { }</ER:1.3> } <ER:1.2>catch (Exception) { }</ER:1.2> } <ER:1.1>finally { }</ER:1.1> } <ER:1.0>catch (IOException) { } finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: this is incorrect, we need to report a rude edit since an ER span has been changed (empty line added): edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFilter_Regions1() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) when (e == null) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) when (e == null) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFilter_Regions2() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) <AS:1>when (e == null)</AS:1> { Goo(); }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) <AS:1>when (e == null)</AS:1> { Goo(); }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Lambda1() { var src1 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = null; try { f = x => <AS:1>1 + Goo(x)</AS:1>; } catch { } <AS:2>Console.Write(f(2));</AS:2> } }"; var src2 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = null; f = x => <AS:1>1 + Goo(x)</AS:1>; <AS:2>Console.Write(f(2));</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Lambda2() { var src1 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = x => { try { <AS:1>return 1 + Goo(x);</AS:1> } <ER:1.0>catch { }</ER:1.0> }; <AS:2>Console.Write(f(2));</AS:2> } }"; var src2 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = x => { <AS:1>return 1 + Goo(x);</AS:1> }; <AS:2>Console.Write(f(2));</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "return 1 + Goo(x);", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Query_Join1() { var src1 = @" class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { try { q = from x in xs join y in ys on <AS:1>F()</AS:1> equals G() select 1; } catch { } <AS:2>q.ToArray();</AS:2> } }"; var src2 = @" class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { q = from x in xs join y in ys on <AS:1>F()</AS:1> equals G() select 1; <AS:2>q.ToArray();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Checked/Unchecked [Fact] public void CheckedUnchecked_Insert_Leaf() { var src1 = @" class Test { static void Main(string[] args) { int a = 1, b = 2; <AS:0>Console.WriteLine(a*b);</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { int a = 1, b = 2; checked { <AS:0>Console.WriteLine(a*b);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void CheckedUnchecked_Insert_Internal() { var src1 = @" class Test { static void Main(string[] args) { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Delete_Internal() { var src1 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "System.Console.WriteLine(5 * M(1, 2));", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Update_Internal() { var src1 = @" class Test { static void Main(string[] args) { unchecked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Lambda1() { var src1 = @" class Test { static void Main(string[] args) { unchecked { Action f = () => <AS:1>5 * M(1, 2)</AS:1>; } <AS:2>f();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { Action f = () => <AS:1>5 * M(1, 2)</AS:1>; } <AS:2>f();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Query1() { var src1 = @" using System.Collections.Generic; using System.Linq; class Test { static void Main() { IEnumerable<int> f; unchecked { f = from a in new[] { 5 } select <AS:1>M(a, int.MaxValue)</AS:1>; } <AS:2>f.ToArray();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" using System.Collections.Generic; using System.Linq; class Test { static void Main() { IEnumerable<int> f; checked { f = from a in new[] { 5 } select <AS:1>M(a, int.MaxValue)</AS:1>; } <AS:2>f.ToArray();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } #endregion #region Lambdas [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_GeneralStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>F(a => <AS:0>1</AS:0>);</AS:1> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>F(a => <AS:0>2</AS:0>);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_Nested1() { var src1 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>1</AS:0>)</AS:1>);</AS:2> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>2</AS:0>)</AS:1>);</AS:2> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_Nested2() { var src1 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>1</AS:0>)</AS:1>);</AS:2> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>G(a => <AS:0>2</AS:0>)</AS:1>);</AS:2> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "G(a => 2 )")); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_IfStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>if (F(a => <AS:0>1</AS:0>))</AS:1> { } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>if (F(a => <AS:0>2</AS:0>))</AS:1> { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_WhileStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>while (F(a => <AS:0>1</AS:0>))</AS:1> { } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>while (F(a => <AS:0>2</AS:0>))</AS:1> { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_DoStatement() { var src1 = @" class C { static void Main(string[] args) { do {} <AS:1>while (F(a => <AS:0>1</AS:0>));</AS:1> } } "; var src2 = @" class C { static void Main(string[] args) { do {} <AS:1>while (F(a => <AS:0>2</AS:0>));</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_SwitchStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>switch (F(a => <AS:0>1</AS:0>))</AS:1> { case 0: break; case 1: break; } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>switch (F(a => <AS:0>2</AS:0>))</AS:1> { case 0: break; case 1: break; } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_LockStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>lock (F(a => <AS:0>1</AS:0>))</AS:1> {} } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>lock (F(a => <AS:0>2</AS:0>))</AS:1> {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_UsingStatement1() { var src1 = @" class C { static void Main(string[] args) { <AS:1>using (F(a => <AS:0>1</AS:0>))</AS:1> {} } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>using (F(a => <AS:0>2</AS:0>))</AS:1> {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ExpressionToStatements() { var src1 = @" class C { static void Main(string[] args) { Func<int, int> f = a => <AS:0>1</AS:0>; } } "; var src2 = @" class C { static void Main(string[] args) { <AS:0>Func<int, int> f = a => { return 1; };</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ExpressionToDelegate() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = a => <AS:0>1</AS:0>; } } "; var src2 = @" using System; class C { static void Main() { <AS:0>Func<int, int> f = delegate(int a) { return 1; };</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_StatementsToExpression() { var src1 = @" class C { static void Main(string[] args) { Func<int, int> f = a => { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" class C { static void Main(string[] args) { <AS:0>Func<int, int> f = a => 1;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_DelegateToExpression() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = delegate(int a) { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" using System; class C { static void Main() { <AS:0>Func<int, int> f = a => 1;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_StatementsToDelegate() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = a => { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" using System; class C { static void Main() { Func<int, int> f = delegate(int a) { <AS:0>return 2;</AS:0> }; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ActiveStatementUpdate() { var src1 = @" using System; class C { static void Main(string[] args) { Func<int, int, int> f = (int a, int b) => <AS:0>a + b + 1</AS:0>; <AS:1>f(2);</AS:1> } }"; var src2 = @" using System; class C { static void Main(string[] args) { Func<int, int, int> f = (_, _) => <AS:0>10</AS:0>; <AS:1>f(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Lambdas_ActiveStatementRemoved1() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { return b => { <AS:0>return b;</AS:0> }; }; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = b => { <AS:0>return b;</AS:0> }; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "return b;", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved2() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => (b) => <AS:0>b</AS:0>; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = <AS:0>(b)</AS:0> => b; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "(b)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved3() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { Func<int, int> z; F(b => { <AS:0>return b;</AS:0> }, out z); return z; }; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = b => { <AS:0>F(b);</AS:0> return 1; }; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "F(b);", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved4() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { <AS:1>z(2);</AS:1> return b => { <AS:0>return b;</AS:0> }; }; } }"; var src2 = @" class C { static void Main(string[] args) <AS:0,1>{</AS:0,1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "{", CSharpFeaturesResources.lambda), Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "{", CSharpFeaturesResources.lambda)); } [Fact] public void Queries_ActiveStatementRemoved_WhereClause() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b where <AS:0>b.goo</AS:0> select b.bar; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select b.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.where_clause)); } [Fact] public void Queries_ActiveStatementRemoved_LetClause() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b let x = <AS:0>b.goo</AS:0> select x; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.let_clause)); } [Fact] public void Queries_ActiveStatementRemoved_JoinClauseLeft() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b join c in d on <AS:0>a.goo</AS:0> equals c.bar select a.bar; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy1() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby <AS:0>a.x</AS:0>, a.y descending, a.z ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy2() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby a.x, <AS:0>a.y</AS:0> descending, a.z ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy3() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby a.x, a.y descending, <AS:0>a.z</AS:0> ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_Remove_JoinInto1() { var src1 = @" class C { static void Main() { var q = from x in xs join y in ys on F() equals G() into g select <AS:0>1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from x in xs join y in ys on F() equals G() select <AS:0>1</AS:0>; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Queries_Remove_QueryContinuation1() { var src1 = @" class C { static void Main() { var q = from x in xs group x by x.F() into g where <AS:0>g.F()</AS:0> select 1; } }"; var src2 = @" class C { static void Main() { var q = from x in xs group x by x.F() <AS:0>into</AS:0> g select 1; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "into", CSharpFeaturesResources.where_clause)); } [Fact] public void Queries_Remove_QueryContinuation2() { var src1 = @" class C { static void Main() { var q = from x in xs group x by x.F() into g select <AS:0>1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from x in xs <AS:0>join</AS:0> y in ys on F() equals G() into g select 1; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "join", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Select_Reduced1() { var src1 = @" class C { static void Main() { var q = from a in array where a > 0 select <AS:0>a + 1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from a in array where a > 0 <AS:0>select</AS:0> a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "select", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Select_Reduced2() { var src1 = @" class C { static int F(IEnumerable<int> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array where a > 0 select a + 1);</AS:1> } }"; var src2 = @" class C { static int F(IEnumerable<int> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array where a > 0 select a);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(from a in array where a > 0 select a);")); } [Fact] public void Queries_GroupBy_Reduced1() { var src1 = @" class C { static void Main() { var q = from a in array group <AS:0>a + 1</AS:0> by a; } }"; var src2 = @" class C { static void Main() { var q = from a in array <AS:0>group</AS:0> a by a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_GroupBy_Reduced2() { var src1 = @" class C { static int F(IEnumerable<IGrouping<int, int>> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array group a by a);</AS:1> } }"; var src2 = @" class C { static int F(IEnumerable<IGrouping<int, int>> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array group a + 1 by a);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(from a in array group a + 1 by a);")); } #endregion #region State Machines [Fact] public void MethodToIteratorMethod_WithActiveStatement() { var src1 = @" class C { static IEnumerable<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { <AS:0>Console.WriteLine(1);</AS:0> yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "yield return 1;", CSharpFeaturesResources.yield_return_statement)); } [Fact] public void MethodToIteratorMethod_WithActiveStatementInLambda() { var src1 = @" class C { static IEnumerable<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // should not contain RUDE_EDIT_INSERT_AROUND edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToIteratorMethod_WithoutActiveStatement() { var src1 = @" class C { static IEnumerable<int> F() { Console.WriteLine(1); return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { Console.WriteLine(1); yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitExpression() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitForEach() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> await foreach (var x in AsyncIter()) { } return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await foreach (var x in AsyncIter())", CSharpFeaturesResources.asynchronous_foreach_statement)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitUsing() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> await using IAsyncDisposable x = new AsyncDisposable(), y = new AsyncDisposable(); return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "x = new AsyncDisposable()", CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "y = new AsyncDisposable()", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_NoAwait1() { var src1 = @" class C { static void F() <AS:0>{</AS:0> Console.WriteLine(1); } } "; var src2 = @" class C { static async void F() <AS:0>{</AS:0> Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_NoAwait2() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var src2 = @" class C { static async void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithActiveStatementInLambda1() { var src1 = @" class C { static Task<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // should not contain RUDE_EDIT_INSERT_AROUND edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithActiveStatementInLambda_2() { var src1 = @" class C { static void F() { var f = new Action(() => { <AS:1>Console.WriteLine(1);</AS:1> }); <AS:0>f();</AS:0> } } "; var src2 = @" class C { static async void F() { var f = new Action(() => { <AS:1>Console.WriteLine(1);</AS:1> }); <AS:0>f();</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithLambda() { var src1 = @" class C { static void F() <AS:0>{</AS:0> var f = new Action(() => { Console.WriteLine(1); }); f(); } } "; var src2 = @" class C { static async void F() <AS:0>{</AS:0> var f = new Action(() => { Console.WriteLine(1); }); f(); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithoutActiveStatement_1() { var src1 = @" class C { static Task<int> F() { Console.WriteLine(1); return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { Console.WriteLine(1); return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithoutActiveStatement_2() { var src1 = @" class C { static void F() { Console.WriteLine(1); } } "; var src2 = @" class C { static async void F() { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement() { var src1 = @" using System; using System.Threading.Tasks; class C { static void F() { var f = new Func<Task<int>>(() => { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); }); } } "; var src2 = @" using System; using System.Threading.Tasks; class C { static void F() { var f = new Func<Task<int>>(async () => { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement_NoAwait() { var src1 = @" using System; class C { static void F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var src2 = @" using System; class C { static void F() { var f = new Action(async () => { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "()")); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement_NoAwait_Nested() { var src1 = @" class C { static void F() { var f = new Func<int, Func<int, int>>(a => <AS:0>b => 1</AS:0>); } } "; var src2 = @" class C { static void F() { var f = new Func<int, Func<int, int>>(async a => <AS:0>b => 1</AS:0>); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "a")); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunctionToAsyncLocalFunction_BlockBody_WithActiveStatement() { var src1 = @" class C { static void F() { Task<int> f() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } } "; var src2 = @" class C { static void F() { async Task<int> f() { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunctionToAsyncLocalFunction_ExpressionBody_WithActiveStatement() { var src1 = @" class C { static void F() { Task<int> f() => <AS:0>Task.FromResult(1)</AS:0>; } } "; var src2 = @" class C { static void F() { async Task<int> f() => <AS:0>await Task.FromResult(1)</AS:0>; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void AnonymousFunctionToAsyncAnonymousFunction_WithActiveStatement_NoAwait() { var src1 = @" using System.Threading.Tasks; class C { static void F() { var f = new Func<Task>(delegate() { <AS:0>Console.WriteLine(1);</AS:0> return Task.CompletedTask; }); } } "; var src2 = @" using System.Threading.Tasks; class C { static async void F() { var f = new Func<Task>(async delegate() { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, FeaturesResources.delegate_)); } [Fact] public void AsyncMethodEdit_Semantics() { var src1 = @" using System; using System.Threading.Tasks; class C { static async Task<int> F() { await using var x = new AsyncDisposable(); await foreach (var x in AsyncIter()) { Console.WriteLine(x); } return await Task.FromResult(1); } } "; var src2 = @" using System; using System.Threading.Tasks; class C { static async Task<int> F() { await using var x = new AsyncDisposable(); await foreach (var x in AsyncIter()) { Console.WriteLine(x + 1); } return await Task.FromResult(2); } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void IteratorMethodEdit_Semantics() { var src1 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { Console.WriteLine(1); yield return 1; } } "; var src2 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { Console.WriteLine(2); yield return 2; } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void AsyncIteratorMethodEdit_Semantics() { var src1 = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class C { static async IAsyncEnumerable<int> F() { Console.WriteLine(1); await Task.Delay(1); yield return 1; } } "; var src2 = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class C { static async IAsyncEnumerable<int> F() { Console.WriteLine(2); await Task.Delay(2); yield return 2; } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(targetFrameworks: new[] { TargetFramework.NetCoreApp }); } [Fact] public void AsyncMethodToMethod() { var src1 = @" class C { static async void F() { } } "; var src2 = @" class C { static void F() { } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "static void F()", FeaturesResources.method)); } #endregion #region Misplaced AS [Fact] public void MisplacedActiveStatement1() { var src1 = @" <AS:1>class C</AS:1> { public static int F(int a) { <AS:0>return a;</AS:0> <AS:2>return a;</AS:2> } }"; var src2 = @" class C { public static int F(int a) { <AS:0>return a;</AS:0> <AS:2>return a;</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MisplacedActiveStatement2() { var src1 = @" class C { static <AS:0>void</AS:0> Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] args) <AS:0>{</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MisplacedTrackingSpan1() { var src1 = @" class C { static <AS:0>void</AS:0> Main(string[] args) { } }"; var src2 = @" class C { static <TS:0>void</TS:0> Main(string[] args) <AS:0>{</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region C# 7.0 [Fact] public void UpdateAroundActiveStatement_IsPattern() { var src1 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> if (x is int i) { Console.WriteLine(""match""); } } } "; var src2 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> if (x is string s) { Console.WriteLine(""match""); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionDeclarationStatement() { var src1 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = (1, 2); } } "; var src2 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = x; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionForEach() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> foreach (var (x, y) in new[] { (1, 2) }) { Console.WriteLine(2); } } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> foreach (var (x, y) in new[] { o }) { Console.WriteLine(2); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_VarDeconstruction() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for (var (x, y) = o1; ; ) { } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for (var (x, y) = o2; ; ) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_TypedDeconstruction() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for ((int x, int y) = o1; ; ) { } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for ((int x, int y) = o2; ; ) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_Tuple() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> (int, int) t; } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> (int, int) t = (1, 2); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_LocalFunction() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(2); } } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(3); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_OutVar() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(); } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(out var x); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_OutVarRemoved() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(out var x); } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_Ref() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> ref int i = ref 1; } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> ref int i = ref 2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionDeclaration() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = o1; } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = o2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionAssignment() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> int x, y; (x, y) = o1; } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> int x, y; (x, y) = o2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_SwitchWithPattern() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>System.Console.WriteLine(1);</AS:0> switch (o1) { case int i: break; } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>System.Console.WriteLine(1);</AS:0> switch (o2) { case int i: break; } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); edits.VerifySemanticDiagnostics(); } #endregion #region Nullable [Fact] public void ChangeLocalNullableToNonNullable() { var src1 = @" class C { static void F() { <AS:0>string? s = ""a"";</AS:0> } } "; var src2 = @" class C { static void F() { <AS:0>string s = ""a"";</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ChangeLocalNonNullableToNullable() { var src1 = @" class C { static void F() { <AS:0>string s = ""a"";</AS:0> } } "; var src2 = @" class C { static void F() { <AS:0>string? s = ""a"";</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Partial Types [Fact] public void InsertDeleteMethod_Inactive() { // Moving inactive method declaration in a file with active statements. var srcA1 = "partial class C { void F1() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var srcB1 = "partial class C { void F2() { } }"; var srcA2 = "partial class C { void F1() { <AS:0>System.Console.WriteLine(1);</AS:0> } void F2() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( activeStatements: GetActiveStatements(srcA1, srcA2, path: "0"), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F2")), }), DocumentResults( activeStatements: GetActiveStatements(srcB1, srcB2, path: "1")) }); } [Fact] [WorkItem(51177, "https://github.com/dotnet/roslyn/issues/51177")] [WorkItem(54758, "https://github.com/dotnet/roslyn/issues/54758")] public void InsertDeleteMethod_Active() { // Moving active method declaration in a file with active statements. // TODO: this is currently a rude edit var srcA1 = "partial class C { }"; var srcB1 = "partial class C { void F() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var srcA2 = "partial class C { void F() { System.Console.WriteLine(1); } }"; var srcB2 = "<AS:0>partial class C</AS:0> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( activeStatements: GetActiveStatements(srcA1, srcA2, path: "0"), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), }), DocumentResults( activeStatements: GetActiveStatements(srcB1, srcB2, path: "1"), // TODO: this is odd AS location https://github.com/dotnet/roslyn/issues/54758 diagnostics: new[] { Diagnostic(RudeEditKind.DeleteActiveStatement, " partial c", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } #endregion #region Records [Fact] public void Record() { var src1 = @" record C(int X) { public int X { get; init; } = <AS:0>1</AS:0>; }"; var src2 = @" record C(int X) { public int X { get; init; } = <AS:0>2</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Record_Constructor() { var src1 = @" record C(int X) { public int X { get; init; } = <AS:0>1</AS:0>; static void Main(string[] args) { <AS:1>var x = new C(1);</AS:1> } }"; var src2 = @" record C(int X) { public int X { get; init; } = <AS:0>2</AS:0>; static void Main(string[] args) { <AS:1>var x = new C(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Record_FieldInitializer_Lambda2() { var src1 = @" record C(int X) { Func<int, Func<int>> a = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C(1).a(1)();</AS:1> } }"; var src2 = @" record C(int X) { Func<int, Func<int>> a = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C(1).a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Line Mapping /// <summary> /// Validates that changes in #line directives produce semantic updates of the containing method. /// </summary> [Fact] public void LineMapping_ChangeLineNumber_WithinMethod() { var src1 = @" class C { #line 1 ""a"" static void F() { <AS:0>A();</AS:0> #line 5 ""b"" B(1); <AS:1>B();</AS:1> #line 2 ""c"" <AS:2>C();</AS:2> <AS:3>C();</AS:3> #line hidden D(); #line default <AS:4>E();</AS:4> } }"; var src2 = @" class C { #line 1 ""a"" static void F() { <AS:0>A();</AS:0> #line 5 ""b"" B(2); <AS:1>B();</AS:1> #line 9 ""c"" <AS:2>C();</AS:2> <AS:3>C();</AS:3> #line hidden D(); #line default <AS:4>E();</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LineMapping_ChangeFilePath() { var src1 = @" class C { static void F() { <AS:0>A();</AS:0> #line 1 ""a"" <AS:1>B();</AS:1> } }"; var src2 = @" class C { static void F() { <AS:0>A();</AS:0> #line 1 ""b"" <AS:1>B();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "B();", string.Format(FeaturesResources._0_directive, "line"))); } [Fact] public void LineMapping_ExceptionRegions_ChangeLineNumber() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 30 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(52971, "https://github.com/dotnet/roslyn/issues/52971")] public void LineMapping_ExceptionRegions_ChangeFilePath() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""c"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: rude edit should be reported edits.VerifyRudeDiagnostics(active); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/52971"), WorkItem(52971, "https://github.com/dotnet/roslyn/issues/52971")] public void LineMapping_ExceptionRegions_LineChange_MultipleMappedFiles() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line 30 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: rude edit? edits.VerifyRudeDiagnostics(active); } #endregion #region Misc [Fact] public void Delete_All_SourceText() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C"))); } [Fact] public void PartiallyExecutedActiveStatement() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> <AS:1>Console.WriteLine(2);</AS:1> <AS:2>Console.WriteLine(3);</AS:2> <AS:3>Console.WriteLine(4);</AS:3> <AS:4>Console.WriteLine(5);</AS:4> } }"; var src2 = @" class C { public static void F() { <AS:0>Console.WriteLine(10);</AS:0> <AS:1>Console.WriteLine(20);</AS:1> <AS:2>Console.WriteLine(30);</AS:2> <AS:3>Console.WriteLine(40);</AS:3> <AS:4>Console.WriteLine(50);</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsLeafFrame, ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsNonLeafFrame, ActiveStatementFlags.IsLeafFrame, ActiveStatementFlags.IsNonLeafFrame, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.PartiallyExecutedActiveStatementUpdate, "Console.WriteLine(10);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(20);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(40);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(50);")); } [Fact] public void PartiallyExecutedActiveStatement_Deleted1() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { public static void F() { <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.PartiallyExecutedActiveStatementDelete, "{", FeaturesResources.code)); } [Fact] public void PartiallyExecutedActiveStatement_Deleted2() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { public static void F() { <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void Block_Delete() { var src1 = @" class C { public static void F() { G(1); <AS:0>{</AS:0> G(2); } G(3); } } "; var src2 = @" class C { public static void F() { G(1); <AS:0>G(3);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory, CombinatorialData] public void MemberBodyInternalError(bool outOfMemory) { var src1 = @" class C { public static void F() { <AS:1>G();</AS:1> } public static void G() { <AS:0>H(1);</AS:0> } public static void H(int x) { } } "; var src2 = @" class C { public static void F() { <AS:1>G();</AS:1> } public static void G() { <AS:0>H(2);</AS:0> } public static void H(int x) { } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); var validator = new CSharpEditAndContinueTestHelpers(faultInjector: node => { if (node.Parent is MethodDeclarationSyntax methodDecl && methodDecl.Identifier.Text == "G") { throw outOfMemory ? new OutOfMemoryException() : new NullReferenceException("NullRef!"); } }); var expectedDiagnostic = outOfMemory ? Diagnostic(RudeEditKind.MemberBodyTooBig, "public static void G()", FeaturesResources.method) : Diagnostic(RudeEditKind.MemberBodyInternalError, "public static void G()", FeaturesResources.method); validator.VerifySemantics( new[] { edits }, TargetFramework.NetCoreApp, new[] { DocumentResults(diagnostics: new[] { expectedDiagnostic }) }); } #endregion #region Top Level Statements [Fact] public void TopLevelStatements_UpdateAroundActiveStatement_LocalFunction() { var src1 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(2); } "; var src2 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(3); } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TopLevelStatements_UpdateAroundActiveStatement_OutVar() { var src1 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> M(); "; var src2 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> M(out var x); "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TopLevelStatements_Inner() { var src1 = @" using System; <AS:1>Goo(1);</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } "; var src2 = @" using System; while (true) { <AS:1>Goo(2);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } #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 Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.EditAndContinue.UnitTests; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.CSharp.UnitTests; using System.Linq; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { [UseExportProvider] public class ActiveStatementTests : EditingTestBase { #region Update [Fact] public void Update_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { <AS:1>Goo(2);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } [Fact] public void Update_Inner_NewCommentAtEndOfActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1>// } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } /// <summary> /// CreateNewOnMetadataUpdate has no effect in presence of active statements (in break mode). /// </summary> [Fact] public void Update_Inner_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main() { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main() { while (true) { <AS:1>Goo(2);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } [Fact] public void Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { <AS:1>Goo(1);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a + 1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Update_Leaf_NewCommentAtEndOfActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0>// } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } /// <summary> /// CreateNewOnMetadataUpdate has no effect in presence of active statements (in break mode). /// </summary> [Fact] public void Update_Leaf_Reloadable() { var src1 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = ReloadableAttributeSrc + @" [CreateNewOnMetadataUpdate] class C { static void Main(string[] args) { while (true) { <AS:1>Goo(1);</AS:1> } } static void Goo(int a) { <AS:0>Console.WriteLine(a + 1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemantics(active, expectedSemanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Main"), preserveLocalVariables: true), SemanticEdit(SemanticEditKind.Update, c => c.GetMember("C.Goo"), preserveLocalVariables: true) }); } [WorkItem(846588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/846588")] [Fact] public void Update_Leaf_Block() { var src1 = @" class C : System.IDisposable { public void Dispose() {} static void Main(string[] args) { using (<AS:0>C x = null</AS:0>) {} } }"; var src2 = @" class C : System.IDisposable { public void Dispose() {} static void Main(string[] args) { using (<AS:0>C x = new C()</AS:0>) {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Delete in Method Body [Fact] public void Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { while (true) { } <AS:1>}</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } // TODO (tomat): considering a change [Fact] public void Delete_Inner_MultipleParents() { var src1 = @" class C : IDisposable { unsafe static void Main(string[] args) { { <AS:1>Goo(1);</AS:1> } if (true) { <AS:2>Goo(2);</AS:2> } else { <AS:3>Goo(3);</AS:3> } int x = 1; switch (x) { case 1: case 2: <AS:4>Goo(4);</AS:4> break; default: <AS:5>Goo(5);</AS:5> break; } checked { <AS:6>Goo(4);</AS:6> } unchecked { <AS:7>Goo(7);</AS:7> } while (true) <AS:8>Goo(8);</AS:8> do <AS:9>Goo(9);</AS:9> while (true); for (int i = 0; i < 10; i++) <AS:10>Goo(10);</AS:10> foreach (var i in new[] { 1, 2}) <AS:11>Goo(11);</AS:11> using (var z = new C()) <AS:12>Goo(12);</AS:12> fixed (char* p = ""s"") <AS:13>Goo(13);</AS:13> label: <AS:14>Goo(14);</AS:14> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C : IDisposable { unsafe static void Main(string[] args) { { <AS:1>}</AS:1> if (true) { <AS:2>}</AS:2> else { <AS:3>}</AS:3> int x = 1; switch (x) { case 1: case 2: <AS:4>break;</AS:4> default: <AS:5>break;</AS:5> } checked { <AS:6>}</AS:6> unchecked { <AS:7>}</AS:7> <AS:8>while (true)</AS:8> { } do { } <AS:9>while (true);</AS:9> for (int i = 0; i < 10; <AS:10>i++</AS:10>) { } foreach (var i <AS:11>in</AS:11> new[] { 1, 2 }) { } using (<AS:12>var z = new C()</AS:12>) { } fixed (<AS:13>char* p = ""s""</AS:13>) { } label: <AS:14>{</AS:14> } } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "case 2:", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "default:", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "while (true)", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "do", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "for (int i = 0; i < 10; i++ )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "foreach (var i in new[] { 1, 2 })", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "using ( var z = new C() )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "fixed ( char* p = \"s\" )", FeaturesResources.code), Diagnostic(RudeEditKind.DeleteActiveStatement, "label", FeaturesResources.code)); } [Fact] public void Delete_Leaf1() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>}</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf2() { var src1 = @" class C { static void Goo(int a) { Console.WriteLine(1); Console.WriteLine(2); <AS:0>Console.WriteLine(3);</AS:0> Console.WriteLine(4); } }"; var src2 = @" class C { static void Goo(int a) { Console.WriteLine(1); Console.WriteLine(2); <AS:0>Console.WriteLine(4);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf_InTry() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { <AS:0>Console.WriteLine(a);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { <AS:0>}</AS:0> catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Leaf_InTry2() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { try { <AS:0>Console.WriteLine(a);</AS:0> } catch { } } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { try { try { <AS:0>}</AS:0> catch { } } catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_Inner_CommentActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { //Goo(1); <AS:1>}</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [WorkItem(755959, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755959")] [Fact] public void Delete_Leaf_CommentActiveStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { //Console.WriteLine(a); <AS:0>}</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Delete_EntireNamespace() { var src1 = @" namespace N { class C { static void Main(String[] args) { <AS:0>Console.WriteLine(1);</AS:0> } } }"; var src2 = @"<AS:0></AS:0>"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.Delete, null, FeaturesResources.namespace_), Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "N.C"))); } #endregion #region Constructors [WorkItem(740949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/740949")] [Fact] public void Updated_Inner_Constructor() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5*2);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo f = new Goo(5*2);")); } [WorkItem(741249, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/741249")] [Fact] public void Updated_Leaf_Constructor() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a;</AS:0> } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; public Goo(int a) { <AS:0>this.value = a*2;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_Constructor_Parameter() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a)</AS:0> { this.value = a; } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int b)</AS:0> { this.value = b; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemantics( ActiveStatementsDescription.Empty, new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember("Goo..ctor")) }, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_Constructor_Parameter_DefaultValue() { var src1 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a = 5)</AS:0> { this.value = a; } }"; var src2 = @" using System; class Program { static void Main(string[] args) { <AS:1>Goo f = new Goo(5);</AS:1> } } class Goo { int value; <AS:0>public Goo(int a = 42)</AS:0> { this.value = a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InitializerUpdate, "int a = 42", FeaturesResources.parameter)); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_ConstructorChaining1() { var src1 = @" using System; class Test { static void Main(string[] args) { <AS:1>B b = new B(2, 3);</AS:1> } } class B : A { public B(int x, int y) : <AS:0>base(x + y, x - y)</AS:0> { } } class A { public A(int x, int y) : this(5 + x, y, 0) { } public A(int x, int y, int z) { } }"; var src2 = @" using System; class Test { static void Main(string[] args) { <AS:1>B b = new B(2, 3);</AS:1> } } class B : A { public B(int x, int y) : <AS:0>base(x + y + 5, x - y)</AS:0> { } } class A { public A(int x, int y) : this(x, y, 0) { } public A(int x, int y, int z) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void Updated_Leaf_ConstructorChaining2() { var src1 = @" using System; class Test { static void Main(string[] args) { <AS:2>B b = new B(2, 3);</AS:2> } } class B : A { public B(int x, int y) : <AS:1>base(x + y, x - y)</AS:1> { } } class A { public A(int x, int y) : <AS:0>this(x, y, 0)</AS:0> { } public A(int x, int y, int z) { } }"; var src2 = @" using System; class Test { static void Main(string[] args) { <AS:2>B b = new B(2, 3);</AS:2> } } class B : A { public B(int x, int y) : <AS:1>base(x + y, x - y)</AS:1> { } } class A { public A(int x, int y) : <AS:0>this(5 + x, y, 0)</AS:0> { } public A(int x, int y, int z) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Fact] public void InstanceConstructorWithoutInitializer() { var src1 = @" class C { int a = 5; <AS:0>public C(int a)</AS:0> { } static void Main(string[] args) { <AS:1>C c = new C(3);</AS:1> } }"; var src2 = @" class C { int a = 42; <AS:0>public C(int a)</AS:0> { } static void Main(string[] args) { <AS:1>C c = new C(3);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update1() { var src1 = @" class D { public D(int d) {} } class C : D { int a = 5; public C(int a) : <AS:2>this(true)</AS:2> { } public C(bool b) : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:3>C c = new C(3);</AS:3> } }"; var src2 = @" class D { public D(int d) {} } class C : D { int a = 5; public C(int a) : <AS:2>this(false)</AS:2> { } public C(bool b) : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:3>C c = new C(3);</AS:3> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "this(false)")); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update2() { var src1 = @" class D { public D(int d) {} } class C : D { public C() : <AS:1>base(F())</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class D { public D(int d) {} } class C : D { <AS:1>public C()</AS:1> {} static int F() { <AS:0>return 1;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "public C()")); } [Fact] public void InstanceConstructorWithInitializer_Internal_Update3() { var src1 = @" class D { public D(int d) <AS:0>{</AS:0> } } class C : D { <AS:1>public C()</AS:1> {} }"; var src2 = @" class D { public D(int d) <AS:0>{</AS:0> } } class C : D { public C() : <AS:1>base(1)</AS:1> {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "base(1)")); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update1() { var src1 = @" class D { public D(int d) { } } class C : D { public C() : <AS:0>base(1)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update2() { var src1 = @" class D { public D() { } public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D() { } public D(int d) { } } class C : D { <AS:0>public C()</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializer_Leaf_Update3() { var src1 = @" class D { public D() { } public D(int d) { } } class C : D { <AS:0>public C()</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class D { public D() { } public D(int d) { } } class C : D { public C() : <AS:0>base(2)</AS:0> {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update1() { var src1 = @" class C { public C() : this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> }) { } }"; var src2 = @" class C { public C() : base((a, b) => { <AS:0>Console.WriteLine(a - b);</AS:0> }) { } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update2() { var src1 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var src2 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(2); } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceConstructorWithInitializerWithLambda_Update3() { var src1 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a + b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var src2 = @" class C { public C() : <AS:1>this((a, b) => { <AS:0>Console.WriteLine(a - b);</AS:0> })</AS:1> { Console.WriteLine(1); } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory] [InlineData("class ")] [InlineData("struct")] public void InstanceConstructor_DeleteParameterless(string typeKind) { var src1 = "partial " + typeKind + " C { public C() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var src2 = "<AS:0>partial " + typeKind + " C</AS:0> { }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "partial " + typeKind + " C", DeletedSymbolDisplay(FeaturesResources.constructor, "C()"))); } #endregion #region Field and Property Initializers [Theory] [InlineData("class ")] [InlineData("struct")] public void InstancePropertyInitializer_Leaf_Update(string typeKind) { var src1 = @" " + typeKind + @" C { int a { get; } = <AS:0>1</AS:0>; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { int a { get; } = <AS:0>2</AS:0>; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory] [InlineData("class ")] [InlineData("struct")] public void InstancePropertyInitializer_Leaf_Update_SynthesizedConstructor(string typeKind) { var src1 = @" " + typeKind + @" C { int a { get; } = <AS:0>1</AS:0>; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { int a { get; } = <AS:0>2</AS:0>; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(742334, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/742334")] [Theory] [InlineData("class ")] [InlineData("struct")] public void InstanceFieldInitializer_Leaf_Update1(string typeKind) { var src1 = @" " + typeKind + @" C { <AS:0>int a = 1</AS:0>, b = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { <AS:0>int a = 2</AS:0>, b = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory] [InlineData("class ")] [InlineData("struct")] public void InstanceFieldInitializer_Leaf_Update1_SynthesizedConstructor(string typeKind) { var src1 = @" " + typeKind + @" C { <AS:0>int a = 1</AS:0>, b = 2; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" " + typeKind + @" C { <AS:0>int a = 2</AS:0>, b = 2; static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Update1() { var src1 = @" class C { <AS:1>int a = F(1)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>int a = F(2)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "int a = F(2)")); } [Fact] public void InstanceFieldInitializer_Internal_Update2() { var src1 = @" class C { int a = F(1), <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { int a = F(1), <AS:1>b = F(3)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "b = F(3)")); } [Fact] public void InstancePropertyInitializer_Internal_Delete1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; int b { get; } = 2; }"; var src2 = @" class C { int a { get { return 1; } } int b { get; } = <AS:0>2</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyInitializer_Internal_Delete2() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; static int s { get; } = 2; int b { get; } = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class C { int a { get; } static int s { get; } = 2; int b { get; } = <AS:0>3</AS:0>; public C() { } static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Delete1() { var src1 = @" class C { <AS:1>int a = F(1)</AS:1>, b = F(2); public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { int a, <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_Internal_Delete2() { var src1 = @" class C { int a = F(1), <AS:1>b = F(2)</AS:1>; public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>int a, b;</AS:1> public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyAndFieldInitializers_Delete1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; static int s { get; } = 2; int b = 2; }"; var src2 = @" class C { int a { get; } static int s { get; } = 2; <AS:0>int b = 3;</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstancePropertyAndFieldInitializers_Delete2() { var src1 = @" class C { int a = <AS:0>1</AS:0>; static int s { get; } = 2; int b { get; } = 2; public C() {} static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var src2 = @" class C { int a; static int s { get; } = 2; int b { get; } = <AS:0>3</AS:0>; public C() { } static void Main(string[] args) { <AS:1>C c = new C();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void InstanceFieldInitializer_SingleDeclarator() { var src1 = @" class C { <AS:1>public static readonly int a = F(1);</AS:1> public C() {} public static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { <AS:2>C c = new C();</AS:2> } }"; var src2 = @" class C { <AS:1>public static readonly int <TS:1>a = F(1)</TS:1>;</AS:1> public C() {} public static int F(int a) { <TS:0><AS:0>return a + 1;</AS:0></TS:0> } static void Main(string[] args) { <TS:2><AS:2>C c = new C();</AS:2></TS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Lambda1() { var src1 = @" class C { Func<int, int> a = z => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var src2 = @" class C { Func<int, int> a = F(z => <AS:0>z + 1</AS:0>); static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void PropertyInitializer_Lambda1() { var src1 = @" class C { Func<int, int> a { get; } = z => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var src2 = @" class C { Func<int, int> a { get; } = F(z => <AS:0>z + 1</AS:0>); static void Main(string[] args) { <AS:1>new C().a(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Lambda2() { var src1 = @" class C { Func<int, Func<int>> a = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var src2 = @" class C { Func<int, Func<int>> a = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void PropertyInitializer_Lambda2() { var src1 = @" class C { Func<int, Func<int>> a { get; } = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var src2 = @" class C { Func<int, Func<int>> a { get; } = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C().a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_InsertConst1() { var src1 = @" class C { <AS:0>int a = 1</AS:0>; public C() {} }"; var src2 = @" class C { <AS:0>const int a = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); edits.VerifyEdits( "Update [int a = 1 ;]@24 -> [const int a = 1;]@24"); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1", FeaturesResources.const_field)); } [Fact] public void LocalInitializer_InsertConst1() { var src1 = @" class C { public void M() { <AS:0>int a = 1</AS:0>; } }"; var src2 = @" class C { public void M() { const int a = 1; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_InsertConst2() { var src1 = @" class C { int <AS:0>a = 1</AS:0>, b = 2; public C() {} }"; var src2 = @" class C { <AS:0>const int a = 1, b = 2;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1, b = 2", FeaturesResources.const_field), Diagnostic(RudeEditKind.ModifiersUpdate, "const int a = 1, b = 2", FeaturesResources.const_field)); } [Fact] public void LocalInitializer_InsertConst2() { var src1 = @" class C { public void M() { int <AS:0>a = 1</AS:0>, b = 2; } }"; var src2 = @" class C { public void M() { const int a = 1, b = 2; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete1() { var src1 = @" class C { <AS:0>int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { int a; <AS:0>int b = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LocalInitializer_Delete1() { var src1 = @" class C { public void M() { <AS:0>int a = 1</AS:0>; } }"; var src2 = @" class C { public void M() { int a; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete2() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { <AS:0>int b = 1;</AS:0> int c; int a; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LocalInitializer_Delete2() { var src1 = @" class C { public void M() { int b = 1; int c; <AS:0>int a = 1;</AS:0> } }"; var src2 = @" class C { public void M() { int b = 1; int c; int a; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_Delete3() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { <AS:0>int b = 1;</AS:0> int c; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void LocalInitializer_Delete3() { var src1 = @" class C { public void M() { int b = 1; int c; <AS:0>int a = 1;</AS:0> } }"; var src2 = @" class C { public void M() { int b = 1; int c; <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance1() { var src1 = @" class C { <AS:0>int a = 1;</AS:0> static int b = 1; int c = 1; public C() {} }"; var src2 = @" class C { int a; static int b = 1; <AS:0>int c = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance2() { var src1 = @" class C { static int c = 1; <AS:0>static int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { <AS:0>static int c = 1;</AS:0> static int a; int b = 1; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteStaticInstance3() { var src1 = @" class C { <AS:0>static int a = 1;</AS:0> int b = 1; public C() {} }"; var src2 = @" class C { <AS:0>static int a;</AS:0> int b = 1; public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldInitializer_DeleteMove1() { var src1 = @" class C { int b = 1; int c; <AS:0>int a = 1;</AS:0> public C() {} }"; var src2 = @" class C { int c; <AS:0>int b = 1;</AS:0> public C() {} }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Move, "int c", FeaturesResources.field), Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void LocalInitializer_DeleteReorder1() { var src1 = @" class C { public void M() { int b = 1; <AS:0>int a = 1;</AS:0> int c; } }"; var src2 = @" class C { public void M() { int c; <AS:0>int b = 1;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void FieldToProperty1() { var src1 = @" class C { int a = <AS:0>1</AS:0>; }"; // The placement of the active statement is not ideal, but acceptable. var src2 = @" <AS:0>class C</AS:0> { int a { get; } = 1; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.field, "a"))); } [Fact] public void PropertyToField1() { var src1 = @" class C { int a { get; } = <AS:0>1</AS:0>; }"; // The placement of the active statement is not ideal, but acceptable. var src2 = @" <AS:0>class C</AS:0> { int a = 1; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, Diagnostic(RudeEditKind.Delete, "class C", DeletedSymbolDisplay(FeaturesResources.auto_property, "a"))); } #endregion #region Lock Statement [Fact] public void LockBody_Update() { var src1 = @" class Test { private static object F() { <AS:0>return new object();</AS:0> } static void Main(string[] args) { <AS:1>lock (F())</AS:1> { System.Console.Write(0); } } }"; var src2 = @" class Test { private static object F() { <AS:0>return new object();</AS:0> } static void Main(string[] args) { <AS:1>lock (F())</AS:1> { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755749")] [Fact] public void Lock_Insert_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { <AS:0>System.Console.Write(5);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (lockThis)", CSharpFeaturesResources.lock_statement)); } [WorkItem(755749, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755749")] [Fact] public void Lock_Insert_Leaf2() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { { System.Console.Write(5); <AS:0>}</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (lockThis)", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Insert_Leaf3() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { { System.Console.Write(5); } <AS:0>System.Console.Write(10);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Insert_Leaf4() { var src1 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (a) { lock (b) { lock (c) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (b) { lock (d) { lock (a) { lock (e) { <AS:0>System.Console.Write();</AS:0> } } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (d)", CSharpFeaturesResources.lock_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "lock (e)", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Insert_Leaf5() { var src1 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (a) { lock (c) { lock (b) { lock (e) { <AS:0>System.Console.Write();</AS:0> } } } } } }"; var src2 = @" class Test { public static object a = new object(); public static object b = new object(); public static object c = new object(); public static object d = new object(); public static object e = new object(); static void Main(string[] args) { lock (b) { lock (d) { lock (a) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (d)", CSharpFeaturesResources.lock_statement)); } [WorkItem(755752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755752")] [Fact] public void Lock_Update_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (""test"") { <AS:0>System.Console.Write(5);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (\"test\")", CSharpFeaturesResources.lock_statement)); } [Fact] public void Lock_Update_Leaf2() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (""test"") { System.Console.Write(5); } <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Delete_Leaf() { var src1 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { lock (lockThis) { <AS:0>System.Console.Write(5);</AS:0> } } }"; var src2 = @" class Test { private static object lockThis = new object(); static void Main(string[] args) { <AS:0>System.Console.Write(5);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Update_Lambda1() { var src1 = @" class C { static void Main(string[] args) { lock (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void Main(string[] args) { lock (F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lock_Update_Lambda2() { var src1 = @" class C { static void Main(string[] args) { lock (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void Main(string[] args) { lock (G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "lock (G(a => a))", CSharpFeaturesResources.lock_statement)); } #endregion #region Fixed Statement [Fact] public void FixedBody_Update() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { unsafe { char* px2; fixed (<AS:1>char* pj = &F()</AS:1>) { System.Console.WriteLine(0); } } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { unsafe { char* px2; fixed (<AS:1>char* pj = &F()</AS:1>) { System.Console.WriteLine(1); } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Insert_Leaf() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* pj = &value)", CSharpFeaturesResources.fixed_statement)); } [Fact] public void Fixed_Insert_Leaf2() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>}</AS:0> } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { px2 = null; } <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Insert_Leaf3() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> fixed (int* pj = &value) { } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* pj = &value)", CSharpFeaturesResources.fixed_statement)); } [WorkItem(755742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755742")] [Fact] public void Fixed_Reorder_Leaf1() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* a = &value) { fixed (int* b = &value) { <AS:0>px2 = null;</AS:0> } } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* b = &value) { fixed (int* a = &value) { <AS:0>px2 = null;</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [WorkItem(755746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755746")] [Fact] public void Fixed_Update_Leaf1() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* p = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* p = &value)", CSharpFeaturesResources.fixed_statement)); } [WorkItem(755746, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/755746")] [Fact] public void Fixed_Update_Leaf2() { var src1 = @" class Test { public static int value1 = 10; public static int value2 = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* a = &value1) { fixed (int* b = &value1) { fixed (int* c = &value1) { <AS:0>px2 = null;</AS:0> } } } } } }"; var src2 = @" class Test { public static int value1 = 10; public static int value2 = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* c = &value1) { fixed (int* d = &value1) { fixed (int* a = &value2) { fixed (int* e = &value1) { <AS:0>px2 = null;</AS:0> } } } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* a = &value2)", CSharpFeaturesResources.fixed_statement), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (int* d = &value1)", CSharpFeaturesResources.fixed_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "fixed (int* e = &value1)", CSharpFeaturesResources.fixed_statement)); } [Fact] public void Fixed_Delete_Leaf() { var src1 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; fixed (int* pj = &value) { <AS:0>px2 = null;</AS:0> } } } }"; var src2 = @" class Test { static int value = 20; static void Main(string[] args) { unsafe { int* px2; <AS:0>px2 = null;</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Fixed_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Fixed_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { fixed (byte* p = &G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "fixed (byte* p = &G(a => a))", CSharpFeaturesResources.fixed_statement)); } #endregion #region ForEach Statement [Fact] public void ForEachBody_Update_ExpressionActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c in <AS:1>F()</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c in <AS:1>F()</AS:1>) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_ExpressionActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) in <AS:1>F()</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) in <AS:1>F()</AS:1>) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_InKeywordActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c <AS:1>in</AS:1> F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (char c <AS:1>in</AS:1> F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_InKeywordActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) <AS:1>in</AS:1> F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach ((string s, int i) <AS:1>in</AS:1> F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_VariableActive() { var src1 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_VariableActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>(string s, int i)</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>(string s, int i)</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachBody_Update_ForeachKeywordActive() { var src1 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> (char c in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> (char c in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariableBody_Update_ForeachKeywordActive() { var src1 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> ((string s, int i) in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (string, int) F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { <AS:1>foreach</AS:1> ((string s, int i) in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Update() { var src1 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>string c</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static string[] F() { <AS:0>return null;</AS:0> } static void Main(string[] args) { foreach (<AS:1>object c</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // not ideal, but good enough: edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "object c"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach ( object c in F())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEachDeconstructionVariable_Update() { var src1 = @" class Test { private static (int, (bool, double))[] F() { <AS:0>return new[] { (1, (true, 2.0)) };</AS:0> } static void Main(string[] args) { foreach (<AS:1>(int i, (bool b, double d))</AS:1> in F()) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static (int, (bool, double))[] F() { <AS:0>return new[] { (1, (true, 2.0)) };</AS:0> } static void Main(string[] args) { foreach (<AS:1>(int i, (var b, double d))</AS:1> in F()) { System.Console.Write(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "(int i, (var b, double d))"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach ( (int i, (var b, double d)) in F())", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Reorder_Leaf() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Reorder_Leaf() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { foreach ((var a1, var a2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Update_Leaf() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var b in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var c in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var a in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEachVariable_Update_Leaf() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { foreach ((var a1, var a2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var c in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach ((int b1, bool b2) in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach ((var a1, var a2) in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Delete_Leaf1() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf1() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Delete_Leaf2() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf2() { var src1 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static (int, bool)[] e1 = new (int, bool)[1]; public static (int, bool)[] e2 = new (int, bool)[1]; static void Main(string[] args) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Delete_Leaf3() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var b in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var a in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_Delete_Leaf3() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach ((int b1, bool b2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach ((var a1, var a2) in e1) { foreach (var c in e1) { <AS:0>System.Console.Write();</AS:0> } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Lambda1() { var src1 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { Action a = () => { <AS:0>System.Console.Write();</AS:0> }; <AS:1>a();</AS:1> } }"; var src2 = @" class Test { public static int[] e1 = new int[1]; public static int[] e2 = new int[1]; static void Main(string[] args) { foreach (var b in e1) { foreach (var c in e1) { Action a = () => { foreach (var a in e1) { <AS:0>System.Console.Write();</AS:0> } }; } <AS:1>a();</AS:1> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var a in e1)", CSharpFeaturesResources.foreach_statement), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "foreach (var b in e1)", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { foreach (var a in F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { foreach (var a in G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "foreach (var a in G(a => a))", CSharpFeaturesResources.foreach_statement)); } [Fact] public void ForEach_Update_Nullable() { var src1 = @" class C { static void F() { var arr = new int?[] { 0 }; foreach (var s in arr) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static void F() { var arr = new int[] { 0 }; foreach (var s in arr) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEach_DeleteBody() { var src1 = @" class C { static void F() { foreach (var s in new[] { 1 }) <AS:0>G();</AS:0> } } "; var src2 = @" class C { static void F() { foreach (var s in new[] { 1 }) <AS:0>;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForEachVariable_DeleteBody() { var src1 = @" class C { static void F() { foreach ((var a1, var a2) in new[] { (1,1) }) <AS:0>G();</AS:0> } } "; var src2 = @" class C { static void F() { foreach ((var a1, var a2) in new[] { (1,1) }) <AS:0>;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region For Statement [Fact] public void ForStatement_Initializer1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(2)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "i = F(2)")); } [Fact] public void ForStatement_Initializer2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>, F(1); i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>, F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Initializer_Delete() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (<AS:1>i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { int i; for (; <AS:1>i < 10</AS:1>; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "for (; i < 10 ; i++)", FeaturesResources.code)); } [Fact] public void ForStatement_Declarator1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>var i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>var i = F(2)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "var i = F(2)")); } [Fact] public void ForStatement_Declarator2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(1); i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Declarator3() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>; i < 10; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (<AS:1>int i = F(1)</AS:1>, j = F(2); i < 10; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Condition1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(10)</AS:1>; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(20)</AS:1>; i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "i < F(20)")); } [Fact] public void ForStatement_Condition_Delete() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; <AS:1>i < F(10)</AS:1>; i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; ; <AS:1>i++</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "for (int i = 1; ; i++ )", FeaturesResources.code)); } [Fact] public void ForStatement_Incrementors1() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(20); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Incrementors2() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(2)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(2)")); } [Fact] public void ForStatement_Incrementors3() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>, i++) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ForStatement_Incrementors4() { var src1 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); <AS:1>F(1)</AS:1>, i++) { System.Console.Write(0); } } }"; var src2 = @" class Test { private static int F(int a) { <AS:0>return a;</AS:0> } static void Main(string[] args) { for (int i = 1; i < F(10); i++, <AS:1>F(1)</AS:1>) { System.Console.Write(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Using Statement and Local Declaration [Fact] public void UsingStatement_Expression_Update_Leaf() { var src1 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; static void Main(string[] args) { using (a) { using (b) { <AS:0>System.Console.Write();</AS:0> } } } }"; var src2 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; static void Main(string[] args) { using (a) { using (c) { using (b) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Using with an expression generates code that stores the value of the expression in a compiler-generated temp. // This temp is not initialized when using is added around an active statement so the disposal is a no-op. // The user might expect that the object the field points to is disposed at the end of the using block, but it isn't. edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "using (c)", CSharpFeaturesResources.using_statement)); } [Fact] public void UsingStatement_Declaration_Update_Leaf() { var src1 = @" class Test { static void Main(string[] args) { using (var a = new Disposable()) { using (var b = new Disposable()) { <AS:0>System.Console.Write();</AS:0> } } } }"; var src2 = @" class Test { static void Main(string[] args) { using (var a = new Disposable()) { using (var c = new Disposable()) { using (var b = new Disposable()) { <AS:0>System.Console.Write();</AS:0> } } } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using with a declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_Leaf1() { var src1 = @" class Test { static void Main(string[] args) { using var a = new Disposable(), b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { using var a = new Disposable(), c = new Disposable(), b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using local declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_Leaf2() { var src1 = @" class Test { static void Main(string[] args) { using var a = new Disposable(); using var b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { using var a = new Disposable(); using var c = new Disposable(); using var b = new Disposable(); <AS:0>System.Console.Write();</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // Unlike using with an expression, using local declaration does not introduce compiler-generated temps. // As with other local declarations that are added but not executed, the variable is not initialized and thus // there should be no expectation (or need) for its disposal. Hence we do not report a rude edit. edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Update_NonLeaf1() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingStatement_Update_NonLeaf2() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (Disposable a = new Disposable(1), b = Disposable(2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (Disposable a = new Disposable(1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingStatement_Update_NonLeaf_Lambda() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(() => 1)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { using (var a = new Disposable(() => 2)) { System.Console.Write(); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingLocalDeclaration_Update_NonLeaf1() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(1); using Disposable b = new Disposable(2), c = new Disposable(3); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(1); using Disposable b = new Disposable(20), c = new Disposable(3); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "}")); } [Fact] public void UsingLocalDeclaration_Update_NonLeaf_Lambda() { var src1 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(() => 1); { using var x = new Disposable(1); } using Disposable b = new Disposable(() => 2), c = new Disposable(() => 3); <AS:1>}</AS:1> } }"; var src2 = @" class Disposable : IDisposable { public void Dispose() <AS:0>{</AS:0>} } class Test { static void Main(string[] args) { if (F()) { using Disposable a = new Disposable(() => 10); { using var x = new Disposable(2); } Console.WriteLine(1); using Disposable b = new Disposable(() => 20), c = new Disposable(() => 30); <AS:1>}</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Expression_InLambdaBody1() { var src1 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; public static System.IDisposable d = null; static void Main(string[] args) { using (a) { Action a = () => { using (b) { <AS:0>System.Console.Write();</AS:0> } }; } <AS:1>a();</AS:1> } }"; var src2 = @" class Test { public static System.IDisposable a = null; public static System.IDisposable b = null; public static System.IDisposable c = null; public static System.IDisposable d = null; static void Main(string[] args) { using (d) { Action a = () => { using (c) { using (b) { <AS:0>System.Console.Write();</AS:0> } } }; } <AS:1>a();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "using (c)", CSharpFeaturesResources.using_statement)); } [Fact] public void UsingStatement_Expression_Update_Lambda1() { var src1 = @" class C { static unsafe void Main(string[] args) { using (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { using (F(a => a + 1)) { <AS:0>Console.WriteLine(2);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UsingStatement_Expression_Update_Lambda2() { var src1 = @" class C { static unsafe void Main(string[] args) { using (F(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var src2 = @" class C { static unsafe void Main(string[] args) { using (G(a => a)) { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "using (G(a => a))", CSharpFeaturesResources.using_statement)); } #endregion #region Conditional Block Statements (If, Switch, While, Do) [Fact] public void IfBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void IfBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>if (!B())</AS:1> { System.Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "if (!B())")); } [Fact] public void IfBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>if (B(() => 1))</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>if (B(() => 2))</AS:1> { System.Console.WriteLine(0); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void WhileBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void WhileBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (B())</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { <AS:1>while (!B())</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "while (!B())")); } [Fact] public void WhileBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>while (B(() => 1))</AS:1> { System.Console.WriteLine(0); } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>while (B(() => 2))</AS:1> { System.Console.WriteLine(1); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Update1() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B());</AS:1> } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (B());</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Update2() { var src1 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B());</AS:1> } }"; var src2 = @" class C { public static bool B() <AS:0>{</AS:0> return false; } public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (!B());</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "while (!B());")); } [Fact] public void DoWhileBody_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { do { System.Console.WriteLine(0); } <AS:1>while (B(() => 1));</AS:1> } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { do { System.Console.WriteLine(1); } <AS:1>while (B(() => 2));</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void DoWhileBody_Delete() { var src1 = @" class C { static void F() { do <AS:0>G();</AS:0> while (true); } } "; var src2 = @" class C { static void F() { do <AS:0>;</AS:0> while (true); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchCase_Update1() { var src1 = @" class C { public static string F() <AS:0>{</AS:0> return null; } public static void Main() { <AS:1>switch (F())</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(1); break; } } }"; var src2 = @" class C { public static string F() <AS:0>{</AS:0> return null; } public static void Main() { <AS:1>switch (F())</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(2); break; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchCase_Update_Lambda() { var src1 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>switch (B(() => 1))</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(1); break; } } }"; var src2 = @" class C { public static bool B(Func<int> a) => <AS:0>false</AS:0>; public static void Main() { <AS:1>switch (B(() => 2))</AS:1> { case ""a"": System.Console.WriteLine(0); break; case ""b"": System.Console.WriteLine(2); break; } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Switch Statement When Clauses, Patterns [Fact] public void SwitchWhenClause_PatternUpdate1() { var src1 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; case byte a when G5(a): return 10; case double b when G2(b): return 20; case C { X: 2 } when G4(9): return 30; case C { X: 2, Y: C { X: 1 } } c1 when G3(c1): return 40; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; case byte a when G5(a): return 10; case double b when G2(b): return 20; case C { X: 2 } when G4(9): return 30; case C { X: 2, Y: C { X: 2 } } c1 when G3(c1): return 40; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_PatternInsert() { var src1 = @" class C { public static int Main() { switch (F()) { case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_PatternDelete() { var src1 = @" class C { public static int Main() { switch (F()) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenDelete() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1: case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenAdd() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1: case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F())", CSharpFeaturesResources.switch_statement_case_clause)); } [Fact] public void SwitchWhenClause_WhenUpdate() { var src1 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F()) { case byte a1 when G1(a1 * 2): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchWhenClause_UpdateGoverningExpression() { var src1 = @" class C { public static int Main() { switch (F(1)) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var src2 = @" class C { public static int Main() { switch (F(2)) { case int a1 when G1(a1): case int a2 <AS:0>when G1(a2)</AS:0>: return 10; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "switch (F(2))", CSharpFeaturesResources.switch_statement)); } [Fact] public void Switch_PropertyPattern_Update_NonLeaf() { var src1 = @" class C { public int X { get => <AS:0>1</AS:0>; } public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C { X: 1 }: return 1; } return 0; } }"; var src2 = @" class C { public int X { get => <AS:0>1</AS:0>; } public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C { X: 2 }: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (obj)")); } [Fact] public void Switch_PositionalPattern_Update_NonLeaf() { var src1 = @" class C { public void Deconstruct(out int x) => <AS:0>x = X</AS:0>; public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C ( x: 1 ): return 1; } return 0; } }"; var src2 = @" class C { public void Deconstruct(out int x) => <AS:0>x = X</AS:0>; public static int F(object obj) { <AS:1>switch (obj)</AS:1> { case C ( x: 2 ): return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (obj)")); } [Fact] public void Switch_VarPattern_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case var (x, y): return 1; case 2: return 2; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case var (x, y): return 1; case 3: return 2; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (G())")); } [Fact] public void Switch_DiscardPattern_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case bool _: return 1; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case int _: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "switch (G())")); } [Fact] public void Switch_NoPatterns_Update_NonLeaf() { var src1 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case 1: return 1; } return 0; } }"; var src2 = @" class C { public static object G() => <AS:0>null</AS:0>; public static int F(object obj) { <AS:1>switch (G())</AS:1> { case 2: return 1; } return 0; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Switch Expression [Fact] public void SwitchExpression() { var src1 = @" class C { public static int Main() { Console.WriteLine(1); <AS:4>return F() switch { int a <AS:0>when F1()</AS:0> => <AS:1>F2()</AS:1>, bool b => <AS:2>F3()</AS:2>, _ => <AS:3>F4()</AS:3> };</AS:4> } }"; var src2 = @" class C { public static int Main() { Console.WriteLine(2); <AS:4>return F() switch { int a <AS:0>when F1()</AS:0> => <AS:1>F2()</AS:1>, bool b => <AS:2>F3()</AS:2>, _ => <AS:3>F4()</AS:3> };</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchExpression_Lambda1() { var src1 = @" class C { public static int Main() => <AS:1>F() switch { 0 => new Func<int>(() => <AS:0>1</AS:0>)(), _ => 2}</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>F() switch { 0 => new Func<int>(() => <AS:0>3</AS:0>)(), _ => 2}</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void SwitchExpression_Lambda2() { var src1 = @" class C { public static int Main() => <AS:1>F() switch { i => new Func<int>(() => <AS:0>i + 1</AS:0>)(), _ => 2}</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>F() switch { i => new Func<int>(() => <AS:0>i + 3</AS:0>)(), _ => 2}</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_MemberExpressionBody() { var src1 = @" class C { public static int Main() => <AS:0>F() switch { 0 => 1, _ => 2}</AS:0>; }"; var src2 = @" class C { public static int Main() => <AS:0>G() switch { 0 => 10, _ => 20}</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_LambdaBody() { var src1 = @" class C { public static Func<int> M() => () => <AS:0>F() switch { 0 => 1, _ => 2}</AS:0>; }"; var src2 = @" class C { public static Func<int> M() => () => <AS:0>G() switch { 0 => 10, _ => 20}</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_QueryLambdaBody() { var src1 = @" class C { public static IEnumerable<int> M() { return from a in new[] { 1 } where <AS:0>F() <AS:1>switch { 0 => true, _ => false}</AS:0>/**/</AS:1> select a; } }"; var src2 = @" class C { public static IEnumerable<int> M() { return from a in new[] { 2 } where <AS:0>F() <AS:1>switch { 0 => true, _ => false}</AS:0>/**/</AS:1> select a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_NestedInGoverningExpression() { var src1 = @" class C { public static int Main() => <AS:1>(F() switch { 0 => 1, _ => 2 }) switch { 1 => <AS:0>10</AS:0>, _ => 20 }</AS:1>; }"; var src2 = @" class C { public static int Main() => <AS:1>(G() switch { 0 => 10, _ => 20 }) switch { 10 => <AS:0>100</AS:0>, _ => 200 }</AS:1>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "(G() switch { 0 => 10, _ => 20 }) switch { 10 => 100 , _ => 200 }")); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_NestedInArm() { var src1 = @" class C { public static int Main() => F1() switch { 1 when F2() <AS:0>switch { 0 => true, _ => false }</AS:0> => F3() <AS:1>switch { 0 => 1, _ => 2 }</AS:1>, _ => 20 }; }"; var src2 = @" class C { public static int Main() => F1() switch { 1 when F2() <AS:0>switch { 0 => true, _ => false }</AS:0> => F3() <AS:1>switch { 0 => 1, _ => 2 }</AS:1>, _ => 20 }; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete1() { var src1 = @" class C { public static int Main() { return Method() switch { true => G(), _ => F2() switch { 1 => <AS:0>0</AS:0>, _ => 2 } }; } }"; var src2 = @" class C { public static int Main() { return Method() switch { true => G(), _ => <AS:0>1</AS:0> }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete2() { var src1 = @" class C { public static int Main() { return F1() switch { 1 => 0, _ => F2() switch { 1 => <AS:0>0</AS:0>, _ => 2 } }; } }"; var src2 = @" class C { public static int Main() { return F1() switch { 1 => <AS:0>0</AS:0>, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] [WorkItem(43099, "https://github.com/dotnet/roslyn/issues/43099")] public void SwitchExpression_Delete3() { var src1 = @" class C { public static int Main() { return F1() switch { 1 when F2() switch { 1 => <AS:0>true</AS:0>, _ => false } => 0, _ => 2 }; } }"; var src2 = @" class C { public static int Main() { return F1() switch { 1 <AS:0>when F3()</AS:0> => 0, _ => 1 }; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Try [Fact] public void Try_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } catch { } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "try", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch (IOException) { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "try", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Update_Inner2() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>catch { }</ER:1.0> Console.WriteLine(2); } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFinally_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { <AS:1>Goo();</AS:1> } <ER:1.0>finally { }</ER:1.0> Console.WriteLine(2); } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch { } } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { <AS:0>Console.WriteLine(1);</AS:0> } catch (IOException) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFinally_DeleteStatement_Inner() { var src1 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>Console.WriteLine(1);</AS:1> } <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var src2 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>}</AS:1> finally { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void TryFinally_DeleteStatement_Leaf() { var src1 = @" class C { static void Main(string[] args) { <ER:0.0>try { Console.WriteLine(0); } finally { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { Console.WriteLine(0); } finally { <AS:0>}</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Try_DeleteStatement_Inner() { var src1 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>Console.WriteLine(1);</AS:1> } <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var src2 = @" class C { static void Main() { <AS:0>Console.WriteLine(0);</AS:0> try { <AS:1>}</AS:1> <ER:1.0>finally { Console.WriteLine(2); }</ER:1.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void Try_DeleteStatement_Leaf() { var src1 = @" class C { static void Main() { try { <AS:0>Console.WriteLine(1);</AS:0> } finally { Console.WriteLine(2); } } }"; var src2 = @" class C { static void Main() { try { <AS:0>}</AS:0> finally { Console.WriteLine(2); } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Catch [Fact] public void Catch_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } catch { <AS:1>Goo();</AS:1> } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } catch { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Console.WriteLine(1);", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_InFilter_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (Exception) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void Catch_Update_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } <ER:0.0>catch (IOException) { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Inner() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(1))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) <AS:1>when (Goo(2))</AS:1> { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "when (Goo(2))"), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Leaf1() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(1))</AS:0> { }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(2))</AS:0> { }</ER:0.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } [Fact] public void CatchFilter_Update_Leaf2() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (IOException) <AS:0>when (Goo(1))</AS:0> { }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:0.0>catch (Exception) <AS:0>when (Goo(1))</AS:0> { }<ER:0.0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause)); } #endregion #region Finally [Fact] public void Finally_Add_Inner() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } finally { <AS:1>Goo();</AS:1> } } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Add_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { try { } finally { <AS:0>Console.WriteLine(1);</AS:0> } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Delete_Inner() { var src1 = @" class C { static void Main(string[] args) { <ER:1.0>try { } finally { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.finally_clause)); } [Fact] public void Finally_Delete_Leaf() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <ER:0.0>try { } finally { <AS:0>Console.WriteLine(1);</AS:0> }</ER:0.0> } }"; var src2 = @" class C { static void Main(string[] args) { <AS:1>Goo();</AS:1> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Console.WriteLine(1);", CSharpFeaturesResources.finally_clause)); } #endregion #region Try-Catch-Finally [Fact] public void TryCatchFinally() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (Exception) { try { try { } finally { try { <AS:1>Goo();</AS:1> } catch { } } } catch (Exception) { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "catch", CSharpFeaturesResources.catch_clause), Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "try", CSharpFeaturesResources.try_block), Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "Goo();", CSharpFeaturesResources.try_block), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "finally", CSharpFeaturesResources.finally_clause)); } [Fact, WorkItem(23865, "https://github.com/dotnet/roslyn/issues/23865")] public void TryCatchFinally_Regions() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException) { try { try { try { <AS:1>Goo();</AS:1> } catch { } } catch (Exception) { } } finally { } }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: this is incorrect, we need to report a rude edit: edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(23865, "https://github.com/dotnet/roslyn/issues/23865")] public void TryCatchFinally2_Regions() { var src1 = @" class C { static void Main(string[] args) { try { try { try { try { <AS:1>Goo();</AS:1> } <ER:1.3>catch { }</ER:1.3> } <ER:1.2>catch (Exception) { }</ER:1.2> } <ER:1.1>finally { }</ER:1.1> } <ER:1.0>catch (IOException) { } finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { try { try { try { <AS:1>Goo();</AS:1> } <ER:1.3>catch { }</ER:1.3> } <ER:1.2>catch (Exception) { }</ER:1.2> } <ER:1.1>finally { }</ER:1.1> } <ER:1.0>catch (IOException) { } finally { }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: this is incorrect, we need to report a rude edit since an ER span has been changed (empty line added): edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFilter_Regions1() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) when (e == null) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) when (e == null) { <AS:1>Goo();</AS:1> }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TryFilter_Regions2() { var src1 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) <AS:1>when (e == null)</AS:1> { Goo(); }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { static void Main(string[] args) { try { } <ER:1.0>catch (IOException e) <AS:1>when (e == null)</AS:1> { Goo(); }</ER:1.0> } static void Goo() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Lambda1() { var src1 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = null; try { f = x => <AS:1>1 + Goo(x)</AS:1>; } catch { } <AS:2>Console.Write(f(2));</AS:2> } }"; var src2 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = null; f = x => <AS:1>1 + Goo(x)</AS:1>; <AS:2>Console.Write(f(2));</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Try_Lambda2() { var src1 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = x => { try { <AS:1>return 1 + Goo(x);</AS:1> } <ER:1.0>catch { }</ER:1.0> }; <AS:2>Console.Write(f(2));</AS:2> } }"; var src2 = @" using System; using System.Linq; class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { Func<int, int> f = x => { <AS:1>return 1 + Goo(x);</AS:1> }; <AS:2>Console.Write(f(2));</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "return 1 + Goo(x);", CSharpFeaturesResources.try_block)); } [Fact] public void Try_Query_Join1() { var src1 = @" class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { try { q = from x in xs join y in ys on <AS:1>F()</AS:1> equals G() select 1; } catch { } <AS:2>q.ToArray();</AS:2> } }"; var src2 = @" class C { static int Goo(int x) { <AS:0>return 1;</AS:0> } static void Main() { q = from x in xs join y in ys on <AS:1>F()</AS:1> equals G() select 1; <AS:2>q.ToArray();</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Checked/Unchecked [Fact] public void CheckedUnchecked_Insert_Leaf() { var src1 = @" class Test { static void Main(string[] args) { int a = 1, b = 2; <AS:0>Console.WriteLine(a*b);</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { int a = 1, b = 2; checked { <AS:0>Console.WriteLine(a*b);</AS:0> } } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void CheckedUnchecked_Insert_Internal() { var src1 = @" class Test { static void Main(string[] args) { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Delete_Internal() { var src1 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteAroundActiveStatement, "System.Console.WriteLine(5 * M(1, 2));", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Update_Internal() { var src1 = @" class Test { static void Main(string[] args) { unchecked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { <AS:1>System.Console.WriteLine(5 * M(1, 2));</AS:1> } } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Lambda1() { var src1 = @" class Test { static void Main(string[] args) { unchecked { Action f = () => <AS:1>5 * M(1, 2)</AS:1>; } <AS:2>f();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" class Test { static void Main(string[] args) { checked { Action f = () => <AS:1>5 * M(1, 2)</AS:1>; } <AS:2>f();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } [Fact] public void CheckedUnchecked_Query1() { var src1 = @" using System.Collections.Generic; using System.Linq; class Test { static void Main() { IEnumerable<int> f; unchecked { f = from a in new[] { 5 } select <AS:1>M(a, int.MaxValue)</AS:1>; } <AS:2>f.ToArray();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var src2 = @" using System.Collections.Generic; using System.Linq; class Test { static void Main() { IEnumerable<int> f; checked { f = from a in new[] { 5 } select <AS:1>M(a, int.MaxValue)</AS:1>; } <AS:2>f.ToArray();</AS:2> } private static int M(int a, int b) { <AS:0>return a * b;</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "checked", CSharpFeaturesResources.checked_statement)); } #endregion #region Lambdas [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_GeneralStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>F(a => <AS:0>1</AS:0>);</AS:1> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>F(a => <AS:0>2</AS:0>);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_Nested1() { var src1 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>1</AS:0>)</AS:1>);</AS:2> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>2</AS:0>)</AS:1>);</AS:2> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_Nested2() { var src1 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>F(a => <AS:0>1</AS:0>)</AS:1>);</AS:2> } } "; var src2 = @" class C { static void Main(string[] args) { <AS:2>F(b => <AS:1>G(a => <AS:0>2</AS:0>)</AS:1>);</AS:2> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "G(a => 2 )")); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_IfStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>if (F(a => <AS:0>1</AS:0>))</AS:1> { } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>if (F(a => <AS:0>2</AS:0>))</AS:1> { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_WhileStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>while (F(a => <AS:0>1</AS:0>))</AS:1> { } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>while (F(a => <AS:0>2</AS:0>))</AS:1> { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_DoStatement() { var src1 = @" class C { static void Main(string[] args) { do {} <AS:1>while (F(a => <AS:0>1</AS:0>));</AS:1> } } "; var src2 = @" class C { static void Main(string[] args) { do {} <AS:1>while (F(a => <AS:0>2</AS:0>));</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_SwitchStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>switch (F(a => <AS:0>1</AS:0>))</AS:1> { case 0: break; case 1: break; } } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>switch (F(a => <AS:0>2</AS:0>))</AS:1> { case 0: break; case 1: break; } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_LockStatement() { var src1 = @" class C { static void Main(string[] args) { <AS:1>lock (F(a => <AS:0>1</AS:0>))</AS:1> {} } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>lock (F(a => <AS:0>2</AS:0>))</AS:1> {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(1359, "https://github.com/dotnet/roslyn/issues/1359")] public void Lambdas_LeafEdits_UsingStatement1() { var src1 = @" class C { static void Main(string[] args) { <AS:1>using (F(a => <AS:0>1</AS:0>))</AS:1> {} } } "; var src2 = @" class C { static void Main(string[] args) { <AS:1>using (F(a => <AS:0>2</AS:0>))</AS:1> {} } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ExpressionToStatements() { var src1 = @" class C { static void Main(string[] args) { Func<int, int> f = a => <AS:0>1</AS:0>; } } "; var src2 = @" class C { static void Main(string[] args) { <AS:0>Func<int, int> f = a => { return 1; };</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ExpressionToDelegate() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = a => <AS:0>1</AS:0>; } } "; var src2 = @" using System; class C { static void Main() { <AS:0>Func<int, int> f = delegate(int a) { return 1; };</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_StatementsToExpression() { var src1 = @" class C { static void Main(string[] args) { Func<int, int> f = a => { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" class C { static void Main(string[] args) { <AS:0>Func<int, int> f = a => 1;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_DelegateToExpression() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = delegate(int a) { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" using System; class C { static void Main() { <AS:0>Func<int, int> f = a => 1;</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_StatementsToDelegate() { var src1 = @" using System; class C { static void Main() { Func<int, int> f = a => { <AS:0>return 1;</AS:0> }; } } "; var src2 = @" using System; class C { static void Main() { Func<int, int> f = delegate(int a) { <AS:0>return 2;</AS:0> }; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Lambdas_ActiveStatementUpdate() { var src1 = @" using System; class C { static void Main(string[] args) { Func<int, int, int> f = (int a, int b) => <AS:0>a + b + 1</AS:0>; <AS:1>f(2);</AS:1> } }"; var src2 = @" using System; class C { static void Main(string[] args) { Func<int, int, int> f = (_, _) => <AS:0>10</AS:0>; <AS:1>f(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(active, capabilities: EditAndContinueTestHelpers.Net6RuntimeCapabilities); } [Fact] public void Lambdas_ActiveStatementRemoved1() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { return b => { <AS:0>return b;</AS:0> }; }; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = b => { <AS:0>return b;</AS:0> }; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "return b;", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved2() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => (b) => <AS:0>b</AS:0>; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = <AS:0>(b)</AS:0> => b; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "(b)", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved3() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { Func<int, int> z; F(b => { <AS:0>return b;</AS:0> }, out z); return z; }; var z = f(1); <AS:1>z(2);</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { Func<int, int> f = b => { <AS:0>F(b);</AS:0> return 1; }; var z = f; <AS:1>z(2);</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "F(b);", CSharpFeaturesResources.lambda)); } [Fact] public void Lambdas_ActiveStatementRemoved4() { var src1 = @" class C { static void Main(string[] args) { Func<int, Func<int, int>> f = a => { <AS:1>z(2);</AS:1> return b => { <AS:0>return b;</AS:0> }; }; } }"; var src2 = @" class C { static void Main(string[] args) <AS:0,1>{</AS:0,1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "{", CSharpFeaturesResources.lambda), Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "{", CSharpFeaturesResources.lambda)); } [Fact] public void Queries_ActiveStatementRemoved_WhereClause() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b where <AS:0>b.goo</AS:0> select b.bar; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select b.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.where_clause)); } [Fact] public void Queries_ActiveStatementRemoved_LetClause() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b let x = <AS:0>b.goo</AS:0> select x; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.let_clause)); } [Fact] public void Queries_ActiveStatementRemoved_JoinClauseLeft() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b join c in d on <AS:0>a.goo</AS:0> equals c.bar select a.bar; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.join_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy1() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby <AS:0>a.x</AS:0>, a.y descending, a.z ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy2() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby a.x, <AS:0>a.y</AS:0> descending, a.z ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_ActiveStatementRemoved_OrderBy3() { var src1 = @" class C { static void Main(string[] args) { var s = from a in b orderby a.x, a.y descending, <AS:0>a.z</AS:0> ascending select a; <AS:1>s.ToArray();</AS:1> } }"; var src2 = @" class C { static void Main(string[] args) { var s = <AS:0>from</AS:0> a in b select a.bar; <AS:1>s.ToArray();</AS:1> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "from", CSharpFeaturesResources.orderby_clause)); } [Fact] public void Queries_Remove_JoinInto1() { var src1 = @" class C { static void Main() { var q = from x in xs join y in ys on F() equals G() into g select <AS:0>1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from x in xs join y in ys on F() equals G() select <AS:0>1</AS:0>; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Queries_Remove_QueryContinuation1() { var src1 = @" class C { static void Main() { var q = from x in xs group x by x.F() into g where <AS:0>g.F()</AS:0> select 1; } }"; var src2 = @" class C { static void Main() { var q = from x in xs group x by x.F() <AS:0>into</AS:0> g select 1; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "into", CSharpFeaturesResources.where_clause)); } [Fact] public void Queries_Remove_QueryContinuation2() { var src1 = @" class C { static void Main() { var q = from x in xs group x by x.F() into g select <AS:0>1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from x in xs <AS:0>join</AS:0> y in ys on F() equals G() into g select 1; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "join", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Select_Reduced1() { var src1 = @" class C { static void Main() { var q = from a in array where a > 0 select <AS:0>a + 1</AS:0>; } }"; var src2 = @" class C { static void Main() { var q = from a in array where a > 0 <AS:0>select</AS:0> a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "select", CSharpFeaturesResources.select_clause)); } [Fact] public void Queries_Select_Reduced2() { var src1 = @" class C { static int F(IEnumerable<int> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array where a > 0 select a + 1);</AS:1> } }"; var src2 = @" class C { static int F(IEnumerable<int> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array where a > 0 select a);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(from a in array where a > 0 select a);")); } [Fact] public void Queries_GroupBy_Reduced1() { var src1 = @" class C { static void Main() { var q = from a in array group <AS:0>a + 1</AS:0> by a; } }"; var src2 = @" class C { static void Main() { var q = from a in array <AS:0>group</AS:0> a by a; } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementLambdaRemoved, "group", CSharpFeaturesResources.groupby_clause)); } [Fact] public void Queries_GroupBy_Reduced2() { var src1 = @" class C { static int F(IEnumerable<IGrouping<int, int>> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array group a by a);</AS:1> } }"; var src2 = @" class C { static int F(IEnumerable<IGrouping<int, int>> e) => <AS:0>1</AS:0>; static void Main() { <AS:1>F(from a in array group a + 1 by a);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "F(from a in array group a + 1 by a);")); } #endregion #region State Machines [Fact] public void MethodToIteratorMethod_WithActiveStatement() { var src1 = @" class C { static IEnumerable<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { <AS:0>Console.WriteLine(1);</AS:0> yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "yield return 1;", CSharpFeaturesResources.yield_return_statement)); } [Fact] public void MethodToIteratorMethod_WithActiveStatementInLambda() { var src1 = @" class C { static IEnumerable<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // should not contain RUDE_EDIT_INSERT_AROUND edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToIteratorMethod_WithoutActiveStatement() { var src1 = @" class C { static IEnumerable<int> F() { Console.WriteLine(1); return new[] { 1, 2, 3 }; } } "; var src2 = @" class C { static IEnumerable<int> F() { Console.WriteLine(1); yield return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitExpression() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitForEach() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> await foreach (var x in AsyncIter()) { } return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await foreach (var x in AsyncIter())", CSharpFeaturesResources.asynchronous_foreach_statement)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_AwaitUsing() { var src1 = @" class C { static Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { <AS:0>Console.WriteLine(1);</AS:0> await using IAsyncDisposable x = new AsyncDisposable(), y = new AsyncDisposable(); return 1; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "x = new AsyncDisposable()", CSharpFeaturesResources.asynchronous_using_declaration), Diagnostic(RudeEditKind.InsertAroundActiveStatement, "y = new AsyncDisposable()", CSharpFeaturesResources.asynchronous_using_declaration)); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_NoAwait1() { var src1 = @" class C { static void F() <AS:0>{</AS:0> Console.WriteLine(1); } } "; var src2 = @" class C { static async void F() <AS:0>{</AS:0> Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithActiveStatement_NoAwait2() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var src2 = @" class C { static async void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithActiveStatementInLambda1() { var src1 = @" class C { static Task<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // should not contain RUDE_EDIT_INSERT_AROUND edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithActiveStatementInLambda_2() { var src1 = @" class C { static void F() { var f = new Action(() => { <AS:1>Console.WriteLine(1);</AS:1> }); <AS:0>f();</AS:0> } } "; var src2 = @" class C { static async void F() { var f = new Action(() => { <AS:1>Console.WriteLine(1);</AS:1> }); <AS:0>f();</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithLambda() { var src1 = @" class C { static void F() <AS:0>{</AS:0> var f = new Action(() => { Console.WriteLine(1); }); f(); } } "; var src2 = @" class C { static async void F() <AS:0>{</AS:0> var f = new Action(() => { Console.WriteLine(1); }); f(); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "static async void F()")); } [Fact] public void MethodToAsyncMethod_WithoutActiveStatement_1() { var src1 = @" class C { static Task<int> F() { Console.WriteLine(1); return Task.FromResult(1); } } "; var src2 = @" class C { static async Task<int> F() { Console.WriteLine(1); return await Task.FromResult(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MethodToAsyncMethod_WithoutActiveStatement_2() { var src1 = @" class C { static void F() { Console.WriteLine(1); } } "; var src2 = @" class C { static async void F() { Console.WriteLine(1); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement() { var src1 = @" using System; using System.Threading.Tasks; class C { static void F() { var f = new Func<Task<int>>(() => { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); }); } } "; var src2 = @" using System; using System.Threading.Tasks; class C { static void F() { var f = new Func<Task<int>>(async () => { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement_NoAwait() { var src1 = @" using System; class C { static void F() { var f = new Action(() => { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var src2 = @" using System; class C { static void F() { var f = new Action(async () => { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "()")); } [Fact] public void LambdaToAsyncLambda_WithActiveStatement_NoAwait_Nested() { var src1 = @" class C { static void F() { var f = new Func<int, Func<int, int>>(a => <AS:0>b => 1</AS:0>); } } "; var src2 = @" class C { static void F() { var f = new Func<int, Func<int, int>>(async a => <AS:0>b => 1</AS:0>); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, "a")); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunctionToAsyncLocalFunction_BlockBody_WithActiveStatement() { var src1 = @" class C { static void F() { Task<int> f() { <AS:0>Console.WriteLine(1);</AS:0> return Task.FromResult(1); } } } "; var src2 = @" class C { static void F() { async Task<int> f() { <AS:0>Console.WriteLine(1);</AS:0> return await Task.FromResult(1); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] [WorkItem(37054, "https://github.com/dotnet/roslyn/issues/37054")] public void LocalFunctionToAsyncLocalFunction_ExpressionBody_WithActiveStatement() { var src1 = @" class C { static void F() { Task<int> f() => <AS:0>Task.FromResult(1)</AS:0>; } } "; var src2 = @" class C { static void F() { async Task<int> f() => <AS:0>await Task.FromResult(1)</AS:0>; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.InsertAroundActiveStatement, "await", CSharpFeaturesResources.await_expression)); } [Fact] public void AnonymousFunctionToAsyncAnonymousFunction_WithActiveStatement_NoAwait() { var src1 = @" using System.Threading.Tasks; class C { static void F() { var f = new Func<Task>(delegate() { <AS:0>Console.WriteLine(1);</AS:0> return Task.CompletedTask; }); } } "; var src2 = @" using System.Threading.Tasks; class C { static async void F() { var f = new Func<Task>(async delegate() { <AS:0>Console.WriteLine(1);</AS:0> }); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdatingStateMachineMethodAroundActiveStatement, FeaturesResources.delegate_)); } [Fact] public void AsyncMethodEdit_Semantics() { var src1 = @" using System; using System.Threading.Tasks; class C { static async Task<int> F() { await using var x = new AsyncDisposable(); await foreach (var x in AsyncIter()) { Console.WriteLine(x); } return await Task.FromResult(1); } } "; var src2 = @" using System; using System.Threading.Tasks; class C { static async Task<int> F() { await using var x = new AsyncDisposable(); await foreach (var x in AsyncIter()) { Console.WriteLine(x + 1); } return await Task.FromResult(2); } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void IteratorMethodEdit_Semantics() { var src1 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { Console.WriteLine(1); yield return 1; } } "; var src2 = @" using System; using System.Collections.Generic; class C { static IEnumerable<int> F() { Console.WriteLine(2); yield return 2; } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(); } [Fact] public void AsyncIteratorMethodEdit_Semantics() { var src1 = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class C { static async IAsyncEnumerable<int> F() { Console.WriteLine(1); await Task.Delay(1); yield return 1; } } "; var src2 = @" using System; using System.Collections.Generic; using System.Threading.Tasks; class C { static async IAsyncEnumerable<int> F() { Console.WriteLine(2); await Task.Delay(2); yield return 2; } } "; var edits = GetTopEdits(src1, src2); _ = GetActiveStatements(src1, src2); edits.VerifySemanticDiagnostics(targetFrameworks: new[] { TargetFramework.NetCoreApp }); } [Fact] public void AsyncMethodToMethod() { var src1 = @" class C { static async void F() { } } "; var src2 = @" class C { static void F() { } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ChangingFromAsynchronousToSynchronous, "static void F()", FeaturesResources.method)); } #endregion #region Misplaced AS [Fact] public void MisplacedActiveStatement1() { var src1 = @" <AS:1>class C</AS:1> { public static int F(int a) { <AS:0>return a;</AS:0> <AS:2>return a;</AS:2> } }"; var src2 = @" class C { public static int F(int a) { <AS:0>return a;</AS:0> <AS:2>return a;</AS:2> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MisplacedActiveStatement2() { var src1 = @" class C { static <AS:0>void</AS:0> Main(string[] args) { } }"; var src2 = @" class C { static void Main(string[] args) <AS:0>{</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void MisplacedTrackingSpan1() { var src1 = @" class C { static <AS:0>void</AS:0> Main(string[] args) { } }"; var src2 = @" class C { static <TS:0>void</TS:0> Main(string[] args) <AS:0>{</AS:0> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region C# 7.0 [Fact] public void UpdateAroundActiveStatement_IsPattern() { var src1 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> if (x is int i) { Console.WriteLine(""match""); } } } "; var src2 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> if (x is string s) { Console.WriteLine(""match""); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionDeclarationStatement() { var src1 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = (1, 2); } } "; var src2 = @" class C { static void F(object x) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = x; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionForEach() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> foreach (var (x, y) in new[] { (1, 2) }) { Console.WriteLine(2); } } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> foreach (var (x, y) in new[] { o }) { Console.WriteLine(2); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_VarDeconstruction() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for (var (x, y) = o1; ; ) { } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for (var (x, y) = o2; ; ) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_TypedDeconstruction() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for ((int x, int y) = o1; ; ) { } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> for ((int x, int y) = o2; ; ) { } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_Tuple() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> (int, int) t; } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> (int, int) t = (1, 2); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_LocalFunction() { var src1 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(2); } } } "; var src2 = @" class C { static void F(object o) { <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(3); } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_OutVar() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(); } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(out var x); } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_OutVarRemoved() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> M(out var x); } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_Ref() { var src1 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> ref int i = ref 1; } } "; var src2 = @" class C { static void F() { <AS:0>Console.WriteLine(1);</AS:0> ref int i = ref 2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionDeclaration() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = o1; } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> var (x, y) = o2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_DeconstructionAssignment() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> int x, y; (x, y) = o1; } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>Console.WriteLine(1);</AS:0> int x, y; (x, y) = o2; } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void UpdateAroundActiveStatement_SwitchWithPattern() { var src1 = @" class C { static void F(object o1, object o2) { <AS:0>System.Console.WriteLine(1);</AS:0> switch (o1) { case int i: break; } } } "; var src2 = @" class C { static void F(object o1, object o2) { <AS:0>System.Console.WriteLine(1);</AS:0> switch (o2) { case int i: break; } } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); edits.VerifySemanticDiagnostics(); } #endregion #region Nullable [Fact] public void ChangeLocalNullableToNonNullable() { var src1 = @" class C { static void F() { <AS:0>string? s = ""a"";</AS:0> } } "; var src2 = @" class C { static void F() { <AS:0>string s = ""a"";</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void ChangeLocalNonNullableToNullable() { var src1 = @" class C { static void F() { <AS:0>string s = ""a"";</AS:0> } } "; var src2 = @" class C { static void F() { <AS:0>string? s = ""a"";</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Partial Types [Fact] public void InsertDeleteMethod_Inactive() { // Moving inactive method declaration in a file with active statements. var srcA1 = "partial class C { void F1() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var srcB1 = "partial class C { void F2() { } }"; var srcA2 = "partial class C { void F1() { <AS:0>System.Console.WriteLine(1);</AS:0> } void F2() { } }"; var srcB2 = "partial class C { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( activeStatements: GetActiveStatements(srcA1, srcA2, path: "0"), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F2")), }), DocumentResults( activeStatements: GetActiveStatements(srcB1, srcB2, path: "1")) }); } [Fact] [WorkItem(51177, "https://github.com/dotnet/roslyn/issues/51177")] [WorkItem(54758, "https://github.com/dotnet/roslyn/issues/54758")] public void InsertDeleteMethod_Active() { // Moving active method declaration in a file with active statements. // TODO: this is currently a rude edit var srcA1 = "partial class C { }"; var srcB1 = "partial class C { void F() { <AS:0>System.Console.WriteLine(1);</AS:0> } }"; var srcA2 = "partial class C { void F() { System.Console.WriteLine(1); } }"; var srcB2 = "<AS:0>partial class C</AS:0> { }"; EditAndContinueValidation.VerifySemantics( new[] { GetTopEdits(srcA1, srcA2), GetTopEdits(srcB1, srcB2) }, new[] { DocumentResults( activeStatements: GetActiveStatements(srcA1, srcA2, path: "0"), semanticEdits: new[] { SemanticEdit(SemanticEditKind.Update, c => c.GetMember<INamedTypeSymbol>("C").GetMember("F")), }), DocumentResults( activeStatements: GetActiveStatements(srcB1, srcB2, path: "1"), // TODO: this is odd AS location https://github.com/dotnet/roslyn/issues/54758 diagnostics: new[] { Diagnostic(RudeEditKind.DeleteActiveStatement, " partial c", DeletedSymbolDisplay(FeaturesResources.method, "F()")) }) }); } #endregion #region Records [Fact] public void Record() { var src1 = @" record C(int X) { public int X { get; init; } = <AS:0>1</AS:0>; }"; var src2 = @" record C(int X) { public int X { get; init; } = <AS:0>2</AS:0>; }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Record_Constructor() { var src1 = @" record C(int X) { public int X { get; init; } = <AS:0>1</AS:0>; static void Main(string[] args) { <AS:1>var x = new C(1);</AS:1> } }"; var src2 = @" record C(int X) { public int X { get; init; } = <AS:0>2</AS:0>; static void Main(string[] args) { <AS:1>var x = new C(1);</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void Record_FieldInitializer_Lambda2() { var src1 = @" record C(int X) { Func<int, Func<int>> a = z => () => <AS:0>z + 1</AS:0>; static void Main(string[] args) { <AS:1>new C(1).a(1)();</AS:1> } }"; var src2 = @" record C(int X) { Func<int, Func<int>> a = z => () => <AS:0>z + 2</AS:0>; static void Main(string[] args) { <AS:1>new C(1).a(1)();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } #endregion #region Line Mapping /// <summary> /// Validates that changes in #line directives produce semantic updates of the containing method. /// </summary> [Fact] public void LineMapping_ChangeLineNumber_WithinMethod() { var src1 = @" class C { #line 1 ""a"" static void F() { <AS:0>A();</AS:0> #line 5 ""b"" B(1); <AS:1>B();</AS:1> #line 2 ""c"" <AS:2>C();</AS:2> <AS:3>C();</AS:3> #line hidden D(); #line default <AS:4>E();</AS:4> } }"; var src2 = @" class C { #line 1 ""a"" static void F() { <AS:0>A();</AS:0> #line 5 ""b"" B(2); <AS:1>B();</AS:1> #line 9 ""c"" <AS:2>C();</AS:2> <AS:3>C();</AS:3> #line hidden D(); #line default <AS:4>E();</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void LineMapping_ChangeFilePath() { var src1 = @" class C { static void F() { <AS:0>A();</AS:0> #line 1 ""a"" <AS:1>B();</AS:1> } }"; var src2 = @" class C { static void F() { <AS:0>A();</AS:0> #line 1 ""b"" <AS:1>B();</AS:1> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.UpdateAroundActiveStatement, "B();", string.Format(FeaturesResources._0_directive, "line"))); } [Fact] public void LineMapping_ExceptionRegions_ChangeLineNumber() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 30 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact, WorkItem(52971, "https://github.com/dotnet/roslyn/issues/52971")] public void LineMapping_ExceptionRegions_ChangeFilePath() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line default } #line 20 ""c"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: rude edit should be reported edits.VerifyRudeDiagnostics(active); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/52971"), WorkItem(52971, "https://github.com/dotnet/roslyn/issues/52971")] public void LineMapping_ExceptionRegions_LineChange_MultipleMappedFiles() { var src1 = @" class C { static void Main() <AS:0>{</AS:0> try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line 20 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var src2 = @" class C { static void Main() <AS:0>{</AS:0> try { <AS:1>Goo();</AS:1> } #line 20 ""a"" <ER:1.1>catch (E1 e) { }</ER:1.1> #line 30 ""b"" <ER:1.0>catch (E2 e) { }</ER:1.0> #line default } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); // TODO: rude edit? edits.VerifyRudeDiagnostics(active); } #endregion #region Misc [Fact] public void Delete_All_SourceText() { var src1 = @" class C { static void Main(string[] args) { <AS:1>Goo(1);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } }"; var src2 = @""; var edits = GetTopEdits(src1, src2); edits.VerifySemanticDiagnostics( Diagnostic(RudeEditKind.Delete, null, DeletedSymbolDisplay(FeaturesResources.class_, "C"))); } [Fact] public void PartiallyExecutedActiveStatement() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> <AS:1>Console.WriteLine(2);</AS:1> <AS:2>Console.WriteLine(3);</AS:2> <AS:3>Console.WriteLine(4);</AS:3> <AS:4>Console.WriteLine(5);</AS:4> } }"; var src2 = @" class C { public static void F() { <AS:0>Console.WriteLine(10);</AS:0> <AS:1>Console.WriteLine(20);</AS:1> <AS:2>Console.WriteLine(30);</AS:2> <AS:3>Console.WriteLine(40);</AS:3> <AS:4>Console.WriteLine(50);</AS:4> } }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsLeafFrame, ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsNonLeafFrame, ActiveStatementFlags.IsLeafFrame, ActiveStatementFlags.IsNonLeafFrame, ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.PartiallyExecutedActiveStatementUpdate, "Console.WriteLine(10);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(20);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(40);"), Diagnostic(RudeEditKind.ActiveStatementUpdate, "Console.WriteLine(50);")); } [Fact] public void PartiallyExecutedActiveStatement_Deleted1() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { public static void F() { <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.PartiallyExecuted | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.PartiallyExecutedActiveStatementDelete, "{", FeaturesResources.code)); } [Fact] public void PartiallyExecutedActiveStatement_Deleted2() { var src1 = @" class C { public static void F() { <AS:0>Console.WriteLine(1);</AS:0> } }"; var src2 = @" class C { public static void F() { <AS:0>}</AS:0> }"; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2, flags: new[] { ActiveStatementFlags.IsNonLeafFrame | ActiveStatementFlags.IsLeafFrame }); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.DeleteActiveStatement, "{", FeaturesResources.code)); } [Fact] public void Block_Delete() { var src1 = @" class C { public static void F() { G(1); <AS:0>{</AS:0> G(2); } G(3); } } "; var src2 = @" class C { public static void F() { G(1); <AS:0>G(3);</AS:0> } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Theory, CombinatorialData] public void MemberBodyInternalError(bool outOfMemory) { var src1 = @" class C { public static void F() { <AS:1>G();</AS:1> } public static void G() { <AS:0>H(1);</AS:0> } public static void H(int x) { } } "; var src2 = @" class C { public static void F() { <AS:1>G();</AS:1> } public static void G() { <AS:0>H(2);</AS:0> } public static void H(int x) { } } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); var validator = new CSharpEditAndContinueTestHelpers(faultInjector: node => { if (node.Parent is MethodDeclarationSyntax methodDecl && methodDecl.Identifier.Text == "G") { throw outOfMemory ? new OutOfMemoryException() : new NullReferenceException("NullRef!"); } }); var expectedDiagnostic = outOfMemory ? Diagnostic(RudeEditKind.MemberBodyTooBig, "public static void G()", FeaturesResources.method) : Diagnostic(RudeEditKind.MemberBodyInternalError, "public static void G()", FeaturesResources.method); validator.VerifySemantics( new[] { edits }, TargetFramework.NetCoreApp, new[] { DocumentResults(diagnostics: new[] { expectedDiagnostic }) }); } #endregion #region Top Level Statements [Fact] public void TopLevelStatements_UpdateAroundActiveStatement_LocalFunction() { var src1 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(2); } "; var src2 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> void M() { Console.WriteLine(3); } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TopLevelStatements_UpdateAroundActiveStatement_OutVar() { var src1 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> M(); "; var src2 = @" using System; <AS:0>Console.WriteLine(1);</AS:0> M(out var x); "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active); } [Fact] public void TopLevelStatements_Inner() { var src1 = @" using System; <AS:1>Goo(1);</AS:1> static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } "; var src2 = @" using System; while (true) { <AS:1>Goo(2);</AS:1> } static void Goo(int a) { <AS:0>Console.WriteLine(a);</AS:0> } "; var edits = GetTopEdits(src1, src2); var active = GetActiveStatements(src1, src2); edits.VerifyRudeDiagnostics(active, Diagnostic(RudeEditKind.ActiveStatementUpdate, "Goo(2);")); } #endregion } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/MethodContextReuseConstraints.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.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal readonly struct MethodContextReuseConstraints { private readonly Guid _moduleVersionId; private readonly int _methodToken; private readonly int _methodVersion; private readonly ILSpan _span; internal MethodContextReuseConstraints(Guid moduleVersionId, int methodToken, int methodVersion, ILSpan span) { Debug.Assert(moduleVersionId != Guid.Empty); Debug.Assert(MetadataTokens.Handle(methodToken).Kind == HandleKind.MethodDefinition); Debug.Assert(methodVersion >= 1); _moduleVersionId = moduleVersionId; _methodToken = methodToken; _methodVersion = methodVersion; _span = span; } public bool AreSatisfied(Guid moduleVersionId, int methodToken, int methodVersion, int ilOffset) { Debug.Assert(moduleVersionId != Guid.Empty); Debug.Assert(MetadataTokens.Handle(methodToken).Kind == HandleKind.MethodDefinition); Debug.Assert(methodVersion >= 1); Debug.Assert(ilOffset >= 0); return moduleVersionId == _moduleVersionId && methodToken == _methodToken && methodVersion == _methodVersion && _span.Contains(ilOffset); } public override string ToString() { return $"0x{_methodToken:x8}v{_methodVersion} from {_moduleVersionId} {_span}"; } /// <summary> /// Finds a span of IL containing the specified offset where local variables and imports are guaranteed to be the same. /// Examples: /// scopes: [ [ ) x [ ) ) /// result: [ ) /// /// scopes: [ x [ ) [ ) ) /// result: [ ) /// /// scopes: [ [ x ) [ ) ) /// result: [ ) /// </summary> public static ILSpan CalculateReuseSpan(int ilOffset, ILSpan initialSpan, IEnumerable<ILSpan> scopes) { Debug.Assert(ilOffset >= 0); uint _startOffset = initialSpan.StartOffset; uint _endOffsetExclusive = initialSpan.EndOffsetExclusive; foreach (ILSpan scope in scopes) { if (ilOffset < scope.StartOffset) { _endOffsetExclusive = Math.Min(_endOffsetExclusive, scope.StartOffset); } else if (ilOffset >= scope.EndOffsetExclusive) { _startOffset = Math.Max(_startOffset, scope.EndOffsetExclusive); } else { _startOffset = Math.Max(_startOffset, scope.StartOffset); _endOffsetExclusive = Math.Min(_endOffsetExclusive, scope.EndOffsetExclusive); } } return new ILSpan(_startOffset, _endOffsetExclusive); } } }
// Licensed to the .NET Foundation under one or more 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.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal readonly struct MethodContextReuseConstraints { private readonly Guid _moduleVersionId; private readonly int _methodToken; private readonly int _methodVersion; private readonly ILSpan _span; internal MethodContextReuseConstraints(Guid moduleVersionId, int methodToken, int methodVersion, ILSpan span) { Debug.Assert(moduleVersionId != Guid.Empty); Debug.Assert(MetadataTokens.Handle(methodToken).Kind == HandleKind.MethodDefinition); Debug.Assert(methodVersion >= 1); _moduleVersionId = moduleVersionId; _methodToken = methodToken; _methodVersion = methodVersion; _span = span; } public bool AreSatisfied(Guid moduleVersionId, int methodToken, int methodVersion, int ilOffset) { Debug.Assert(moduleVersionId != Guid.Empty); Debug.Assert(MetadataTokens.Handle(methodToken).Kind == HandleKind.MethodDefinition); Debug.Assert(methodVersion >= 1); Debug.Assert(ilOffset >= 0); return moduleVersionId == _moduleVersionId && methodToken == _methodToken && methodVersion == _methodVersion && _span.Contains(ilOffset); } public override string ToString() { return $"0x{_methodToken:x8}v{_methodVersion} from {_moduleVersionId} {_span}"; } /// <summary> /// Finds a span of IL containing the specified offset where local variables and imports are guaranteed to be the same. /// Examples: /// scopes: [ [ ) x [ ) ) /// result: [ ) /// /// scopes: [ x [ ) [ ) ) /// result: [ ) /// /// scopes: [ [ x ) [ ) ) /// result: [ ) /// </summary> public static ILSpan CalculateReuseSpan(int ilOffset, ILSpan initialSpan, IEnumerable<ILSpan> scopes) { Debug.Assert(ilOffset >= 0); uint _startOffset = initialSpan.StartOffset; uint _endOffsetExclusive = initialSpan.EndOffsetExclusive; foreach (ILSpan scope in scopes) { if (ilOffset < scope.StartOffset) { _endOffsetExclusive = Math.Min(_endOffsetExclusive, scope.StartOffset); } else if (ilOffset >= scope.EndOffsetExclusive) { _startOffset = Math.Max(_startOffset, scope.EndOffsetExclusive); } else { _startOffset = Math.Max(_startOffset, scope.StartOffset); _endOffsetExclusive = Math.Min(_endOffsetExclusive, scope.EndOffsetExclusive); } } return new ILSpan(_startOffset, _endOffsetExclusive); } } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Workspaces/Core/Portable/Options/IWorkspaceOptionService.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.Options { /// <summary> /// Interface used for exposing functionality from the option service that we don't want to /// ever be public. /// </summary> internal interface IWorkspaceOptionService : IOptionService { void OnWorkspaceDisposed(Workspace workspace); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Interface used for exposing functionality from the option service that we don't want to /// ever be public. /// </summary> internal interface IWorkspaceOptionService : IOptionService { void OnWorkspaceDisposed(Workspace workspace); } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Features/Core/Portable/FullyQualify/AbstractFullyQualifyCodeFixProvider.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.CodeActions; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.CodeFixes.FullyQualify { internal abstract partial class AbstractFullyQualifyCodeFixProvider : CodeFixProvider { private const int MaxResults = 3; private const int NamespaceWithNoErrorsWeight = 0; private const int TypeWeight = 1; private const int NamespaceWithErrorsWeight = 2; protected AbstractFullyQualifyCodeFixProvider() { } public override FixAllProvider? GetFixAllProvider() { // Fix All is not supported by this code fix // https://github.com/dotnet/roslyn/issues/34465 return null; } protected abstract bool IgnoreCase { get; } protected abstract bool CanFullyQualify(Diagnostic diagnostic, ref SyntaxNode node); protected abstract Task<SyntaxNode> ReplaceNodeAsync(SyntaxNode node, string containerName, bool resultingSymbolIsType, CancellationToken cancellationToken); public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var span = context.Span; var diagnostics = context.Diagnostics; var cancellationToken = context.CancellationToken; var project = document.Project; var diagnostic = diagnostics.First(); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = root.FindToken(span.Start).GetAncestors<SyntaxNode>().First(n => n.Span.Contains(span)); using (Logger.LogBlock(FunctionId.Refactoring_FullyQualify, cancellationToken)) { // Has to be a simple identifier or generic name. if (node == null || !CanFullyQualify(diagnostic, ref node)) { return; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var matchingTypes = await GetMatchingTypesAsync(document, semanticModel, node, cancellationToken).ConfigureAwait(false); var matchingNamespaces = await GetMatchingNamespacesAsync(project, semanticModel, node, cancellationToken).ConfigureAwait(false); if (matchingTypes.IsEmpty && matchingNamespaces.IsEmpty) { return; } var matchingTypeContainers = FilterAndSort(GetContainers(matchingTypes, semanticModel.Compilation)); var matchingNamespaceContainers = FilterAndSort(GetContainers(matchingNamespaces, semanticModel.Compilation)); var proposedContainers = matchingTypeContainers.Concat(matchingNamespaceContainers) .Distinct() .Take(MaxResults); var codeActions = CreateActions(document, node, semanticModel, proposedContainers).ToImmutableArray(); if (codeActions.Length > 1) { // Wrap the spell checking actions into a single top level suggestion // so as to not clutter the list. context.RegisterCodeFix(new GroupingCodeAction( string.Format(FeaturesResources.Fully_qualify_0, GetNodeName(document, node)), codeActions), context.Diagnostics); } else { context.RegisterFixes(codeActions, context.Diagnostics); } } } private IEnumerable<CodeAction> CreateActions( Document document, SyntaxNode node, SemanticModel semanticModel, IEnumerable<SymbolResult> proposedContainers) { foreach (var symbolResult in proposedContainers) { var container = symbolResult.Symbol; var containerName = container.ToMinimalDisplayString(semanticModel, node.SpanStart); var name = GetNodeName(document, node); // Actual member name might differ by case. string memberName; if (IgnoreCase) { var member = container.GetMembers(name).FirstOrDefault(); memberName = member != null ? member.Name : name; } else { memberName = name; } var codeAction = new MyCodeAction( $"{containerName}.{memberName}", c => ProcessNodeAsync(document, node, containerName, symbolResult.OriginalSymbol, c)); yield return codeAction; } } private static string GetNodeName(Document document, SyntaxNode node) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); syntaxFacts.GetNameAndArityOfSimpleName(node, out var name, out _); Contract.ThrowIfNull(name, "node isn't a SimpleNameSyntax? CanFullyQualify should have returned false."); return name; } private async Task<Document> ProcessNodeAsync(Document document, SyntaxNode node, string containerName, INamespaceOrTypeSymbol? originalSymbol, CancellationToken cancellationToken) { Contract.ThrowIfNull(originalSymbol, "Original symbol information missing. Haven't called GetContainers?"); var newRoot = await ReplaceNodeAsync(node, containerName, originalSymbol.IsType, cancellationToken).ConfigureAwait(false); return document.WithSyntaxRoot(newRoot); } private async Task<ImmutableArray<SymbolResult>> GetMatchingTypesAsync( Document document, SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var project = document.Project; var syntaxFacts = project.LanguageServices.GetRequiredService<ISyntaxFactsService>(); syntaxFacts.GetNameAndArityOfSimpleName(node, out var name, out var arity); var looksGeneric = syntaxFacts.LooksGeneric(node); var symbols = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync( project, SearchQuery.Create(name, IgnoreCase), SymbolFilter.Type, cancellationToken).ConfigureAwait(false); // also lookup type symbols with the "Attribute" suffix. var inAttributeContext = syntaxFacts.IsAttributeName(node); if (inAttributeContext) { var attributeSymbols = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync( project, SearchQuery.Create(name + "Attribute", IgnoreCase), SymbolFilter.Type, cancellationToken).ConfigureAwait(false); symbols = symbols.Concat(attributeSymbols); } var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var hideAdvancedMembers = options.GetOption(CompletionOptions.HideAdvancedMembers); var editorBrowserInfo = new EditorBrowsableInfo(semanticModel.Compilation); var validSymbols = symbols .OfType<INamedTypeSymbol>() .Where(s => IsValidNamedTypeSearchResult(semanticModel, arity, inAttributeContext, looksGeneric, s) && s.IsEditorBrowsable(hideAdvancedMembers, semanticModel.Compilation, editorBrowserInfo)) .ToImmutableArray(); // Check what the current node binds to. If it binds to any symbols, but with // the wrong arity, then we don't want to suggest fully qualifying to the same // type that we're already binding to. That won't address the WrongArity problem. var currentSymbolInfo = semanticModel.GetSymbolInfo(node, cancellationToken); if (currentSymbolInfo.CandidateReason == CandidateReason.WrongArity) { validSymbols = validSymbols.WhereAsArray( s => !currentSymbolInfo.CandidateSymbols.Contains(s)); } return validSymbols.SelectAsArray(s => new SymbolResult(s, weight: TypeWeight)); } private static bool IsValidNamedTypeSearchResult( SemanticModel semanticModel, int arity, bool inAttributeContext, bool looksGeneric, INamedTypeSymbol searchResult) { if (arity != 0 && searchResult.GetArity() != arity) { // If the user supplied type arguments, then the search result has to match the // number provided. return false; } if (looksGeneric && searchResult.TypeArguments.Length == 0) { return false; } if (!searchResult.IsAccessibleWithin(semanticModel.Compilation.Assembly)) { // Search result has to be accessible from our current location. return false; } if (inAttributeContext && !searchResult.IsAttribute()) { // If we need an attribute, we have to have found an attribute. return false; } if (!HasValidContainer(searchResult)) { // Named type we find must be in a namespace, or a non-generic type. return false; } return true; } private static bool HasValidContainer(ISymbol symbol) { var container = symbol.ContainingSymbol; return container is INamespaceSymbol || (container is INamedTypeSymbol parentType && !parentType.IsGenericType); } private async Task<ImmutableArray<SymbolResult>> GetMatchingNamespacesAsync( Project project, SemanticModel semanticModel, SyntaxNode simpleName, CancellationToken cancellationToken) { var syntaxFacts = project.LanguageServices.GetRequiredService<ISyntaxFactsService>(); if (syntaxFacts.IsAttributeName(simpleName)) { return ImmutableArray<SymbolResult>.Empty; } syntaxFacts.GetNameAndArityOfSimpleName(simpleName, out var name, out var arityUnused); if (cancellationToken.IsCancellationRequested) { return ImmutableArray<SymbolResult>.Empty; } var symbols = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync( project, SearchQuery.Create(name, IgnoreCase), SymbolFilter.Namespace, cancellationToken).ConfigureAwait(false); // There might be multiple namespaces that this name will resolve successfully in. // Some of them may be 'better' results than others. For example, say you have // Y.Z and Y exists in both X1 and X2 // We'll want to order them such that we prefer the namespace that will correctly // bind Z off of Y as well. string? rightName = null; var isAttributeName = false; if (syntaxFacts.IsLeftSideOfDot(simpleName)) { var rightSide = syntaxFacts.GetRightSideOfDot(simpleName.Parent); Contract.ThrowIfNull(rightSide); syntaxFacts.GetNameAndArityOfSimpleName(rightSide, out rightName, out arityUnused); isAttributeName = syntaxFacts.IsAttributeName(rightSide); } var namespaces = symbols .OfType<INamespaceSymbol>() .Where(n => !n.IsGlobalNamespace && HasAccessibleTypes(n, semanticModel, cancellationToken)) .Select(n => new SymbolResult(n, BindsWithoutErrors(n, rightName, isAttributeName) ? NamespaceWithNoErrorsWeight : NamespaceWithErrorsWeight)); return namespaces.ToImmutableArray(); } private bool BindsWithoutErrors(INamespaceSymbol ns, string? rightName, bool isAttributeName) { // If there was no name on the right, then this binds without any problems. if (rightName == null) { return true; } // Otherwise, see if the namespace we will bind this contains a member with the same // name as the name on the right. var types = ns.GetMembers(rightName); if (types.Any()) { return true; } if (!isAttributeName) { return false; } return BindsWithoutErrors(ns, rightName + "Attribute", isAttributeName: false); } private static bool HasAccessibleTypes(INamespaceSymbol @namespace, SemanticModel model, CancellationToken cancellationToken) => Enumerable.Any(@namespace.GetAllTypes(cancellationToken), t => t.IsAccessibleWithin(model.Compilation.Assembly)); private static IEnumerable<SymbolResult> GetContainers( ImmutableArray<SymbolResult> symbols, Compilation compilation) { foreach (var symbolResult in symbols) { var containingSymbol = symbolResult.Symbol.ContainingSymbol as INamespaceOrTypeSymbol; if (containingSymbol is INamespaceSymbol namespaceSymbol) { containingSymbol = compilation.GetCompilationNamespace(namespaceSymbol); } if (containingSymbol != null) { yield return symbolResult.WithSymbol(containingSymbol); } } } private static IEnumerable<SymbolResult> FilterAndSort(IEnumerable<SymbolResult> symbols) => symbols.Distinct() .Where(n => n.Symbol is INamedTypeSymbol || !((INamespaceSymbol)n.Symbol).IsGlobalNamespace) .Order(); private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, equivalenceKey: title) { } } private class GroupingCodeAction : CodeAction.CodeActionWithNestedActions { public GroupingCodeAction(string title, ImmutableArray<CodeAction> nestedActions) : base(title, nestedActions, isInlinable: true) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.Shared.Utilities.EditorBrowsableHelpers; namespace Microsoft.CodeAnalysis.CodeFixes.FullyQualify { internal abstract partial class AbstractFullyQualifyCodeFixProvider : CodeFixProvider { private const int MaxResults = 3; private const int NamespaceWithNoErrorsWeight = 0; private const int TypeWeight = 1; private const int NamespaceWithErrorsWeight = 2; protected AbstractFullyQualifyCodeFixProvider() { } public override FixAllProvider? GetFixAllProvider() { // Fix All is not supported by this code fix // https://github.com/dotnet/roslyn/issues/34465 return null; } protected abstract bool IgnoreCase { get; } protected abstract bool CanFullyQualify(Diagnostic diagnostic, ref SyntaxNode node); protected abstract Task<SyntaxNode> ReplaceNodeAsync(SyntaxNode node, string containerName, bool resultingSymbolIsType, CancellationToken cancellationToken); public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var span = context.Span; var diagnostics = context.Diagnostics; var cancellationToken = context.CancellationToken; var project = document.Project; var diagnostic = diagnostics.First(); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var node = root.FindToken(span.Start).GetAncestors<SyntaxNode>().First(n => n.Span.Contains(span)); using (Logger.LogBlock(FunctionId.Refactoring_FullyQualify, cancellationToken)) { // Has to be a simple identifier or generic name. if (node == null || !CanFullyQualify(diagnostic, ref node)) { return; } var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var matchingTypes = await GetMatchingTypesAsync(document, semanticModel, node, cancellationToken).ConfigureAwait(false); var matchingNamespaces = await GetMatchingNamespacesAsync(project, semanticModel, node, cancellationToken).ConfigureAwait(false); if (matchingTypes.IsEmpty && matchingNamespaces.IsEmpty) { return; } var matchingTypeContainers = FilterAndSort(GetContainers(matchingTypes, semanticModel.Compilation)); var matchingNamespaceContainers = FilterAndSort(GetContainers(matchingNamespaces, semanticModel.Compilation)); var proposedContainers = matchingTypeContainers.Concat(matchingNamespaceContainers) .Distinct() .Take(MaxResults); var codeActions = CreateActions(document, node, semanticModel, proposedContainers).ToImmutableArray(); if (codeActions.Length > 1) { // Wrap the spell checking actions into a single top level suggestion // so as to not clutter the list. context.RegisterCodeFix(new GroupingCodeAction( string.Format(FeaturesResources.Fully_qualify_0, GetNodeName(document, node)), codeActions), context.Diagnostics); } else { context.RegisterFixes(codeActions, context.Diagnostics); } } } private IEnumerable<CodeAction> CreateActions( Document document, SyntaxNode node, SemanticModel semanticModel, IEnumerable<SymbolResult> proposedContainers) { foreach (var symbolResult in proposedContainers) { var container = symbolResult.Symbol; var containerName = container.ToMinimalDisplayString(semanticModel, node.SpanStart); var name = GetNodeName(document, node); // Actual member name might differ by case. string memberName; if (IgnoreCase) { var member = container.GetMembers(name).FirstOrDefault(); memberName = member != null ? member.Name : name; } else { memberName = name; } var codeAction = new MyCodeAction( $"{containerName}.{memberName}", c => ProcessNodeAsync(document, node, containerName, symbolResult.OriginalSymbol, c)); yield return codeAction; } } private static string GetNodeName(Document document, SyntaxNode node) { var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); syntaxFacts.GetNameAndArityOfSimpleName(node, out var name, out _); Contract.ThrowIfNull(name, "node isn't a SimpleNameSyntax? CanFullyQualify should have returned false."); return name; } private async Task<Document> ProcessNodeAsync(Document document, SyntaxNode node, string containerName, INamespaceOrTypeSymbol? originalSymbol, CancellationToken cancellationToken) { Contract.ThrowIfNull(originalSymbol, "Original symbol information missing. Haven't called GetContainers?"); var newRoot = await ReplaceNodeAsync(node, containerName, originalSymbol.IsType, cancellationToken).ConfigureAwait(false); return document.WithSyntaxRoot(newRoot); } private async Task<ImmutableArray<SymbolResult>> GetMatchingTypesAsync( Document document, SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var project = document.Project; var syntaxFacts = project.LanguageServices.GetRequiredService<ISyntaxFactsService>(); syntaxFacts.GetNameAndArityOfSimpleName(node, out var name, out var arity); var looksGeneric = syntaxFacts.LooksGeneric(node); var symbols = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync( project, SearchQuery.Create(name, IgnoreCase), SymbolFilter.Type, cancellationToken).ConfigureAwait(false); // also lookup type symbols with the "Attribute" suffix. var inAttributeContext = syntaxFacts.IsAttributeName(node); if (inAttributeContext) { var attributeSymbols = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync( project, SearchQuery.Create(name + "Attribute", IgnoreCase), SymbolFilter.Type, cancellationToken).ConfigureAwait(false); symbols = symbols.Concat(attributeSymbols); } var options = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var hideAdvancedMembers = options.GetOption(CompletionOptions.HideAdvancedMembers); var editorBrowserInfo = new EditorBrowsableInfo(semanticModel.Compilation); var validSymbols = symbols .OfType<INamedTypeSymbol>() .Where(s => IsValidNamedTypeSearchResult(semanticModel, arity, inAttributeContext, looksGeneric, s) && s.IsEditorBrowsable(hideAdvancedMembers, semanticModel.Compilation, editorBrowserInfo)) .ToImmutableArray(); // Check what the current node binds to. If it binds to any symbols, but with // the wrong arity, then we don't want to suggest fully qualifying to the same // type that we're already binding to. That won't address the WrongArity problem. var currentSymbolInfo = semanticModel.GetSymbolInfo(node, cancellationToken); if (currentSymbolInfo.CandidateReason == CandidateReason.WrongArity) { validSymbols = validSymbols.WhereAsArray( s => !currentSymbolInfo.CandidateSymbols.Contains(s)); } return validSymbols.SelectAsArray(s => new SymbolResult(s, weight: TypeWeight)); } private static bool IsValidNamedTypeSearchResult( SemanticModel semanticModel, int arity, bool inAttributeContext, bool looksGeneric, INamedTypeSymbol searchResult) { if (arity != 0 && searchResult.GetArity() != arity) { // If the user supplied type arguments, then the search result has to match the // number provided. return false; } if (looksGeneric && searchResult.TypeArguments.Length == 0) { return false; } if (!searchResult.IsAccessibleWithin(semanticModel.Compilation.Assembly)) { // Search result has to be accessible from our current location. return false; } if (inAttributeContext && !searchResult.IsAttribute()) { // If we need an attribute, we have to have found an attribute. return false; } if (!HasValidContainer(searchResult)) { // Named type we find must be in a namespace, or a non-generic type. return false; } return true; } private static bool HasValidContainer(ISymbol symbol) { var container = symbol.ContainingSymbol; return container is INamespaceSymbol || (container is INamedTypeSymbol parentType && !parentType.IsGenericType); } private async Task<ImmutableArray<SymbolResult>> GetMatchingNamespacesAsync( Project project, SemanticModel semanticModel, SyntaxNode simpleName, CancellationToken cancellationToken) { var syntaxFacts = project.LanguageServices.GetRequiredService<ISyntaxFactsService>(); if (syntaxFacts.IsAttributeName(simpleName)) { return ImmutableArray<SymbolResult>.Empty; } syntaxFacts.GetNameAndArityOfSimpleName(simpleName, out var name, out var arityUnused); if (cancellationToken.IsCancellationRequested) { return ImmutableArray<SymbolResult>.Empty; } var symbols = await DeclarationFinder.FindAllDeclarationsWithNormalQueryAsync( project, SearchQuery.Create(name, IgnoreCase), SymbolFilter.Namespace, cancellationToken).ConfigureAwait(false); // There might be multiple namespaces that this name will resolve successfully in. // Some of them may be 'better' results than others. For example, say you have // Y.Z and Y exists in both X1 and X2 // We'll want to order them such that we prefer the namespace that will correctly // bind Z off of Y as well. string? rightName = null; var isAttributeName = false; if (syntaxFacts.IsLeftSideOfDot(simpleName)) { var rightSide = syntaxFacts.GetRightSideOfDot(simpleName.Parent); Contract.ThrowIfNull(rightSide); syntaxFacts.GetNameAndArityOfSimpleName(rightSide, out rightName, out arityUnused); isAttributeName = syntaxFacts.IsAttributeName(rightSide); } var namespaces = symbols .OfType<INamespaceSymbol>() .Where(n => !n.IsGlobalNamespace && HasAccessibleTypes(n, semanticModel, cancellationToken)) .Select(n => new SymbolResult(n, BindsWithoutErrors(n, rightName, isAttributeName) ? NamespaceWithNoErrorsWeight : NamespaceWithErrorsWeight)); return namespaces.ToImmutableArray(); } private bool BindsWithoutErrors(INamespaceSymbol ns, string? rightName, bool isAttributeName) { // If there was no name on the right, then this binds without any problems. if (rightName == null) { return true; } // Otherwise, see if the namespace we will bind this contains a member with the same // name as the name on the right. var types = ns.GetMembers(rightName); if (types.Any()) { return true; } if (!isAttributeName) { return false; } return BindsWithoutErrors(ns, rightName + "Attribute", isAttributeName: false); } private static bool HasAccessibleTypes(INamespaceSymbol @namespace, SemanticModel model, CancellationToken cancellationToken) => Enumerable.Any(@namespace.GetAllTypes(cancellationToken), t => t.IsAccessibleWithin(model.Compilation.Assembly)); private static IEnumerable<SymbolResult> GetContainers( ImmutableArray<SymbolResult> symbols, Compilation compilation) { foreach (var symbolResult in symbols) { var containingSymbol = symbolResult.Symbol.ContainingSymbol as INamespaceOrTypeSymbol; if (containingSymbol is INamespaceSymbol namespaceSymbol) { containingSymbol = compilation.GetCompilationNamespace(namespaceSymbol); } if (containingSymbol != null) { yield return symbolResult.WithSymbol(containingSymbol); } } } private static IEnumerable<SymbolResult> FilterAndSort(IEnumerable<SymbolResult> symbols) => symbols.Distinct() .Where(n => n.Symbol is INamedTypeSymbol || !((INamespaceSymbol)n.Symbol).IsGlobalNamespace) .Order(); private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, equivalenceKey: title) { } } private class GroupingCodeAction : CodeAction.CodeActionWithNestedActions { public GroupingCodeAction(string title, ImmutableArray<CodeAction> nestedActions) : base(title, nestedActions, isInlinable: true) { } } } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/EditorFeatures/CSharpTest/SignatureHelp/AbstractCSharpSignatureHelpProviderTests.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.CSharp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public abstract class AbstractCSharpSignatureHelpProviderTests : AbstractSignatureHelpProviderTests<CSharpTestWorkspaceFixture> { protected override ParseOptions CreateExperimentalParseOptions() { return new CSharpParseOptions().WithFeatures(new Dictionary<string, string>()); // no experimental features to enable } } }
// Licensed to the .NET Foundation under one or more 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.CSharp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public abstract class AbstractCSharpSignatureHelpProviderTests : AbstractSignatureHelpProviderTests<CSharpTestWorkspaceFixture> { protected override ParseOptions CreateExperimentalParseOptions() { return new CSharpParseOptions().WithFeatures(new Dictionary<string, string>()); // no experimental features to enable } } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Analyzers/Core/Analyzers/DiagnosticCustomTags.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.Diagnostics; using Microsoft.CodeAnalysis.CodeStyle; namespace Microsoft.CodeAnalysis.Diagnostics { internal static class DiagnosticCustomTags { private static readonly string s_enforceOnBuildNeverTag = EnforceOnBuild.Never.ToCustomTag(); private static readonly string[] s_microsoftCustomTags = new string[] { WellKnownDiagnosticTags.Telemetry }; private static readonly string[] s_editAndContinueCustomTags = new string[] { WellKnownDiagnosticTags.EditAndContinue, WellKnownDiagnosticTags.Telemetry, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag }; private static readonly string[] s_unnecessaryCustomTags = new string[] { WellKnownDiagnosticTags.Unnecessary, WellKnownDiagnosticTags.Telemetry }; private static readonly string[] s_notConfigurableCustomTags = new string[] { WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag, WellKnownDiagnosticTags.Telemetry }; private static readonly string[] s_unnecessaryAndNotConfigurableCustomTags = new string[] { WellKnownDiagnosticTags.Unnecessary, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag, WellKnownDiagnosticTags.Telemetry }; public static string[] Microsoft { get { Assert(s_microsoftCustomTags, WellKnownDiagnosticTags.Telemetry); return s_microsoftCustomTags; } } public static string[] EditAndContinue { get { Assert(s_editAndContinueCustomTags, WellKnownDiagnosticTags.EditAndContinue, WellKnownDiagnosticTags.Telemetry, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag); return s_editAndContinueCustomTags; } } public static string[] Unnecessary { get { Assert(s_unnecessaryCustomTags, WellKnownDiagnosticTags.Unnecessary, WellKnownDiagnosticTags.Telemetry); return s_unnecessaryCustomTags; } } public static string[] NotConfigurable { get { Assert(s_notConfigurableCustomTags, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag, WellKnownDiagnosticTags.Telemetry); return s_notConfigurableCustomTags; } } public static string[] UnnecessaryAndNotConfigurable { get { Assert(s_unnecessaryAndNotConfigurableCustomTags, WellKnownDiagnosticTags.Unnecessary, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag, WellKnownDiagnosticTags.Telemetry); return s_unnecessaryAndNotConfigurableCustomTags; } } [Conditional("DEBUG")] private static void Assert(string[] customTags, params string[] tags) { Debug.Assert(customTags.Length == tags.Length); for (var i = 0; i < tags.Length; i++) { Debug.Assert(customTags[i] == tags[i]); } } internal static string[] Create(bool isUnnecessary, bool isConfigurable, EnforceOnBuild enforceOnBuild) { Debug.Assert(isConfigurable || enforceOnBuild == EnforceOnBuild.Never); var customTagsBuilder = ImmutableArray.CreateBuilder<string>(); customTagsBuilder.AddRange(Microsoft); customTagsBuilder.Add(enforceOnBuild.ToCustomTag()); if (!isConfigurable) { customTagsBuilder.Add(WellKnownDiagnosticTags.NotConfigurable); } if (isUnnecessary) { customTagsBuilder.Add(WellKnownDiagnosticTags.Unnecessary); } return customTagsBuilder.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. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CodeStyle; namespace Microsoft.CodeAnalysis.Diagnostics { internal static class DiagnosticCustomTags { private static readonly string s_enforceOnBuildNeverTag = EnforceOnBuild.Never.ToCustomTag(); private static readonly string[] s_microsoftCustomTags = new string[] { WellKnownDiagnosticTags.Telemetry }; private static readonly string[] s_editAndContinueCustomTags = new string[] { WellKnownDiagnosticTags.EditAndContinue, WellKnownDiagnosticTags.Telemetry, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag }; private static readonly string[] s_unnecessaryCustomTags = new string[] { WellKnownDiagnosticTags.Unnecessary, WellKnownDiagnosticTags.Telemetry }; private static readonly string[] s_notConfigurableCustomTags = new string[] { WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag, WellKnownDiagnosticTags.Telemetry }; private static readonly string[] s_unnecessaryAndNotConfigurableCustomTags = new string[] { WellKnownDiagnosticTags.Unnecessary, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag, WellKnownDiagnosticTags.Telemetry }; public static string[] Microsoft { get { Assert(s_microsoftCustomTags, WellKnownDiagnosticTags.Telemetry); return s_microsoftCustomTags; } } public static string[] EditAndContinue { get { Assert(s_editAndContinueCustomTags, WellKnownDiagnosticTags.EditAndContinue, WellKnownDiagnosticTags.Telemetry, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag); return s_editAndContinueCustomTags; } } public static string[] Unnecessary { get { Assert(s_unnecessaryCustomTags, WellKnownDiagnosticTags.Unnecessary, WellKnownDiagnosticTags.Telemetry); return s_unnecessaryCustomTags; } } public static string[] NotConfigurable { get { Assert(s_notConfigurableCustomTags, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag, WellKnownDiagnosticTags.Telemetry); return s_notConfigurableCustomTags; } } public static string[] UnnecessaryAndNotConfigurable { get { Assert(s_unnecessaryAndNotConfigurableCustomTags, WellKnownDiagnosticTags.Unnecessary, WellKnownDiagnosticTags.NotConfigurable, s_enforceOnBuildNeverTag, WellKnownDiagnosticTags.Telemetry); return s_unnecessaryAndNotConfigurableCustomTags; } } [Conditional("DEBUG")] private static void Assert(string[] customTags, params string[] tags) { Debug.Assert(customTags.Length == tags.Length); for (var i = 0; i < tags.Length; i++) { Debug.Assert(customTags[i] == tags[i]); } } internal static string[] Create(bool isUnnecessary, bool isConfigurable, EnforceOnBuild enforceOnBuild) { Debug.Assert(isConfigurable || enforceOnBuild == EnforceOnBuild.Never); var customTagsBuilder = ImmutableArray.CreateBuilder<string>(); customTagsBuilder.AddRange(Microsoft); customTagsBuilder.Add(enforceOnBuild.ToCustomTag()); if (!isConfigurable) { customTagsBuilder.Add(WellKnownDiagnosticTags.NotConfigurable); } if (isUnnecessary) { customTagsBuilder.Add(WellKnownDiagnosticTags.Unnecessary); } return customTagsBuilder.ToArray(); } } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/VisualStudio/IntegrationTest/TestUtilities/Common/ErrorListItem.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 Roslyn.Utilities; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Common { [Serializable] public class ErrorListItem : IEquatable<ErrorListItem> { public string Severity { get; set; } public string Description { get; set; } public string Project { get; set; } public string FileName { get; set; } public int Line { get; set; } public int Column { get; set; } public ErrorListItem(string severity, string description, string project, string fileName, int line, int column) { Severity = severity; Description = description; Project = project; FileName = fileName; Line = line; Column = column; } public bool Equals(ErrorListItem? other) => other != null && Comparison.AreStringValuesEqual(Severity, other.Severity) && Comparison.AreStringValuesEqual(Description, other.Description) && Comparison.AreStringValuesEqual(Project, other.Project) && Comparison.AreStringValuesEqual(FileName, other.FileName) && Line == other.Line && Column == other.Column; public override bool Equals(object? obj) => Equals(obj as ErrorListItem); public override int GetHashCode() => Hash.Combine(Severity, Hash.Combine(Description, Hash.Combine(Project, Hash.Combine(FileName, Hash.Combine(Line, Hash.Combine(Column, 0)))))); public override string ToString() => $"Severity:{Severity} Description:{Description} Project:{Project} File:{FileName} Line:{Line} Column:{Column}"; } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Common { [Serializable] public class ErrorListItem : IEquatable<ErrorListItem> { public string Severity { get; set; } public string Description { get; set; } public string Project { get; set; } public string FileName { get; set; } public int Line { get; set; } public int Column { get; set; } public ErrorListItem(string severity, string description, string project, string fileName, int line, int column) { Severity = severity; Description = description; Project = project; FileName = fileName; Line = line; Column = column; } public bool Equals(ErrorListItem? other) => other != null && Comparison.AreStringValuesEqual(Severity, other.Severity) && Comparison.AreStringValuesEqual(Description, other.Description) && Comparison.AreStringValuesEqual(Project, other.Project) && Comparison.AreStringValuesEqual(FileName, other.FileName) && Line == other.Line && Column == other.Column; public override bool Equals(object? obj) => Equals(obj as ErrorListItem); public override int GetHashCode() => Hash.Combine(Severity, Hash.Combine(Description, Hash.Combine(Project, Hash.Combine(FileName, Hash.Combine(Line, Hash.Combine(Column, 0)))))); public override string ToString() => $"Severity:{Severity} Description:{Description} Project:{Project} File:{FileName} Line:{Line} Column:{Column}"; } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Workspaces/Core/Portable/FindSymbols/FindReferences/Finders/NamespaceSymbolReferenceFinder.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.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class NamespaceSymbolReferenceFinder : AbstractReferenceFinder<INamespaceSymbol> { private static readonly SymbolDisplayFormat s_globalNamespaceFormat = new(SymbolDisplayGlobalNamespaceStyle.Included); protected override bool CanFind(INamespaceSymbol symbol) => true; protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( INamespaceSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, GetNamespaceIdentifierName(symbol)).ConfigureAwait(false); var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithGlobalAttributes.Concat(documentsWithName); } private static string GetNamespaceIdentifierName(INamespaceSymbol symbol) { return symbol.IsGlobalNamespace ? symbol.ToDisplayString(s_globalNamespaceFormat) : symbol.Name; } protected override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( INamespaceSymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var identifierName = GetNamespaceIdentifierName(symbol); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var tokens = await GetIdentifierOrGlobalNamespaceTokensWithTextAsync( document, semanticModel, identifierName, cancellationToken).ConfigureAwait(false); var nonAliasReferences = await FindReferencesInTokensAsync( symbol, document, semanticModel, tokens, t => syntaxFacts.TextMatch(t.ValueText, identifierName), cancellationToken).ConfigureAwait(false); var aliasReferences = await FindAliasReferencesAsync(nonAliasReferences, symbol, document, semanticModel, cancellationToken).ConfigureAwait(false); var suppressionReferences = await FindReferencesInDocumentInsideGlobalSuppressionsAsync(document, semanticModel, symbol, cancellationToken).ConfigureAwait(false); return nonAliasReferences.Concat(aliasReferences, suppressionReferences); } } }
// Licensed to the .NET Foundation under one or more 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.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.FindSymbols.Finders { internal class NamespaceSymbolReferenceFinder : AbstractReferenceFinder<INamespaceSymbol> { private static readonly SymbolDisplayFormat s_globalNamespaceFormat = new(SymbolDisplayGlobalNamespaceStyle.Included); protected override bool CanFind(INamespaceSymbol symbol) => true; protected override async Task<ImmutableArray<Document>> DetermineDocumentsToSearchAsync( INamespaceSymbol symbol, Project project, IImmutableSet<Document>? documents, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var documentsWithName = await FindDocumentsAsync(project, documents, cancellationToken, GetNamespaceIdentifierName(symbol)).ConfigureAwait(false); var documentsWithGlobalAttributes = await FindDocumentsWithGlobalAttributesAsync(project, documents, cancellationToken).ConfigureAwait(false); return documentsWithGlobalAttributes.Concat(documentsWithName); } private static string GetNamespaceIdentifierName(INamespaceSymbol symbol) { return symbol.IsGlobalNamespace ? symbol.ToDisplayString(s_globalNamespaceFormat) : symbol.Name; } protected override async ValueTask<ImmutableArray<FinderLocation>> FindReferencesInDocumentAsync( INamespaceSymbol symbol, Document document, SemanticModel semanticModel, FindReferencesSearchOptions options, CancellationToken cancellationToken) { var identifierName = GetNamespaceIdentifierName(symbol); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var tokens = await GetIdentifierOrGlobalNamespaceTokensWithTextAsync( document, semanticModel, identifierName, cancellationToken).ConfigureAwait(false); var nonAliasReferences = await FindReferencesInTokensAsync( symbol, document, semanticModel, tokens, t => syntaxFacts.TextMatch(t.ValueText, identifierName), cancellationToken).ConfigureAwait(false); var aliasReferences = await FindAliasReferencesAsync(nonAliasReferences, symbol, document, semanticModel, cancellationToken).ConfigureAwait(false); var suppressionReferences = await FindReferencesInDocumentInsideGlobalSuppressionsAsync(document, semanticModel, symbol, cancellationToken).ConfigureAwait(false); return nonAliasReferences.Concat(aliasReferences, suppressionReferences); } } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Features/Core/Portable/Wrapping/AbstractWrappingCodeRefactoringProvider.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.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; namespace Microsoft.CodeAnalysis.Wrapping { /// <summary> /// Base type for the C# and VB wrapping refactorings. The only responsibility of this type is /// to walk up the tree at the position the user is at, seeing if any node above the user can be /// wrapped by any provided <see cref="ISyntaxWrapper"/>s. /// /// Once we get any wrapping actions, we stop looking further. This keeps the refactorings /// scoped as closely as possible to where the user is, as well as preventing overloading of the /// lightbulb with too many actions. /// </summary> internal abstract class AbstractWrappingCodeRefactoringProvider : CodeRefactoringProvider { private readonly ImmutableArray<ISyntaxWrapper> _wrappers; protected AbstractWrappingCodeRefactoringProvider( ImmutableArray<ISyntaxWrapper> wrappers) { _wrappers = wrappers; } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; if (!span.IsEmpty) { return; } var position = span.Start; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position); foreach (var node in token.Parent.AncestorsAndSelf()) { // Make sure we don't have any syntax errors here. Don't want to format if we don't // really understand what's going on. if (node.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) { return; } // Check if any wrapper can handle this node. If so, then we're done, otherwise // keep walking up. foreach (var wrapper in _wrappers) { cancellationToken.ThrowIfCancellationRequested(); var computer = await wrapper.TryCreateComputerAsync( document, position, node, cancellationToken).ConfigureAwait(false); if (computer == null) { continue; } var actions = await computer.GetTopLevelCodeActionsAsync().ConfigureAwait(false); if (actions.IsDefaultOrEmpty) { continue; } context.RegisterRefactorings(actions); return; } } } } }
// Licensed to the .NET Foundation under one or more 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.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; namespace Microsoft.CodeAnalysis.Wrapping { /// <summary> /// Base type for the C# and VB wrapping refactorings. The only responsibility of this type is /// to walk up the tree at the position the user is at, seeing if any node above the user can be /// wrapped by any provided <see cref="ISyntaxWrapper"/>s. /// /// Once we get any wrapping actions, we stop looking further. This keeps the refactorings /// scoped as closely as possible to where the user is, as well as preventing overloading of the /// lightbulb with too many actions. /// </summary> internal abstract class AbstractWrappingCodeRefactoringProvider : CodeRefactoringProvider { private readonly ImmutableArray<ISyntaxWrapper> _wrappers; protected AbstractWrappingCodeRefactoringProvider( ImmutableArray<ISyntaxWrapper> wrappers) { _wrappers = wrappers; } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; if (!span.IsEmpty) { return; } var position = span.Start; var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position); foreach (var node in token.Parent.AncestorsAndSelf()) { // Make sure we don't have any syntax errors here. Don't want to format if we don't // really understand what's going on. if (node.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) { return; } // Check if any wrapper can handle this node. If so, then we're done, otherwise // keep walking up. foreach (var wrapper in _wrappers) { cancellationToken.ThrowIfCancellationRequested(); var computer = await wrapper.TryCreateComputerAsync( document, position, node, cancellationToken).ConfigureAwait(false); if (computer == null) { continue; } var actions = await computer.GetTopLevelCodeActionsAsync().ConfigureAwait(false); if (actions.IsDefaultOrEmpty) { continue; } context.RegisterRefactorings(actions); return; } } } } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Workspaces/CSharp/Portable/CodeGeneration/CSharpCodeGenerationServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { [ExportLanguageServiceFactory(typeof(ICodeGenerationService), LanguageNames.CSharp), Shared] internal partial class CSharpCodeGenerationServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCodeGenerationServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices provider) => new CSharpCodeGenerationService(provider); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { [ExportLanguageServiceFactory(typeof(ICodeGenerationService), LanguageNames.CSharp), Shared] internal partial class CSharpCodeGenerationServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpCodeGenerationServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices provider) => new CSharpCodeGenerationService(provider); } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Compilers/CSharp/Test/Semantic/FlowAnalysis/RegionAnalysisTests.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.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// Tests for the region analysis APIs. /// </summary> /// <remarks> /// Please add your tests to other files if possible: /// * FlowDiagnosticTests.cs - all tests on Diagnostics /// * IterationJumpYieldStatementTests.cs - while, do, for, foreach, break, continue, goto, iterator (yield break, yield return) /// * TryLockUsingStatementTests.cs - try-catch-finally, lock, &amp; using statement /// * PatternsVsRegions.cs - region analysis tests for pattern matching /// </remarks> public partial class RegionAnalysisTests : FlowTestBase { #region "Expressions" [WorkItem(545047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545047")] [Fact] public void DataFlowsInAndNullable_Field() { // WARNING: if this test is edited, the test with the // test with the same name in VB must be modified too var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } static void Main(string[] args) { int? i = 1; S s = new S(1); /*<bind>*/ Console.WriteLine(i.Value); Console.WriteLine(s.F); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void DataFlowsOutAndStructField() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } static void Main(string[] args) { S s = new S(1); /*<bind>*/ s.F = 1; /*</bind>*/ var x = s.F; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, s, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void DataFlowsInAndNullable_Property() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } public int P { get; set; } static void Main(string[] args) { int? i = 1; S s = new S(1); /*<bind>*/ Console.WriteLine(i.Value); Console.WriteLine(s.P); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [WorkItem(538238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538238")] [Fact] public void TestDataFlowsIn03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main(string[] args) { int x = 1; int y = 2; int z = /*<bind>*/x + y/*</bind>*/; } } "); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestDataFlowForValueTypes() { // WARNING: test matches the same test in VB (TestDataFlowForValueTypes) // Keep the two tests in sync! var analysis = CompileAndAnalyzeDataFlowStatements(@" class Tst { public static void Main() { S0 a; S1 b; S2 c; S3 d; E0 e; E1 f; /*<bind>*/ Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(c); Console.WriteLine(d); Console.WriteLine(e); Console.WriteLine(f); /*</bind>*/ } } struct S0 { } struct S1 { public S0 s0; } struct S2 { public S0 s0; public int s1; } struct S3 { public S2 s; public object s1; } enum E0 { } enum E1 { V1 } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("a, b, c, d, e, f", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("a, b, c, d, e, f", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(538997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538997")] [Fact] public void TestDataFlowsIn04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; class Program { static void Main() { string s = ""; Func<string> f = /*<bind>*/s/*</bind>*/.ToString; } } "); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestDataFlowsOutExpression01() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public void F(int x) { int a = 1, y; int tmp = x + /*<bind>*/ (y = x = 2) /*</bind>*/ + (a = 2); int c = a + 4 + x + y; } }"); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(540171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540171")] [Fact] public void TestIncrement() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/i++/*</bind>*/; M(i); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace1() { var results = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/ System.Console /*</bind>*/ .WriteLine(i); } } "); Assert.False(results.Succeeded); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace3() { var results = CompileAndAnalyzeDataFlowExpression(@" public class A { public class B { public static void M() { } } } class C { static void M(int i) { /*<bind>*/ A.B /*</bind>*/ .M(i); } } "); Assert.False(results.Succeeded); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace4() { var results = CompileAndAnalyzeDataFlowExpression(@" public class A { public class B { public static void M() { } } } class C { static void M(int i) { /*<bind>*/ A /*</bind>*/ .B.M(i); } } "); Assert.False(results.Succeeded); } [WorkItem(540183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540183")] [Fact] public void DataFlowsOutIncrement01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/i++/*</bind>*/; M(i); } } "); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [WorkItem(6359, "DevDiv_Projects/Roslyn")] [Fact] public void DataFlowsOutPreDecrement01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Test { string method(string s, int i) { string[] myvar = new string[i]; myvar[0] = s; /*<bind>*/myvar[--i] = s + i.ToString()/*</bind>*/; return myvar[i]; } }"); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, s, i, myvar", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, s, i, myvar", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void TestBranchOfTernaryOperator() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x ? /*<bind>*/ x /*</bind>*/ : true; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(540832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540832")] [Fact] public void TestAssignmentExpressionAsBranchOfTernaryOperator() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x; int y = true ? /*<bind>*/ x = 1 /*</bind>*/ : x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestAlwaysAssignedWithTernaryOperator() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a, b, x = 100; /*<bind>*/ int c = true ? a = 1 : b = 2; /*</bind>*/ } }"); Assert.Equal("a, c", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, x, c", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i; i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned05() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) && (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned06() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ a && (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned07() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) && !a /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned08() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) || (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned09() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ a || (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned10() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) || !a /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned11() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ (b = a) ?? (b = null) /*</bind>*/ ; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned12() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ a ?? (b = null) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned13() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ (b = a) ?? null /*</bind>*/ ; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned14() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b, c, d, e, f; bool c = (b = a) ? (c = a) : (d = a) ? (e = a) : /*<bind>*/ (f = a) /*</bind>*/; } }"); Assert.Equal("f", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a, b, d", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b, d, f", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned15() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b, c, d, e, f; bool c = (b = a) ? (c = a) : /*<bind>*/ (d = a) ? (e = a) : (f = a) /*</bind>*/; } }"); Assert.Equal("d", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b, d", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned16() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = B(out a) && B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned17() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = /*<bind>*/B(out a) && B(out b)/*</bind>*/; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned18() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = B(out a) || B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned19() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = /*<bind>*/B(out a) || B(out b)/*</bind>*/; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned22() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; if (/*<bind>*/B(out a)/*</bind>*/) a = true; else b = true; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssignedAndWrittenInside() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestWrittenInside03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i; i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite01() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int x = 3; /*<bind>*/x/*</bind>*/ = 3; } }"); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite02() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int x = 3; /*<bind>*/x/*</bind>*/ += 3; } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void M(out int x) { x = 1; } public static void Main(string[] args) { int x = 3; M(out /*<bind>*/x/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void M(ref int x) { x = 1; } public static void Main(string[] args) { int x = 3; M(ref /*<bind>*/x/*</bind>*/); } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAssignmentExpressionSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x = ( /*<bind>*/ x = 1 /*</bind>*/ ) + x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestSingleVariableSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x | /*<bind>*/ x /*</bind>*/ ; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestParenthesizedAssignmentExpressionSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x | /*<bind>*/ (x = x) /*</bind>*/ | x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestRefArgumentSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x = 0; Goo(ref /*<bind>*/ x /*</bind>*/ ); System.Console.WriteLine(x); } static void Goo(ref int x) { } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(540066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540066")] [Fact] public void AnalysisOfBadRef() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { /*<bind>*/Main(ref 1)/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned20NullCoalescing() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static object B(out object b) { b = null; return b; } public static void Main(string[] args) { object a, b; object c = B(out a) ?? B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(528662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528662")] [Fact] public void TestNullCoalescingWithConstNullLeft() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" struct STest { public static string SM() { const string s = null; var ss = ""Q""; var ret = /*<bind>*/( s ?? (ss = ""C""))/*</bind>*/ + ss; return ret; } }"); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("ss", GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Equal("s", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Equal("ss", GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(528662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528662")] [Fact] public void TestNullCoalescingWithConstNotNullLeft() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class Test { public static string SM() { const string s = ""Not Null""; var ss = ""QC""; var ret = /*<bind>*/ s ?? ss /*</bind>*/ + ""\r\n""; return ret; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(8935, "DevDiv_Projects/Roslyn")] [Fact] public void TestDefaultOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class Test<T> { public T GetT() { return /*<bind>*/ default(T) /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestTypeOfOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class Test<T> { public short GetT(T t) { if (/*<bind>*/ typeof(T) == typeof(int) /*</bind>*/) return 123; return 456; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestIsOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; struct Test<T> { public string GetT(T t) { if /*<bind>*/(t is string)/*</bind>*/ return ""SSS""; return null; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("t", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestAsOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; struct Test<T> { public string GetT(T t) { string ret = null; if (t is string) ret = /*<bind>*/t as string/*</bind>*/; return ret; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("t", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t, ret", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t, ret", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(4028, "DevDiv_Projects/Roslyn")] [Fact] public void TestArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int y = 1; int[,] x = { { /*<bind>*/ y /*</bind>*/ } }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestImplicitStackAllocArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int z = 1; int y = 1; var x = stackalloc[] { /*<bind>*/ y /*</bind>*/ , z++ }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("z, y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestStackAllocArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int z = 1; int y = 1; var x = stackalloc int[] { /*<bind>*/ y /*</bind>*/ , z++ }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("z, y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(539286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539286")] [Fact] public void TestAnalysisInFieldInitializers() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static void Main() { Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; f(1); } } "); var results2 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; static void Main() { int r = f(1); } } "); Assert.Equal(GetSymbolNamesJoined(results1.AlwaysAssigned), GetSymbolNamesJoined(results2.AlwaysAssigned)); Assert.Equal(GetSymbolNamesJoined(results1.Captured), GetSymbolNamesJoined(results2.Captured)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedInside), GetSymbolNamesJoined(results2.CapturedInside)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedOutside), GetSymbolNamesJoined(results2.CapturedOutside)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsIn), GetSymbolNamesJoined(results2.DataFlowsIn)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsOut), GetSymbolNamesJoined(results2.DataFlowsOut)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results2.DefinitelyAssignedOnEntry)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results2.DefinitelyAssignedOnExit)); Assert.Equal(GetSymbolNamesJoined(results1.ReadInside), GetSymbolNamesJoined(results2.ReadInside)); Assert.Equal(GetSymbolNamesJoined(results1.ReadOutside), string.Join(", ", new string[] { "f" }.Concat((results2.ReadOutside).Select(symbol => symbol.Name)).OrderBy(name => name))); Assert.Equal(GetSymbolNamesJoined(results1.WrittenInside), GetSymbolNamesJoined(results2.WrittenInside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenOutside), string.Join(", ", new string[] { "f" }.Concat((results2.WrittenOutside).Select(symbol => symbol.Name)).OrderBy(name => name))); } [WorkItem(539286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539286")] [Fact] public void TestAnalysisInSimpleFieldInitializers() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { int x = 1; int y = 1; int z = /*<bind>*/1 + (x=2) + p + y/*</bind>*/; } "); var results2 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { int x = 1; int y = 1; static void Main() { /*<bind>*/1 + (x=2) + p + y/*</bind>*/; } } "); // NOTE: 'f' should not be reported in results1.AlwaysAssigned, this issue will be addressed separately Assert.Equal(GetSymbolNamesJoined(results1.AlwaysAssigned), GetSymbolNamesJoined(results2.AlwaysAssigned)); Assert.Equal(GetSymbolNamesJoined(results1.Captured), GetSymbolNamesJoined(results2.Captured)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedInside), GetSymbolNamesJoined(results2.CapturedInside)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedOutside), GetSymbolNamesJoined(results2.CapturedOutside)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsIn), GetSymbolNamesJoined(results2.DataFlowsIn)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsOut), GetSymbolNamesJoined(results2.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results2.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results2.DefinitelyAssignedOnExit)); Assert.Equal(GetSymbolNamesJoined(results1.ReadInside), GetSymbolNamesJoined(results2.ReadInside)); Assert.Equal(GetSymbolNamesJoined(results1.ReadOutside), GetSymbolNamesJoined(results2.ReadOutside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenInside), GetSymbolNamesJoined(results2.WrittenInside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenOutside), GetSymbolNamesJoined(results2.WrittenOutside)); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void ConstantFieldInitializerExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { const int myLength = /*<bind>*/5/*</bind>*/; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void ConstantFieldInitializerExpression2() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { // NOTE: illegal, but still a region we should handle. const bool myLength = true || ((Func<int, int>)(x => { int y = x; return /*<bind>*/y/*</bind>*/; }))(1) == 2; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("System.Int32 y", dataFlows.DataFlowsIn.Single().ToTestDisplayString()); Assert.Equal("System.Int32 y", dataFlows.ReadInside.Single().ToTestDisplayString()); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void FieldInitializerExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { bool myLength = true || ((Func<int, int>)(x => { int y = x; return /*<bind>*/y/*</bind>*/; }))(1) == 2; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("System.Int32 y", dataFlows.DataFlowsIn.Single().ToTestDisplayString()); Assert.Equal("System.Int32 y", dataFlows.ReadInside.Single().ToTestDisplayString()); } [WorkItem(542454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542454")] [Fact] public void IdentifierNameInObjectCreationExpr() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class myClass { static int Main() { myClass oc = new /*<bind>*/myClass/*</bind>*/(); return 0; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(542463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542463")] [Fact] public void MethodGroupInDelegateCreation() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class C { void Method() { System.Action a = new System.Action(/*<bind>*/Method/*</bind>*/); } } "); Assert.Equal("this", dataFlows.ReadInside.Single().Name); } [WorkItem(542771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542771")] [Fact] public void BindInCaseLabel() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class TestShapes { static void Main() { color s = color.blue; switch (s) { case true ? /*<bind>*/ color.blue /*</bind>*/ : color.blue: break; default: goto default; } } } enum color { blue, green }"); var tmp = dataFlows.VariablesDeclared; // ensure no exception thrown Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(542915, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542915")] [Fact] public void BindLiteralExprInEnumDecl() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" enum Number { Zero = /*<bind>*/0/*</bind>*/ } "); Assert.True(dataFlows.Succeeded); Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(542944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542944")] [Fact] public void AssignToConst() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main(string[] args) { const string a = null; /*<bind>*/a = null;/*</bind>*/ } } "); Assert.Equal("a", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfUnassignedStructLocal() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { int x; int* px = /*<bind>*/&x/*</bind>*/; } } "); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfAssignedStructLocal() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { int x = 1; int* px = /*<bind>*/&x/*</bind>*/; } } "); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfUnassignedStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfAssignedStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; s.x = 2; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("s", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("s, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestAddressOfAssignedStructField2() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; } class Program { static void Main() { S s; s.x = 2; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); // Really ??? Assert.Equal("s", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("s", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("s, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } // Make sure that assignment is consistent with address-of. [Fact] public void TestAssignToStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; int x = /*<bind>*/s.x = 1/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact, WorkItem(544314, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544314")] public void TestOmittedLambdaPointerTypeParameter() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; unsafe public class Test { public delegate int D(int* p); public static void Main() { int i = 10; int* p = &i; D d = /*<bind>*/delegate { return *p;}/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("p", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("p", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("p", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i, p", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("i, p", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("p", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i, p, d", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = /*<bind>*/ new MemberInitializerTest() { x = 1, y = 2 } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_LocalAccessed() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { int x = 0, y = 0; var i = /*<bind>*/ new MemberInitializerTest() { x = x, y = y } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, y, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_InvalidAccess() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = /*<bind>*/ new MemberInitializerTest() { x = x, y = y } /*</bind>*/; int x = 0, y = 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i, x, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_LocalAccessed_InitializerExpressionSyntax() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { int x = 0, y = 0; var i = new MemberInitializerTest() /*<bind>*/ { x = x, y = y } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, y, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_NestedObjectInitializer() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class Goo { public int z; } public class MemberInitializerTest { public int x; public Goo y { get; set; } public static void Main() { int x = 0, z = 0; var i = new MemberInitializerTest() { x = x, y = /*<bind>*/ { z = z } /*</bind>*/ }; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("z", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("z", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, z, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_VariableCaptured() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class Goo { public delegate int D(); public D z; } public class MemberInitializerTest { public int x; public Goo y { get; set; } public static void Main() { int x = 0, z = 0; var i = new MemberInitializerTest() /*<bind>*/ { x = x, y = { z = () => z } } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("z", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("z", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, z, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestWithExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable record B(string? X) { static void M1(B b1) { var x = ""hello""; _ = /*<bind>*/b1 with { X = x }/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { List<int> list = /*<bind>*/ new List<int>() { 1, 2, 3, 4, 5 } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression_LocalAccessed() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { int x = 1; List<int> list = new List<int>() /*<bind>*/ { x } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression_ComplexElementInitializer() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { int x = 1; List<int> list = new List<int>() { /*<bind>*/ { x } /*</bind>*/ }; return 0; } } "); // Nice to have: "x" flows in, "x" read inside, "list, x" written outside. Assert.False(analysis.Succeeded); } [Fact] public void TestCollectionInitializerExpression_VariableCaptured() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public delegate int D(); public static int Main() { int x = 1; List<D> list = new List<D>() /*<bind>*/ { () => x } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("x", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void ObjectInitializerInField() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class C { public Func<int, int, int> dele; } public class Test { C c = /*<bind>*/new C { dele = delegate(int x, int y) { return x + y; } }/*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact] public void CollectionInitializerInField() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class C { public Func<int, int, int> dele; } public class Test { List<Func<int, int, int>> list = /*<bind>*/new List<Func<int, int, int>>() { (x, y) => { return x + y; } }/*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact(), WorkItem(529329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529329")] public void QueryAsFieldInitializer() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; using System.Collections.Generic; using System.Collections; class Test { public IEnumerable e = /*<bind>*/ from x in new[] { 1, 2, 3 } where BadExpression let y = x.ToString() select y /*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [WorkItem(544361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544361")] [Fact] public void FullQueryExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System.Linq; class Program { static void Main(string[] args) { var q = /*<bind>*/from arg in args group arg by arg.Length into final select final/*</bind>*/; } }"); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverRead() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); var value = /*<bind>*/x.y/*</bind>*/.z.Value; } }"); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverWritten() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); /*<bind>*/x.y/*</bind>*/.z.Value = 3; } }"); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverReadAndWritten() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); /*<bind>*/x.y/*</bind>*/.z.Value += 3; } }"); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void UnaryPlus() { // reported at https://social.msdn.microsoft.com/Forums/vstudio/en-US/f5078027-def2-429d-9fef-ab7f240883d2/writteninside-for-unary-operators?forum=roslyn var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Main { static int Main(int a) { /*<bind>*/ return +a; /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void NullCoalescingAssignment() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowMultipleExpressions(@" public class C { public static void Main() { C c; c ??= new C(); object x1; object y1; /*<bind0>*/GetC(x1 = 1).Prop ??= (y1 = 2)/*</bind0>*/; x1.ToString(); y1.ToString(); object x2; object y2; /*<bind1>*/GetC(x2 = 1).Field ??= (y2 = 2)/*</bind1>*/; x2.ToString(); y2.ToString(); } static C GetC(object i) => null; object Prop { get; set; } object Field; } "); var propertyDataFlowAnalysis = dataFlowAnalysisResults.First(); var fieldDataFlowAnalysis = dataFlowAnalysisResults.Skip(1).Single(); assertAllInfo(propertyDataFlowAnalysis, "x1", "y1", "x2", "y2"); assertAllInfo(fieldDataFlowAnalysis, "x2", "y2", "x1", "y1"); void assertAllInfo(DataFlowAnalysis dataFlowAnalysis, string currentX, string currentY, string otherX, string otherY) { Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal(currentX, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal($"{currentX}, {currentY}", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x1, y1, x2, y2", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal($"{currentX}, {currentY}", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal($"c, {otherX}, {otherY}", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } } [Fact] public void CondAccess_NullCoalescing_DataFlow() { // This test corresponds to ExtractMethodTests.TestFlowStateNullableParameters3 var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { public string M() { string? a = null; string? b = null; return /*<bind>*/(a + b + a)?.ToString()/*</bind>*/ ?? string.Empty; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("this, a, b", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } [Theory] [InlineData("c?.M0(x = 0)")] [InlineData("c!.M0(x = 0)")] public void CondAccess_Equals_DataFlowsOut_01(string leftOperand) { var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { bool M0(object? obj) => false; public static void M(C? c) { int x = 0; if (" + leftOperand + @" == /*<bind>*/c!.M0(x = 0)/*</bind>*/) { x.ToString(); } x.ToString(); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } [Theory] [InlineData("c?.M0(x = 0)")] [InlineData("c!.M0(x = 0)")] public void CondAccess_Equals_DataFlowsOut_02(string leftOperand) { var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { bool M0(object? obj) => false; public static void M(C? c) { int x = 0; if (" + leftOperand + @" == /*<bind>*/c!.M0(x = 0)/*</bind>*/) { x.ToString(); } } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } #endregion #region "Statements" [Fact] public void TestDataReadWrittenIncDecOperator() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static short Main() { short x = 0, y = 1, z = 2; /*<bind>*/ x++; y--; /*</bind>*/ return y; } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.StartPointIsReachable); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTernaryExpressionWithAssignments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ int z = x ? y = 1 : y = 2; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegion() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements( @"class C { public static void Main(string[] args) { int i; return; /*<bind>*/ i = i + 1; /*</bind>*/ int j = i; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegion2() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements( @"class C { public static void Main(string[] args) { string i = 0, j = 0, k = 0, l = 0; goto l1; /*<bind>*/ Console.WriteLine(i); j = 1; l1: Console.WriteLine(j); k = 1; goto l2; Console.WriteLine(k); l = 1; l3: Console.WriteLine(l); i = 1; /*</bind>*/ l2: Console.WriteLine(i + j + k + l); goto l3; } }"); Assert.Equal("j, l", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i, k", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegionInExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression( @"class C { public static bool Main() { int i, j; return false && /*<bind>*/((i = i + 1) == 2 || (j = i) == 3)/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [Fact] public void TestDeclarationWithSelfReferenceAndTernaryOperator() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x = true ? 1 : x; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestDeclarationWithTernaryOperatorAndAssignment() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x, z, y = true ? 1 : x = z; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x, z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestDictionaryInitializer() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Goo() { int i, j; /*<bind>*/ var s = new Dictionary<int, int>() {[i = j = 1] = 2 }; /*</bind>*/ System.Console.WriteLine(i + j); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.StartPointIsReachable); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i, j, s", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("i, j, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [WorkItem(542435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542435")] [Fact] public void NullArgsToAnalyzeControlFlowStatements() { var compilation = CreateCompilation(@" class C { static void Main() { int i = 10; } } "); var semanticModel = compilation.GetSemanticModel(compilation.SyntaxTrees[0]); var statement = compilation.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().First(); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(statement, null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(null, statement)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow(null, statement)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow(statement, null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow((StatementSyntax)null)); } [WorkItem(542507, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542507")] [Fact] public void DateFlowAnalyzeForLocalWithInvalidRHS() { // Case 1 var analysis = CompileAndAnalyzeDataFlowStatements(@" using System; public class Test { public delegate int D(); public void goo(ref D d) { /*<bind>*/ d = { return 10;}; /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); // Case 2 analysis = CompileAndAnalyzeDataFlowStatements(@" using System; public class Gen<T> { public void DefaultTest() { /*<bind>*/ object obj = default (new Gen<T>()); /*</bind>*/ } } "); Assert.Equal("obj", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [Fact] public void TestEntryPoints01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F() { goto L1; // 1 /*<bind>*/ L1: ; /*</bind>*/ goto L1; // 2 } }"); Assert.Equal(1, analysis.EntryPoints.Count()); } [Fact] public void TestExitPoints01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { L1: ; // 1 /*<bind>*/ if (x == 0) goto L1; if (x == 1) goto L2; if (x == 3) goto L3; L3: ; /*</bind>*/ L2: ; // 2 } }"); Assert.Equal(2, analysis.ExitPoints.Count()); } [Fact] public void TestRegionCompletesNormally01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ goto L1; /*</bind>*/ L1: ; } }"); Assert.True(analysis.StartPointIsReachable); Assert.False(analysis.EndPointIsReachable); } [Fact] public void TestRegionCompletesNormally02() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ x = 2; /*</bind>*/ } }"); Assert.True(analysis.EndPointIsReachable); } [Fact] public void TestRegionCompletesNormally03() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ if (x == 0) return; /*</bind>*/ } }"); Assert.True(analysis.EndPointIsReachable); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestVariablesDeclared01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a; /*<bind>*/ int b; int x, y = 1; { var z = ""a""; } /*</bind>*/ int c; } }"); Assert.Equal("b, x, y, z", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [Fact] public void TestVariablesInitializedWithSelfReference() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int x = x = 1; int y, z = 1; /*</bind>*/ } }"); Assert.Equal("x, y, z", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void AlwaysAssignedUnreachable() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int y; /*<bind>*/ if (x == 1) { y = 2; return; } else { y = 3; throw new Exception(); } /*</bind>*/ int = y; } }"); Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [WorkItem(538170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538170")] [Fact] public void TestVariablesDeclared02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) /*<bind>*/ { int a; int b; int x, y = 1; { string z = ""a""; } int c; } /*</bind>*/ }"); Assert.Equal("a, b, x, y, z, c", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [WorkItem(541280, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541280")] [Fact] public void TestVariablesDeclared03() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F() /*<bind>*/ { int a = 0; long a = 1; } /*</bind>*/ }"); Assert.Equal("a, a", GetSymbolNamesJoined(analysis.VariablesDeclared)); var intsym = analysis.VariablesDeclared.First() as ILocalSymbol; var longsym = analysis.VariablesDeclared.Last() as ILocalSymbol; Assert.Equal("Int32", intsym.Type.Name); Assert.Equal("Int64", longsym.Type.Name); } [WorkItem(539229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539229")] [Fact] public void UnassignedVariableFlowsOut01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main(string[] args) { int i = 10; /*<bind>*/ int j = j + i; /*</bind>*/ Console.Write(i); Console.Write(j); } }"); Assert.Equal("j", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("j", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i, j", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("i, j", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("j", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestDataFlowsIn01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y = 2; /*<bind>*/ int b = a + x + 3; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("x, a", GetSymbolNamesJoined(analysis.DataFlowsIn)); } [Fact] public void TestOutParameter01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(out T t) where T : class, new() { /*<bind>*/ T t1; Test(out t1); t = t1; /*</bind>*/ System.Console.WriteLine(t1.ToString()); } } "); Assert.Equal("this", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("t, t1", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y; /*<bind>*/ if (x == 1) y = x = 2; /*</bind>*/ int c = a + 4 + x + y; } }"); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [WorkItem(538146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538146")] [Fact] public void TestDataFlowsOut02() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void Test(string[] args) { /*<bind>*/ int s = 10, i = 1; int b = s + i; /*</bind>*/ System.Console.WriteLine(s); System.Console.WriteLine(i); } }"); Assert.Equal("s, i", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut03() { var analysis = CompileAndAnalyzeDataFlowStatements( @"using System.Text; class Program { private static string Main() { StringBuilder builder = new StringBuilder(); /*<bind>*/ builder.Append(""Hello""); builder.Append("" From ""); builder.Append("" Roslyn""); /*</bind>*/ return builder.ToString(); } }"); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut04() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(out int x) { /*<bind>*/ x = 12; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut05() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(out int x) { /*<bind>*/ x = 12; return; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut06() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i = 1; while (b) { /*<bind>*/ i = i + 1; /*</bind>*/ } } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("b", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut07() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i; /*<bind>*/ i = 2; goto next; /*</bind>*/ next: int j = i; } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(analysis.ReadOutside)); } [WorkItem(540793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540793")] [Fact] public void TestDataFlowsOut08() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i = 2; try { /*<bind>*/ i = 1; /*</bind>*/ } finally { int j = i; } } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut09() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void Test(string[] args) { int i; string s; /*<bind>*/i = 10; s = args[0] + i.ToString();/*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut10() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main(string[] args) { int x = 10; /*<bind>*/ int y; if (x == 10) y = 5; /*</bind>*/ Console.WriteLine(y); } } "); Assert.Equal("y", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestAlwaysAssigned01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y = 1; /*<bind>*/ if (x == 2) a = 3; else a = 4; x = 4; if (x == 3) y = 12; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("x, a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssigned02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ const int a = 1; /*</bind>*/ } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [WorkItem(540795, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540795")] [Fact] public void TestAlwaysAssigned03() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Always { public void F() { ushort x = 0, y = 1, z; /*<bind>*/ x++; return; uint z = y; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestReadInside01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(out T t) where T : class, new() { /*<bind>*/ T t1; Test(out t1); t = t1; /*</bind>*/ System.Console.WriteLine(t1.ToString()); } } "); Assert.Equal("this, t1", GetSymbolNamesJoined(analysis.ReadInside)); } [Fact] public void TestAlwaysAssignedDuplicateVariables() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a, a, b, b; b = 1; /*</bind>*/ } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAccessedInsideOutside() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a, b, c, d, e, f, g, h, i; a = 1; c = b = a + x; /*<bind>*/ d = c; e = f = d; /*</bind>*/ g = e; h = i = g; } }"); Assert.Equal("c, d", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("d, e, f", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, a, e, g", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, b, c, g, h, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestAlwaysAssignedThroughParenthesizedExpression() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a = 1, b, c, d, e; b = 2; (c) = 3; ((d)) = 4; /*</bind>*/ } }"); Assert.Equal("a, b, c, d", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedThroughCheckedExpression() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int e, f, g; checked(e) = 5; (unchecked(f)) = 5; /*</bind>*/ } }"); Assert.Equal("e, f", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedUsingAlternateNames() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int green, blue, red, yellow, brown; @green = 1; blu\u0065 = 2; re܏d = 3; yellow\uFFF9 = 4; @brown\uFFF9 = 5; /*</bind>*/ } }"); Assert.Equal("green, blue, red, yellow, brown", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedViaPassingAsOutParameter() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a; G(out a); /*</bind>*/ } void G(out int x) { x = 1; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedWithExcludedAssignment() { var analysis = CompileAndAnalyzeDataFlowStatements(@" partial class C { public void F(int x) { /*<bind>*/ int a, b; G(a = x = 1); H(b = 2); /*</bind>*/ } partial void G(int x); partial void H(int x); partial void H(int x) { } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestDeclarationWithSelfReference() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x = x; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithAssignments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (x) y = 1; else y = 2; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithConstantCondition() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (true) y = x; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithNonConstantCondition() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (true | x) y = x; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } // [Obsolete] // [Fact] // public void TestNonStatementSelection() // { // var analysisResults = CompileAndAnalyzeControlAndDataFlowRegion(@" //class C { // static void Main() // { // // /*<bind>*/ //int // /*</bind>*/ // x = 1; // } //} //"); // var controlFlowAnalysisResults = analysisResults.Item1; // var dataFlowAnalysisResults = analysisResults.Item2; // Assert.True(controlFlowAnalysisResults.Succeeded); // Assert.True(dataFlowAnalysisResults.Succeeded); // Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); // Assert.True(controlFlowAnalysisResults.EndPointIsReachable); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)); // Assert.Equal("x", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)); // } [Fact] public void TestInvocation() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { int x = 1, y = 1; /*<bind>*/ Goo(x); /*</bind>*/ } static void Goo(int x) { } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestInvocationWithAssignmentInArguments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { int x = 1, y = 1; /*<bind>*/ Goo(x = y, y = 2); /*</bind>*/ int z = x + y; } static void Goo(int x, int y) { } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact, WorkItem(538979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538979")] public void AssertFromInvalidLocalDeclaration() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; public class MyClass { public static int Main() { variant /*<bind>*/ v = new byte(2) /*</bind>*/; // CS0246 byte b = v; // CS1729 return 1; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); } [Fact, WorkItem(538979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538979")] public void AssertFromInvalidKeywordAsExpr() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class B : A { public float M() { /*<bind>*/ { return base; // CS0175 } /*</bind>*/ } } class A {} "); var controlFlowAnalysisResults = analysisResults.Item1; //var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); } [WorkItem(539071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539071")] [Fact] public void AssertFromFoldConstantEnumConversion() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" enum E { x, y, z } class Test { static int Main() { /*<bind>*/ E v = E.x; if (v != (E)((int)E.z - 1)) return 0; /*</bind>*/ return 1; } } "); var controlFlowAnalysisResults = analysisResults.Item1; //var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); } [Fact] public void ByRefParameterNotInAppropriateCollections2() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(ref T t) { /*<bind>*/ T t1 = GetValue<T>(ref t); /*</bind>*/ System.Console.WriteLine(t1.ToString()); } T GetValue<T>(ref T t) { return t; } } "); Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void UnreachableDeclaration() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void F() { /*<bind>*/ int x; /*</bind>*/ System.Console.WriteLine(x); } } "); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void Parameters01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void F(int x, ref int y, out int z) { /*<bind>*/ y = z = 3; /*</bind>*/ } } "); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(528308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528308")] [Fact] public void RegionForIfElseIfWithoutElse() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class Test { ushort TestCase(ushort p) { /*<bind>*/ if (p > 0) { return --p; } else if (p < 0) { return ++p; } /*</bind>*/ // else { return 0; } } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Empty(controlFlowAnalysisResults.EntryPoints); Assert.Equal(2, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } // [Obsolete] // [Fact] // public void TestBadRegion() // { // var analysisResults = CompileAndAnalyzeControlAndDataFlowRegion(@" //class C { // static void Main() // { // int a = 1; // int b = 1; // // if(a > 1) // /*<bind>*/ // a = 1; // b = 2; // /*</bind>*/ // } //} //"); // var controlFlowAnalysisResults = analysisResults.Item1; // var dataFlowAnalysisResults = analysisResults.Item2; // Assert.False(controlFlowAnalysisResults.Succeeded); // Assert.False(dataFlowAnalysisResults.Succeeded); // Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); // Assert.True(controlFlowAnalysisResults.EndPointIsReachable); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)); // } [WorkItem(541331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541331")] [Fact] public void AttributeOnAccessorInvalid() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class C { public class AttributeX : Attribute { } public int Prop { get /*<bind>*/{ return 1; }/*</bind>*/ protected [AttributeX] set { } } } "); var controlFlowAnalysisResults = analysisResults.Item1; Assert.Empty(controlFlowAnalysisResults.EntryPoints); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); } [WorkItem(541585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541585")] [Fact] public void BadAssignThis() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class Program { static void Main(string[] args) { /*<bind>*/ this = new S(); /*</bind>*/ } } struct S { }"); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(528623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528623")] [Fact] public void TestElementAccess01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" public class Test { public void M(long[] p) { var v = new long[] { 1, 2, 3 }; /*<bind>*/ v[0] = p[0]; p[0] = v[1]; /*</bind>*/ v[1] = v[0]; p[2] = p[0]; } } "); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.DataFlowsIn)); // By Design Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.ReadInside)); // By Design Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, p, v", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(541947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541947")] [Fact] public void BindPropertyAccessorBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public int P { get /*<bind>*/ { return 0; } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.False(ctrlFlows.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); } [WorkItem(8926, "DevDiv_Projects/Roslyn")] [WorkItem(542346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542346")] [WorkItem(528775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528775")] [Fact] public void BindEventAccessorBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public delegate void D(); public event D E { add { /*NA*/ } remove /*<bind>*/ { /*NA*/ } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.True(ctrlFlows.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); } [WorkItem(541980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541980")] [Fact] public void BindDuplicatedAccessor() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public int P { get { return 1;} get /*<bind>*/ { return 0; } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; var tmp = ctrlFlows.EndPointIsReachable; // ensure no exception thrown Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(543737, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543737")] [Fact] public void BlockSyntaxInAttributeDecl() { { var compilation = CreateCompilation(@" [Attribute(delegate.Class)] public class C { public static int Main () { return 1; } } "); var tree = compilation.SyntaxTrees.First(); var index = tree.GetCompilationUnitRoot().ToFullString().IndexOf(".Class)", StringComparison.Ordinal); var tok = tree.GetCompilationUnitRoot().FindToken(index); var node = tok.Parent as StatementSyntax; Assert.Null(node); } { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" [Attribute(x => { /*<bind>*/int y = 12;/*</bind>*/ })] public class C { public static int Main () { return 1; } } "); Assert.False(results.Item1.Succeeded); Assert.False(results.Item2.Succeeded); } } [Fact, WorkItem(529273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529273")] public void IncrementDecrementOnNullable() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class C { void M(ref sbyte p1, ref sbyte? p2) { byte? local_0 = 2; short? local_1; ushort non_nullable = 99; /*<bind>*/ p1++; p2 = (sbyte?) (local_0.Value - 1); local_1 = (byte)(p2.Value + 1); var ret = local_1.HasValue ? local_1.Value : 0; --non_nullable; /*</bind>*/ } } "); Assert.Equal("ret", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("p1, p2, local_1, non_nullable, ret", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("p1, local_0, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("p1, p2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("p1, p2, local_0, local_1, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("p1, p2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p1, p2, local_1, non_nullable, ret", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, p1, p2, local_0, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(17971, "https://github.com/dotnet/roslyn/issues/17971")] [Fact] public void VariablesDeclaredInBrokenForeach() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { static void Main(string[] args) { /*<bind>*/ Console.WriteLine(1); foreach () Console.WriteLine(2); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact] [WorkItem(4950, "https://github.com/dotnet/roslyn/issues/4950")] public void RegionWithUnsafeBlock() { var source = @"using System; class Program { static void Main(string[] args) { object value = args; // start IntPtr p; unsafe { object t = value; p = IntPtr.Zero; } // end Console.WriteLine(p); } } "; foreach (string keyword in new[] { "unsafe", "checked", "unchecked" }) { var compilation = CreateCompilation(source.Replace("unsafe", keyword)); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var stmt1 = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().Where(n => n.ToString() == "IntPtr p;").Single(); var stmt2 = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().Where(n => n.ToString().StartsWith(keyword)).First(); var dataFlowAnalysisResults = model.AnalyzeDataFlow(stmt1, stmt2); Assert.True(dataFlowAnalysisResults.Succeeded); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, value, p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("args, p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } } #endregion #region "lambda" [Fact] [WorkItem(41600, "https://github.com/dotnet/roslyn/pull/41600")] public void DataFlowAnalysisLocalFunctions10() { var dataFlow = CompileAndAnalyzeDataFlowExpression(@" class C { public void M() { bool Dummy(params object[] x) {return true;} try {} catch when (/*<bind>*/TakeOutParam(out var x1)/*</bind>*/ && x1 > 0) { Dummy(x1); } var x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out var x4) && x4 > 0) { Dummy(x4); } try {} catch when (x6 && TakeOutParam(out var x6)) { Dummy(x6); } try {} catch when (TakeOutParam(out var x7) && x7 > 0) { var x7 = 12; Dummy(x7); } try {} catch when (TakeOutParam(out var x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); try {} catch when (TakeOutParam(out var x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out var x9) && x9 > 0) // 2 { Dummy(x9); } } try {} catch when (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } // try {} // catch when (TakeOutParam(y11, out var x11) // { // let y11 = 12; // Dummy(y11); // } try {} catch when (Dummy(TakeOutParam(out var x14), TakeOutParam(out var x14), // 2 x14)) { Dummy(x14); } try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out var x15), x15)) { Dummy(x15); } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } } "); Assert.True(dataFlow.Succeeded); Assert.Null(GetSymbolNamesJoined(dataFlow.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedOutside)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlow.DataFlowsIn)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnEntry)); Assert.Equal("this, x1", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlow.ReadInside)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.WrittenInside)); Assert.Equal("this, x1, x4, x4, x6, x7, x7, x8, x9, x9, y10, x14, x15, x, x", GetSymbolNamesJoined(dataFlow.ReadOutside)); Assert.Equal("this, x, x4, x4, x6, x7, x7, x8, x9, x9, x10, " + "y10, x14, x14, x15, x15, x, y, x", GetSymbolNamesJoined(dataFlow.WrittenOutside)); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void DataFlowAnalysisLocalFunctions9() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { int Testing; void M() { local(); /*<bind>*/ NewMethod(); /*</bind>*/ Testing = 5; void local() { } } void NewMethod() { } }"); var dataFlow = results.dataFlowAnalysis; Assert.True(dataFlow.Succeeded); Assert.Null(GetSymbolNamesJoined(dataFlow.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlow.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlow.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.WrittenOutside)); var controlFlow = results.controlFlowAnalysis; Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions01() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { local(); /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.False(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions02() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ local(); System.Console.WriteLine(0); /*</bind>*/ void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions03() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ local(); void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions04() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { System.Console.WriteLine(0); local(); void local() { /*<bind>*/ throw null; /*</bind>*/ } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions05() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { local(); void local() { /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions06() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { void local() { throw null; } /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] public void TestReturnStatements03() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; /*<bind>*/ if (x == 1) return; Func<int,int> f = (int i) => { return i+1; }; if (x == 2) return; /*</bind>*/ } }"); Assert.Equal(2, analysis.ExitPoints.Count()); } [Fact] public void TestReturnStatements04() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; if (x == 1) return; Func<int,int> f = (int i) => { /*<bind>*/ return i+1; /*</bind>*/ } ; if (x == 2) return; } }"); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestReturnStatements05() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; if (x == 1) return; /*<bind>*/ Func<int,int?> f = (int i) => { return i == 1 ? i+1 : null; } ; /*</bind>*/ if (x == 2) return; } }"); Assert.True(analysis.Succeeded); Assert.Empty(analysis.ReturnStatements); } [Fact] public void TestReturnStatements06() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(uint? x) { if (x == null) return; if (x.Value == 1) return; /*<bind>*/ Func<uint?, ulong?> f = (i) => { return i.Value +1; } ; if (x.Value == 2) return; /*</bind>*/ } }"); Assert.True(analysis.Succeeded); Assert.Equal(1, analysis.ExitPoints.Count()); } [WorkItem(541198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541198")] [Fact] public void TestReturnStatements07() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public int F(int x) { Func<int,int> f = (int i) => { goto XXX; /*<bind>*/ return 1; /*</bind>*/ } ; } }"); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestMultipleLambdaExpressions() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { void M() { int i; N(/*<bind>*/() => { M(); }/*</bind>*/, () => { i++; }); } void N(System.Action x, System.Action y) { } }"); Assert.True(analysis.Succeeded); Assert.Equal("this, i", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("this", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReturnFromLambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; class Program { static void Main(string[] args) { int i = 1; Func<int> lambda = () => { /*<bind>*/return i;/*</bind>*/ }; } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, lambda", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void DataFlowsOutLambda01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main(string[] args) { int i = 12; D d = () => { /*<bind>*/ i = 14; return; /*</bind>*/ }; int j = i; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void DataFlowsOutLambda02() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main() { int? i = 12; D d = () => { /*<bind>*/ i = 14; /*</bind>*/ return; }; int j = i.Value; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void DataFlowsOutLambda03() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main(string[] args) { int i = 12; D d = () => { /*<bind>*/ i = 14; /*</bind>*/ }; int j = i; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [WorkItem(538984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538984")] [Fact] public void TestReadInside02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void Method() { System.Func<int, int> a = x => /*<bind>*/x * x/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, a, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestCaptured02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" using System; class C { int field = 123; public void F(int x) { const int a = 1, y = 1; /*<bind>*/ Func<int> lambda = () => x + y + field; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y, lambda", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact, WorkItem(539648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539648"), WorkItem(529185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529185")] public void ReturnsInsideLambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; class Program { delegate R Func<T, R>(T t); static void Main(string[] args) { /*<bind>*/ Func<int, int> f = (arg) => { int s = 3; return s; }; /*</bind>*/ f.Invoke(2); } }"); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Empty(controlFlowAnalysisResults.ReturnStatements); Assert.Equal("f", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, f", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("f, arg, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); } [WorkItem(539861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539861")] [Fact] public void VariableDeclaredLambda01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { /*<bind>*/ TestDelegate testDel = (ref int x) => { }; /*</bind>*/ int p = 2; testDel(ref p); Console.WriteLine(p); } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, testDel", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("testDel, x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("testDel, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); } [WorkItem(539861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539861")] [Fact] public void VariableDeclaredLambda02() { var results1 = CompileAndAnalyzeDataFlowStatements(@" using System; class Program { delegate void TestDelegate(ref int? x); static void Main() { /*<bind>*/ TestDelegate testDel = (ref int? x) => { int y = x; x.Value = 10; }; /*</bind>*/ int? p = 2; testDel(ref p); Console.WriteLine(p); } } "); Assert.Equal("testDel, x, y", GetSymbolNamesJoined(results1.VariablesDeclared)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(results1.Captured)); Assert.Null(GetSymbolNamesJoined(results1.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results1.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results1.DataFlowsIn)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results1.DefinitelyAssignedOnEntry)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results1.ReadInside)); Assert.Equal("testDel, p", GetSymbolNamesJoined(results1.ReadOutside)); Assert.Equal("testDel, x, y", GetSymbolNamesJoined(results1.WrittenInside)); Assert.Equal("p", GetSymbolNamesJoined(results1.WrittenOutside)); } [WorkItem(540449, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540449")] [Fact] public void AnalysisInsideLambdas() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static void Main() { Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; } } "); Assert.Equal("x", GetSymbolNamesJoined(results1.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(results1.Captured)); Assert.Null(GetSymbolNamesJoined(results1.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results1.CapturedOutside)); Assert.Equal("p, y", GetSymbolNamesJoined(results1.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results1.DataFlowsOut)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results1.DefinitelyAssignedOnEntry)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results1.DefinitelyAssignedOnExit)); Assert.Equal("p, y", GetSymbolNamesJoined(results1.ReadInside)); Assert.Null(GetSymbolNamesJoined(results1.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results1.WrittenInside)); Assert.Equal("f, p, x, y", GetSymbolNamesJoined(results1.WrittenOutside)); } [WorkItem(528622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528622")] [Fact] public void AlwaysAssignedParameterLambda() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; internal class Test { void M(sbyte[] ary) { /*<bind>*/ ( (Action<short>)(x => { Console.Write(x); }) )(ary[0])/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Equal("ary", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("ary, x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [WorkItem(541946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541946")] [Fact] public void LambdaInTernaryWithEmptyBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public delegate void D(); public class A { void M() { int i = 0; /*<bind>*/ D d = true ? (D)delegate { i++; } : delegate { }; /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.True(ctrlFlows.EndPointIsReachable); Assert.Equal("d", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("d", GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.Captured)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, i", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, i, d", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("i, d", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Equal("this, i", GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact] public void ForEachVariableInLambda() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class Program { static void Main() { var nums = new int?[] { 4, 5 }; foreach (var num in /*<bind>*/nums/*</bind>*/) { Func<int, int> f = x => x + num.Value; Console.WriteLine(f(0)); } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("num, f, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, f, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543398")] [Fact] public void LambdaBlockSyntax() { var source = @" using System; class c1 { void M() { var a = 0; foreach(var l in """") { Console.WriteLine(l); a = (int) l; l = (char) a; } Func<int> f = ()=> { var c = a; a = c; return 0; }; var b = 0; Console.WriteLine(b); } }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CSharpCompilation.Create("FlowAnalysis", syntaxTrees: new[] { tree }); var model = comp.GetSemanticModel(tree); var methodBlock = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BlockSyntax>().First(); var foreachStatement = methodBlock.DescendantNodes().OfType<ForEachStatementSyntax>().First(); var foreachBlock = foreachStatement.DescendantNodes().OfType<BlockSyntax>().First(); var lambdaExpression = methodBlock.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().First(); var lambdaBlock = lambdaExpression.DescendantNodes().OfType<BlockSyntax>().First(); var flowAnalysis = model.AnalyzeDataFlow(methodBlock); Assert.Equal(4, flowAnalysis.ReadInside.Count()); Assert.Equal(5, flowAnalysis.WrittenInside.Count()); Assert.Equal(5, flowAnalysis.VariablesDeclared.Count()); flowAnalysis = model.AnalyzeDataFlow(foreachBlock); Assert.Equal(2, flowAnalysis.ReadInside.Count()); Assert.Equal(2, flowAnalysis.WrittenInside.Count()); Assert.Equal(0, flowAnalysis.VariablesDeclared.Count()); flowAnalysis = model.AnalyzeDataFlow(lambdaBlock); Assert.Equal(2, flowAnalysis.ReadInside.Count()); Assert.Equal(2, flowAnalysis.WrittenInside.Count()); Assert.Equal(1, flowAnalysis.VariablesDeclared.Count()); } [Fact] public void StaticLambda_01() { var source = @" using System; class C { static void Main() { int x = 42; Action fn = static () => Console.Write(x); fn(); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,48): error CS8820: A static anonymous function cannot contain a reference to 'x'. // Action fn = static () => Console.Write(x); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(9, 48) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("x", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } [Fact] public void StaticLambda_02() { var source = @" using System; class C { static void Main() { int x = 42; Action fn = static () => { int y = x; x = 43; Console.Write(y); }; fn(); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,21): error CS8820: A static anonymous function cannot contain a reference to 'x'. // int y = x; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(11, 21), // (12,13): error CS8820: A static anonymous function cannot contain a reference to 'x'. // x = 43; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(12, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("x, y", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } [Fact] public void StaticLambda_03() { var source = @" using System; class C { public static int x = 42; static void Main() { Action fn = static () => { int y = x; x = 43; Console.Write(y); }; fn(); } } "; verify(source); verify(source.Replace("static (", "(")); void verify(string source) { var verifier = CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "42"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } } #endregion #region "query expressions" [Fact] public void QueryExpression01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 1, 2, 3, 4 }; /*<bind>*/ var q2 = from x in nums where (x > 2) where x > 3 select x; /*</bind>*/ } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("q2", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, q2", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new sbyte[] { 1, 2, 3, 4 }; var q2 = from x in nums where (x > 2) select /*<bind>*/ x+1 /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression03() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int?[] { 1, 2, null, 4 }; var q2 = from x in nums group x.Value + 1 by /*<bind>*/ x.Value % 2 /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression04() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new uint[] { 1, 2, 3, 4 }; var q2 = from int x in nums where x < 3 select /*<bind>*/ x /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression05() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new sbyte[] { 1, 2, 3, 4 }; var q2 = from int x in nums where x < 3 group /*<bind>*/ x /*</bind>*/ by x%2; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541916")] [Fact] public void ForEachVariableInQueryExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 4, 5 }; foreach (var num in nums) { var q = from n in /*<bind>*/ nums /*</bind>*/ select num; } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, q, n", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541945, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541945")] [Fact] public void ForVariableInQueryExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 4, 5 }; for (int num = 0; num < 10; num++) { var q = from n in /*<bind>*/ nums /*</bind>*/ select num; } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, q, n", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541926")] [Fact] public void Bug8863() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System.Linq; class C { static void Main(string[] args) { /*<bind>*/ var temp = from x in ""abc"" let z = x.ToString() select z into w select w; /*</bind>*/ } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("temp, x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("temp", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, temp", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("temp, x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void Bug9415() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var q1 = from x in new int[] { /*<bind>*/4/*</bind>*/, 5 } orderby x select x; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, q1, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543546")] [Fact] public void GroupByClause() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System.Linq; public class Test { public static void Main() { var strings = new string[] { }; var q = from s in strings select s into t /*<bind>*/group t by t.Length/*</bind>*/; } }"); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291")] [Fact] public void CaptureInQuery() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System.Linq; public class Test { public static void Main(int[] data) { int y = 1; { int x = 2; var f2 = from a in data select a + y; var f3 = from a in data where x > 0 select a; var f4 = from a in data let b = 1 where /*<bind>*/M(() => b)/*</bind>*/ select a + b; var f5 = from c in data where M(() => c) select c; } } private static bool M(Func<int> f) => true; }"); var dataFlowAnalysisResults = analysisResults; Assert.Equal("y, x, b", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } #endregion query expressions #region "switch statement tests" [Fact] public void LocalInOtherSwitchCase() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; using System.Linq; public class Test { public static void Main() { int ret = 6; switch (ret) { case 1: int i = 10; break; case 2: var q1 = from j in new int[] { 3, 4 } select /*<bind>*/i/*</bind>*/; break; } } }"); Assert.Empty(dataFlows.DataFlowsOut); } [WorkItem(541639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541639")] [Fact] public void VariableDeclInsideSwitchCaptureInLambdaExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { public static void Main() { switch (10) { default: int i = 10; Func<int> f1 = () => /*<bind>*/i/*</bind>*/; break; } } } "); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i, f1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541710")] [Fact] public void ArrayCreationExprInForEachInsideSwitchSection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { switch ('2') { default: break; case '2': foreach (var i100 in new int[] {4, /*<bind>*/5/*</bind>*/ }) { } break; } } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Empty(dataFlowAnalysisResults.DataFlowsIn); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Empty(dataFlowAnalysisResults.ReadInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("i100", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void RegionInsideSwitchExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { switch ('2') { default: break; case '2': switch (/*<bind>*/'2'/*</bind>*/) { case '2': break; } break; } } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Empty(dataFlowAnalysisResults.DataFlowsIn); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Empty(dataFlowAnalysisResults.ReadInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void NullableAsSwitchExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" using System; class C { public void F(ulong? p) { /*<bind>*/ switch (p) { case null: break; case 1: goto case null; default: break; } /*</bind>*/ } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(17281, "https://github.com/dotnet/roslyn/issues/17281")] public void DiscardVsVariablesDeclared() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class A { } class Test { private void Repro(A node) { /*<bind>*/ switch (node) { case A _: break; case Unknown: break; default: return; } /*</bind>*/ } }"); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Equal("node", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("node", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } #endregion #region "Misc." [Fact, WorkItem(11298, "DevDiv_Projects/Roslyn")] public void BaseExpressionSyntax() { var source = @" using System; public class BaseClass { public virtual void MyMeth() { } } public class MyClass : BaseClass { public override void MyMeth() { base.MyMeth(); } delegate BaseClass D(); public void OtherMeth() { D f = () => base; } public static void Main() { } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocation = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(invocation); Assert.Empty(flowAnalysis.Captured); Assert.Empty(flowAnalysis.CapturedInside); Assert.Empty(flowAnalysis.CapturedOutside); Assert.Equal("MyClass this", flowAnalysis.DataFlowsIn.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.DataFlowsOut); Assert.Equal("MyClass this", flowAnalysis.ReadInside.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.WrittenInside); Assert.Equal("MyClass this", flowAnalysis.WrittenOutside.Single().ToTestDisplayString()); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); flowAnalysis = model.AnalyzeDataFlow(lambda); Assert.Equal("MyClass this", flowAnalysis.Captured.Single().ToTestDisplayString()); Assert.Equal("MyClass this", flowAnalysis.DataFlowsIn.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.DataFlowsOut); Assert.Equal("MyClass this", flowAnalysis.ReadInside.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.WrittenInside); Assert.Equal("this, f", GetSymbolNamesJoined(flowAnalysis.WrittenOutside)); } [WorkItem(543101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543101")] [Fact] public void AnalysisInsideBaseClause() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { A(int x) : this(/*<bind>*/x.ToString()/*</bind>*/) { } A(string x) { } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543758, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543758")] [Fact] public void BlockSyntaxOfALambdaInAttributeArg() { var controlFlowAnalysisResults = CompileAndAnalyzeControlFlowStatements(@" class Test { [Attrib(() => /*<bind>*/{ }/*</bind>*/)] public static void Main() { } } "); Assert.False(controlFlowAnalysisResults.Succeeded); } [WorkItem(529196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529196")] [Fact()] public void DefaultValueOfOptionalParam() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" public class Derived { public void Goo(int x = /*<bind>*/ 2 /*</bind>*/) { } } "); Assert.True(dataFlowAnalysisResults.Succeeded); } [Fact] public void GenericStructureCycle() { var source = @"struct S<T> { public S<S<T>> F; } class C { static void M() { S<object> o; } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetFirstNode<StatementSyntax>(tree, root.ToFullString().IndexOf("S<object> o", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); Assert.Equal("o", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(545372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545372")] [Fact] public void AnalysisInSyntaxError01() { var source = @"using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; class Program { static void Main(string[] args) { Expression<Func<int>> f3 = () => if (args == null) {}; } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetLastNode<StatementSyntax>(tree, root.ToFullString().IndexOf("if", StringComparison.Ordinal)); Assert.Equal("if (args == null) {}", statement.ToFullString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, f3", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(546964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546964")] [Fact] public void AnalysisWithMissingMember() { var source = @"class C { void Goo(string[] args) { foreach (var s in args) { this.EditorOperations = 1; } } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetLastNode<StatementSyntax>(tree, root.ToFullString().IndexOf("EditorOperations", StringComparison.Ordinal)); Assert.Equal("this.EditorOperations = 1;", statement.ToString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); var v = analysis.DataFlowsOut; } [Fact, WorkItem(547059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547059")] public void ObjectInitIncompleteCodeInQuery() { var source = @" using System.Collections.Generic; using System.Linq; class Program { static void Main() { var symlist = new List<ISymbol>(); var expList = from s in symlist select new ExportedSymbol() { S } } public interface ISymbol { } public class ExportedSymbol { public ISymbol Symbol; public byte UseBits; } "; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var statement = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BlockSyntax>().FirstOrDefault(); var expectedtext = @" { var symlist = new List<ISymbol>(); var expList = from s in symlist select new ExportedSymbol() { S } } "; Assert.Equal(expectedtext, statement.ToFullString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); } [Fact] public void StaticSetterAssignedInCtor() { var source = @"class C { C() { P = new object(); } static object P { get; set; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetFirstNode<StatementSyntax>(tree, root.ToFullString().IndexOf("P = new object()", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); } [Fact] public void FieldBeforeAssignedInStructCtor() { var source = @"struct S { object value; S(object x) { S.Equals(value , value); this.value = null; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0170: Use of possibly unassigned field 'value' // S.Equals(value , value); Diagnostic(ErrorCode.ERR_UseDefViolationField, "value").WithArguments("value") ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetRoot(); var expression = GetLastNode<ExpressionSyntax>(tree, root.ToFullString().IndexOf("value ", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(expression); Assert.True(analysis.Succeeded); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact, WorkItem(14110, "https://github.com/dotnet/roslyn/issues/14110")] public void Test14110() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { var (a0, b0) = (1, 2); (var c0, int d0) = (3, 4); bool e0 = a0 is int f0; bool g0 = a0 is var h0; M(out int i0); M(out var j0); /*<bind>*/ var (a, b) = (1, 2); (var c, int d) = (3, 4); bool e = a is int f; bool g = a is var h; M(out int i); M(out var j); /*</bind>*/ var (a1, b1) = (1, 2); (var c1, int d1) = (3, 4); bool e1 = a1 is int f1; bool g1 = a1 is var h1; M(out int i1); M(out var j1); } static void M(out int z) => throw null; } "); Assert.Equal("a, b, c, d, e, f, g, h, i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact, WorkItem(15640, "https://github.com/dotnet/roslyn/issues/15640")] public void Test15640() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" using System; class Programand { static void Main() { foreach (var (a0, b0) in new[] { (1, 2) }) {} /*<bind>*/ foreach (var (a, b) in new[] { (1, 2) }) {} /*</bind>*/ foreach (var (a1, b1) in new[] { (1, 2) }) {} } } "); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact] public void RegionAnalysisLocalFunctions() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ void Local() { } /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions2() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ Local(); /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions3() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ Action a = Local; /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions4() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ var a = new Action(Local); /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions5() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { void Local() { /*<bind>*/ int x = 0; x++; x = M(x + 1); /*</bind>*/ } Local(); } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions6() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { var a = new Action(() => { void Local() { /*<bind>*/ int x = 0; x++; x = M(x + 1); /*</bind>*/ } }); a(); } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions7() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ var a = (Action)Local; /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions8() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { int x = 0; void Local() { x++; } Local(); /*<bind>*/ x++; x = M(x + 1); /*</bind>*/ } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void LocalFuncCapture1() { var results = CompileAndAnalyzeDataFlowStatements(@" public static class SomeClass { private static void Repro( int arg ) { /*<bind>*/int localValue = arg;/*</bind>*/ int LocalCapture() => arg; } }"); Assert.True(results.Succeeded); Assert.Equal("arg", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("arg", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("arg", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("arg", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("arg, localValue", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("localValue", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("arg", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("arg", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("localValue", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture2() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; Local(); /*<bind>*/int y = x;/*</bind>*/ int Local() { x = 0; } } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture3() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; /*<bind>*/int y = x;/*</bind>*/ Local(); int Local() => x; } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture4() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x, y = 0; /*<bind>*/x = y;/*</bind>*/ Local(); int Local() => x; } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("this, y", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture5() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { int x = 0; void M() { /*<bind>*/ int L(int a) => x; /*</bind>*/ L(); } }"); Assert.Equal("this", GetSymbolNamesJoined(results.Captured)); Assert.Equal("this", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void LocalFuncCapture6() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M(int x) { int y; int z; void Local() { /*<bind>*/ x++; y = 0; y++; /*</bind>*/ } Local(); } }"); Assert.Equal("x, y", GetSymbolNamesJoined(results.Captured)); Assert.Equal("x, y", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); // TODO(https://github.com/dotnet/roslyn/issues/14214): This is wrong. // Both x and y should flow out. Assert.Equal("y", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this, x", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.AlwaysAssigned)); } [Fact] public void LocalFuncCapture7() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; void L() { /*<bind>*/ int y = 0; y++; x = 0; /*</bind>*/ } x++; } }"); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this, x", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.AlwaysAssigned)); } [Fact, WorkItem(37421, "https://github.com/dotnet/roslyn/issues/37421")] public void LocalFuncCapture8() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { int field = 123; void M(int x) { int a = 1, y = 1; int Outside() => x+field; /*<bind>*/ int Inside() => y; /*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("y", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact, WorkItem(37421, "https://github.com/dotnet/roslyn/issues/37421")] public void LocalFuncCapture9() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { int field = 123; void M(int x) { int a = 1, y = 1; int Outside() => x+field; Inside(); /*<bind>*/ int Inside() => y; /*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("y", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void AssignmentInsideLocal01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ x = 1; /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 1) { x = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal03() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if (false) { x = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); // This is a conservative approximation, ignoring whether the branch containing // the assignment is reachable Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal04() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ x = 1; /*</bind>*/ x = 1; } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] [WorkItem(39569, "https://github.com/dotnet/roslyn/issues/39569")] public void AssignmentInsideLocal05() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { x = 1; } /*<bind>*/ Local(); /*</bind>*/ System.Console.WriteLine(x); } } "); // Right now region analysis requires bound nodes for each variable and value being // assigned. This doesn't work with the current local function analysis because we only // store the slots, not the full boundnode of every assignment (which is impossible // anyway). This should be: // Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal06() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; /*<bind>*/ void Local() { x = 1; } /*</bind>*/ Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal07() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; /*<bind>*/ void Local() { x = 1; } Local(); /*</bind>*/ System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal08() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 0) { x = 1; return; } else { y = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); System.Console.WriteLine(y); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal09() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 0) { x = 1; return; } else { y = 1; throw new Exception(); } /*</bind>*/ } Local(); System.Console.WriteLine(x); System.Console.WriteLine(y); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); // N.B. This is not as precise as possible. The branch assigning y is unreachable, so // the result does not technically flow out. This is a conservative approximation. Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact, WorkItem(25043, "https://github.com/dotnet/roslyn/issues/25043")] public void FallThroughInSwitch_01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ switch (true) { case true: void f() { } } /*</bind>*/ } }"); Assert.Equal(0, analysis.EntryPoints.Count()); } [Fact, WorkItem(25043, "https://github.com/dotnet/roslyn/issues/25043")] public void FallThroughInSwitch_02() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ switch (true) { case true when true: void f() { } } /*</bind>*/ } }"); Assert.Equal(0, analysis.EntryPoints.Count()); } [Fact] public void AnalysisOfTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = /*<bind>*/(x, y) == (x = 0, 1)/*</bind>*/; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfNestedTupleInTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = (1, (2, 3)) == (0, /*<bind>*/(x = 0, y)/*</bind>*/); } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfExpressionInTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = (1, 2) == (0, /*<bind>*/(x = 0) + y/*</bind>*/); } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfMixedDeconstruction() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { bool M() { int x = 0; string y; /*<bind>*/ (x, (y, var z)) = (x, ("""", true)) /*</bind>*/ return z; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertyGetter_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { int _myProp; int MyProp { get => /*<bind>*/this._myProp;/*</bind>*/ set => this._myProp = value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertySetter_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { int _myProp; int MyProp { get => this._myProp; set => /*<bind>*/this._myProp = value;/*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertyGetter_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { int _myProp; int MyProp { get => /*<bind>*/this._myProp;/*</bind>*/ set => this._myProp = value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertySetter_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { int _myProp; int MyProp { get => this._myProp; set => /*<bind>*/this._myProp = value;/*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventAdder_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { EventHandler _myEvent; event EventHandler MyEvent { add => /*<bind>*/ this._myEvent += value; /*</bind>*/ remove => this._myEvent -= value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventRemover_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { EventHandler _myEvent; event EventHandler MyEvent { add => this._myEvent += value; remove => /*<bind>*/ this._myEvent -= value; /*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventAdder_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { EventHandler _myEvent; event EventHandler MyEvent { add => /*<bind>*/ this._myEvent += value; /*</bind>*/ remove => this._myEvent -= value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventRemover_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { EventHandler _myEvent; event EventHandler MyEvent { add => this._myEvent += value; remove => /*<bind>*/ this._myEvent -= value; /*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(27969, "https://github.com/dotnet/roslyn/issues/27969")] public void CodeInInitializer01() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { object P { get; } = Create(nameof(P), /*<bind>*/x => true/*</bind>*/); static object Create(string name, Func<string, bool> f) => throw null; } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(27969, "https://github.com/dotnet/roslyn/issues/27969")] public void CodeInInitializer02() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { object P { get; } = Create(P, /*<bind>*/x => true/*</bind>*/); static object Create(object name, Func<string, bool> f) => throw null; } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(19845, "https://github.com/dotnet/roslyn/issues/19845")] public void CodeInInitializer03() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static int X { get; set; } int Y = /*<bind>*/X/*</bind>*/; }"); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(26028, "https://github.com/dotnet/roslyn/issues/26028")] public void BrokenForeach01() { var source = @"class C { void M() { foreach (var x } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); // The foreach loop is broken, so its embedded statement is filled in during syntax error recovery. It is zero-width. var stmt = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<ForEachStatementSyntax>().Single().Statement; Assert.Equal(0, stmt.Span.Length); var dataFlowAnalysisResults = model.AnalyzeDataFlow(stmt); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(30548, "https://github.com/dotnet/roslyn/issues/30548")] public void SymbolInDataFlowInButNotInReadInside() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp39 { class Program { void Method(out object test) { test = null; var a = test != null; /*<bind>*/if (a) { return; } if (A == a) { test = new object(); }/*</bind>*/ } } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact, WorkItem(37427, "https://github.com/dotnet/roslyn/issues/37427")] public void RegionWithLocalFunctions() { // local functions inside the region var s1 = @" class A { static void M(int p) { int i, j; i = 1; /*<bind>*/ int L1() => 1; int k; j = i; int L2() => 2; /*</bind>*/ k = j; } } "; // local functions outside the region var s2 = @" class A { static void M(int p) { int i, j; i = 1; int L1() => 1; /*<bind>*/ int k; j = i; /*</bind>*/ int L2() => 2; k = j; } } "; foreach (var s in new[] { s1, s2 }) { var analysisResults = CompileAndAnalyzeDataFlowStatements(s); var dataFlowAnalysisResults = analysisResults; Assert.True(dataFlowAnalysisResults.Succeeded); Assert.Equal("k", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("p, i, k", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } } [Fact] public void TestAddressOfUnassignedStructLocal_02() { // This test demonstrates that "data flow analysis" pays attention to private fields // of structs imported from metadata. var libSource = @" public struct Struct { private string Field; }"; var libraryReference = CreateCompilation(libSource).EmitToImageReference(); var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { Struct x; // considered not definitely assigned because it has a field Struct * px = /*<bind>*/&x/*</bind>*/; // address taken of an unassigned variable } } ", libraryReference); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } #endregion #region "Used Local Functions" [Fact] public void RegionAnalysisUsedLocalFunctions() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ void Local() { } /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions2() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions3() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { } void Unused(){ } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions4() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Second(); } void Second() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions5() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions6() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions7() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Second(); } void Second() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions8() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ System.Action a = new System.Action(Local); /*</bind>*/ void Local() { Second(); } void Second() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions9() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ static void Local() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions10() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Sub(); static void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions11() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ static void Local() { Sub(); static void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions12() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions13() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions14() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions15() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions16() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions17() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions18() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions19() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions20() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions21() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions22() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions23() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } #endregion #region "Top level statements" [Fact] public void TestTopLevelStatements() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; /*<bind>*/ Console.Write(1); Console.Write(2); Console.Write(3); Console.Write(4); Console.Write(5); /*</bind>*/ "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTopLevelStatements_Lambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; int i = 1; Func<int> lambda = () => { /*<bind>*/return i;/*</bind>*/ }; "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i, args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i, args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i, lambda, args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTopLevelStatements_LambdaCapturingArgs() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; Func<int> lambda = () => { /*<bind>*/return args.Length;/*</bind>*/ }; "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("lambda, args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } #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.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { /// <summary> /// Tests for the region analysis APIs. /// </summary> /// <remarks> /// Please add your tests to other files if possible: /// * FlowDiagnosticTests.cs - all tests on Diagnostics /// * IterationJumpYieldStatementTests.cs - while, do, for, foreach, break, continue, goto, iterator (yield break, yield return) /// * TryLockUsingStatementTests.cs - try-catch-finally, lock, &amp; using statement /// * PatternsVsRegions.cs - region analysis tests for pattern matching /// </remarks> public partial class RegionAnalysisTests : FlowTestBase { #region "Expressions" [WorkItem(545047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545047")] [Fact] public void DataFlowsInAndNullable_Field() { // WARNING: if this test is edited, the test with the // test with the same name in VB must be modified too var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } static void Main(string[] args) { int? i = 1; S s = new S(1); /*<bind>*/ Console.WriteLine(i.Value); Console.WriteLine(s.F); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void DataFlowsOutAndStructField() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } static void Main(string[] args) { S s = new S(1); /*<bind>*/ s.F = 1; /*</bind>*/ var x = s.F; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, s, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void DataFlowsInAndNullable_Property() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { public int F; public S(int f) { this.F = f; } public int P { get; set; } static void Main(string[] args) { int? i = 1; S s = new S(1); /*<bind>*/ Console.WriteLine(i.Value); Console.WriteLine(s.P); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [WorkItem(538238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538238")] [Fact] public void TestDataFlowsIn03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main(string[] args) { int x = 1; int y = 2; int z = /*<bind>*/x + y/*</bind>*/; } } "); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestDataFlowForValueTypes() { // WARNING: test matches the same test in VB (TestDataFlowForValueTypes) // Keep the two tests in sync! var analysis = CompileAndAnalyzeDataFlowStatements(@" class Tst { public static void Main() { S0 a; S1 b; S2 c; S3 d; E0 e; E1 f; /*<bind>*/ Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(c); Console.WriteLine(d); Console.WriteLine(e); Console.WriteLine(f); /*</bind>*/ } } struct S0 { } struct S1 { public S0 s0; } struct S2 { public S0 s0; public int s1; } struct S3 { public S2 s; public object s1; } enum E0 { } enum E1 { V1 } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("a, b, c, d, e, f", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("a, b, c, d, e, f", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(538997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538997")] [Fact] public void TestDataFlowsIn04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; class Program { static void Main() { string s = ""; Func<string> f = /*<bind>*/s/*</bind>*/.ToString; } } "); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestDataFlowsOutExpression01() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public void F(int x) { int a = 1, y; int tmp = x + /*<bind>*/ (y = x = 2) /*</bind>*/ + (a = 2); int c = a + 4 + x + y; } }"); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(540171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540171")] [Fact] public void TestIncrement() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/i++/*</bind>*/; M(i); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace1() { var results = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/ System.Console /*</bind>*/ .WriteLine(i); } } "); Assert.False(results.Succeeded); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace3() { var results = CompileAndAnalyzeDataFlowExpression(@" public class A { public class B { public static void M() { } } } class C { static void M(int i) { /*<bind>*/ A.B /*</bind>*/ .M(i); } } "); Assert.False(results.Succeeded); } [WorkItem(543695, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543695")] [Fact] public void FlowAnalysisOnTypeOrNamespace4() { var results = CompileAndAnalyzeDataFlowExpression(@" public class A { public class B { public static void M() { } } } class C { static void M(int i) { /*<bind>*/ A /*</bind>*/ .B.M(i); } } "); Assert.False(results.Succeeded); } [WorkItem(540183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540183")] [Fact] public void DataFlowsOutIncrement01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void M(int i) { /*<bind>*/i++/*</bind>*/; M(i); } } "); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [WorkItem(6359, "DevDiv_Projects/Roslyn")] [Fact] public void DataFlowsOutPreDecrement01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Test { string method(string s, int i) { string[] myvar = new string[i]; myvar[0] = s; /*<bind>*/myvar[--i] = s + i.ToString()/*</bind>*/; return myvar[i]; } }"); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, s, i, myvar", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, s, i, myvar", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void TestBranchOfTernaryOperator() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x ? /*<bind>*/ x /*</bind>*/ : true; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(540832, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540832")] [Fact] public void TestAssignmentExpressionAsBranchOfTernaryOperator() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x; int y = true ? /*<bind>*/ x = 1 /*</bind>*/ : x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestAlwaysAssignedWithTernaryOperator() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a, b, x = 100; /*<bind>*/ int c = true ? a = 1 : b = 2; /*</bind>*/ } }"); Assert.Equal("a, c", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, x, c", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i; i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned05() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) && (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned06() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ a && (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned07() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) && !a /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned08() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) || (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned09() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ a || (b = !a) /*</bind>*/ ? 1 : 2; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned10() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b; int c = /*<bind>*/ (b = a) || !a /*</bind>*/ ? 1 : 2; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned11() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ (b = a) ?? (b = null) /*</bind>*/ ; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned12() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ a ?? (b = null) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned13() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { object a = new object; object b; object c = /*<bind>*/ (b = a) ?? null /*</bind>*/ ; } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned14() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b, c, d, e, f; bool c = (b = a) ? (c = a) : (d = a) ? (e = a) : /*<bind>*/ (f = a) /*</bind>*/; } }"); Assert.Equal("f", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a, b, d", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b, d, f", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned15() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { bool a = true; bool b, c, d, e, f; bool c = (b = a) ? (c = a) : /*<bind>*/ (d = a) ? (e = a) : (f = a) /*</bind>*/; } }"); Assert.Equal("d", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a, b", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a, b, d", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned16() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = B(out a) && B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned17() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = /*<bind>*/B(out a) && B(out b)/*</bind>*/; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned18() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = B(out a) || B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned19() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; bool c = /*<bind>*/B(out a) || B(out b)/*</bind>*/; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned22() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static bool B(out bool b) { b = true; return b; } public static void Main(string[] args) { bool a, b; if (/*<bind>*/B(out a)/*</bind>*/) a = true; else b = true; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssignedAndWrittenInside() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestWrittenInside03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int i; i = /*<bind>*/ int.Parse(args[0].ToString()) /*</bind>*/ ; } }"); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite01() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int x = 3; /*<bind>*/x/*</bind>*/ = 3; } }"); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite02() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void Main(string[] args) { int x = 3; /*<bind>*/x/*</bind>*/ += 3; } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite03() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void M(out int x) { x = 1; } public static void Main(string[] args) { int x = 3; M(out /*<bind>*/x/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReadWrite04() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static void M(ref int x) { x = 1; } public static void Main(string[] args) { int x = 3; M(ref /*<bind>*/x/*</bind>*/); } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.WrittenOutside)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestAssignmentExpressionSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x = ( /*<bind>*/ x = 1 /*</bind>*/ ) + x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestSingleVariableSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x | /*<bind>*/ x /*</bind>*/ ; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestParenthesizedAssignmentExpressionSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { bool x = true; bool y = x | /*<bind>*/ (x = x) /*</bind>*/ | x; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestRefArgumentSelection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int x = 0; Goo(ref /*<bind>*/ x /*</bind>*/ ); System.Console.WriteLine(x); } static void Goo(ref int x) { } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(540066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540066")] [Fact] public void AnalysisOfBadRef() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { /*<bind>*/Main(ref 1)/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void TestAlwaysAssigned20NullCoalescing() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { public static object B(out object b) { b = null; return b; } public static void Main(string[] args) { object a, b; object c = B(out a) ?? B(out /*<bind>*/b/*</bind>*/); } }"); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(528662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528662")] [Fact] public void TestNullCoalescingWithConstNullLeft() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" struct STest { public static string SM() { const string s = null; var ss = ""Q""; var ret = /*<bind>*/( s ?? (ss = ""C""))/*</bind>*/ + ss; return ret; } }"); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("ss", GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Equal("s", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Equal("ss", GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(528662, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528662")] [Fact] public void TestNullCoalescingWithConstNotNullLeft() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class Test { public static string SM() { const string s = ""Not Null""; var ss = ""QC""; var ret = /*<bind>*/ s ?? ss /*</bind>*/ + ""\r\n""; return ret; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("s, ss", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(8935, "DevDiv_Projects/Roslyn")] [Fact] public void TestDefaultOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class Test<T> { public T GetT() { return /*<bind>*/ default(T) /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestTypeOfOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class Test<T> { public short GetT(T t) { if (/*<bind>*/ typeof(T) == typeof(int) /*</bind>*/) return 123; return 456; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestIsOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; struct Test<T> { public string GetT(T t) { if /*<bind>*/(t is string)/*</bind>*/ return ""SSS""; return null; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("t", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void TestAsOperator01() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; struct Test<T> { public string GetT(T t) { string ret = null; if (t is string) ret = /*<bind>*/t as string/*</bind>*/; return ret; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("t", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, t, ret", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, t, ret", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(4028, "DevDiv_Projects/Roslyn")] [Fact] public void TestArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int y = 1; int[,] x = { { /*<bind>*/ y /*</bind>*/ } }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestImplicitStackAllocArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int z = 1; int y = 1; var x = stackalloc[] { /*<bind>*/ y /*</bind>*/ , z++ }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("z, y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestStackAllocArrayInitializer() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static void Main() { int z = 1; int y = 1; var x = stackalloc int[] { /*<bind>*/ y /*</bind>*/ , z++ }; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("z, y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(539286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539286")] [Fact] public void TestAnalysisInFieldInitializers() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static void Main() { Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; f(1); } } "); var results2 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; static void Main() { int r = f(1); } } "); Assert.Equal(GetSymbolNamesJoined(results1.AlwaysAssigned), GetSymbolNamesJoined(results2.AlwaysAssigned)); Assert.Equal(GetSymbolNamesJoined(results1.Captured), GetSymbolNamesJoined(results2.Captured)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedInside), GetSymbolNamesJoined(results2.CapturedInside)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedOutside), GetSymbolNamesJoined(results2.CapturedOutside)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsIn), GetSymbolNamesJoined(results2.DataFlowsIn)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsOut), GetSymbolNamesJoined(results2.DataFlowsOut)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results2.DefinitelyAssignedOnEntry)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results2.DefinitelyAssignedOnExit)); Assert.Equal(GetSymbolNamesJoined(results1.ReadInside), GetSymbolNamesJoined(results2.ReadInside)); Assert.Equal(GetSymbolNamesJoined(results1.ReadOutside), string.Join(", ", new string[] { "f" }.Concat((results2.ReadOutside).Select(symbol => symbol.Name)).OrderBy(name => name))); Assert.Equal(GetSymbolNamesJoined(results1.WrittenInside), GetSymbolNamesJoined(results2.WrittenInside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenOutside), string.Join(", ", new string[] { "f" }.Concat((results2.WrittenOutside).Select(symbol => symbol.Name)).OrderBy(name => name))); } [WorkItem(539286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539286")] [Fact] public void TestAnalysisInSimpleFieldInitializers() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { int x = 1; int y = 1; int z = /*<bind>*/1 + (x=2) + p + y/*</bind>*/; } "); var results2 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { int x = 1; int y = 1; static void Main() { /*<bind>*/1 + (x=2) + p + y/*</bind>*/; } } "); // NOTE: 'f' should not be reported in results1.AlwaysAssigned, this issue will be addressed separately Assert.Equal(GetSymbolNamesJoined(results1.AlwaysAssigned), GetSymbolNamesJoined(results2.AlwaysAssigned)); Assert.Equal(GetSymbolNamesJoined(results1.Captured), GetSymbolNamesJoined(results2.Captured)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedInside), GetSymbolNamesJoined(results2.CapturedInside)); Assert.Equal(GetSymbolNamesJoined(results1.CapturedOutside), GetSymbolNamesJoined(results2.CapturedOutside)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsIn), GetSymbolNamesJoined(results2.DataFlowsIn)); Assert.Equal(GetSymbolNamesJoined(results1.DataFlowsOut), GetSymbolNamesJoined(results2.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results2.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results2.DefinitelyAssignedOnExit)); Assert.Equal(GetSymbolNamesJoined(results1.ReadInside), GetSymbolNamesJoined(results2.ReadInside)); Assert.Equal(GetSymbolNamesJoined(results1.ReadOutside), GetSymbolNamesJoined(results2.ReadOutside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenInside), GetSymbolNamesJoined(results2.WrittenInside)); Assert.Equal(GetSymbolNamesJoined(results1.WrittenOutside), GetSymbolNamesJoined(results2.WrittenOutside)); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void ConstantFieldInitializerExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { const int myLength = /*<bind>*/5/*</bind>*/; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void ConstantFieldInitializerExpression2() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { // NOTE: illegal, but still a region we should handle. const bool myLength = true || ((Func<int, int>)(x => { int y = x; return /*<bind>*/y/*</bind>*/; }))(1) == 2; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("System.Int32 y", dataFlows.DataFlowsIn.Single().ToTestDisplayString()); Assert.Equal("System.Int32 y", dataFlows.ReadInside.Single().ToTestDisplayString()); } [WorkItem(541968, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541968")] [Fact] public void FieldInitializerExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; public class Aa { bool myLength = true || ((Func<int, int>)(x => { int y = x; return /*<bind>*/y/*</bind>*/; }))(1) == 2; } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("System.Int32 y", dataFlows.DataFlowsIn.Single().ToTestDisplayString()); Assert.Equal("System.Int32 y", dataFlows.ReadInside.Single().ToTestDisplayString()); } [WorkItem(542454, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542454")] [Fact] public void IdentifierNameInObjectCreationExpr() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class myClass { static int Main() { myClass oc = new /*<bind>*/myClass/*</bind>*/(); return 0; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(542463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542463")] [Fact] public void MethodGroupInDelegateCreation() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class C { void Method() { System.Action a = new System.Action(/*<bind>*/Method/*</bind>*/); } } "); Assert.Equal("this", dataFlows.ReadInside.Single().Name); } [WorkItem(542771, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542771")] [Fact] public void BindInCaseLabel() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" class TestShapes { static void Main() { color s = color.blue; switch (s) { case true ? /*<bind>*/ color.blue /*</bind>*/ : color.blue: break; default: goto default; } } } enum color { blue, green }"); var tmp = dataFlows.VariablesDeclared; // ensure no exception thrown Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(542915, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542915")] [Fact] public void BindLiteralExprInEnumDecl() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" enum Number { Zero = /*<bind>*/0/*</bind>*/ } "); Assert.True(dataFlows.Succeeded); Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(542944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542944")] [Fact] public void AssignToConst() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main(string[] args) { const string a = null; /*<bind>*/a = null;/*</bind>*/ } } "); Assert.Equal("a", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("args, a", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfUnassignedStructLocal() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { int x; int* px = /*<bind>*/&x/*</bind>*/; } } "); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfAssignedStructLocal() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { int x = 1; int* px = /*<bind>*/&x/*</bind>*/; } } "); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfUnassignedStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(543987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543987")] [Fact] public void TestAddressOfAssignedStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; s.x = 2; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("s", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("s, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestAddressOfAssignedStructField2() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; } class Program { static void Main() { S s; s.x = 2; int* px = /*<bind>*/&s.x/*</bind>*/; } } "); // Really ??? Assert.Equal("s", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("s", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("s", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("s, px", GetSymbolNamesJoined(analysis.WrittenOutside)); } // Make sure that assignment is consistent with address-of. [Fact] public void TestAssignToStructField() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public struct S { public int x; public int y; } class Program { static void Main() { S s; int x = /*<bind>*/s.x = 1/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("s", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact, WorkItem(544314, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544314")] public void TestOmittedLambdaPointerTypeParameter() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; unsafe public class Test { public delegate int D(int* p); public static void Main() { int i = 10; int* p = &i; D d = /*<bind>*/delegate { return *p;}/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("p", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("p", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("p", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i, p", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("i, p", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("p", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i, p, d", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = /*<bind>*/ new MemberInitializerTest() { x = 1, y = 2 } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_LocalAccessed() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { int x = 0, y = 0; var i = /*<bind>*/ new MemberInitializerTest() { x = x, y = y } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, y, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_InvalidAccess() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { var i = /*<bind>*/ new MemberInitializerTest() { x = x, y = y } /*</bind>*/; int x = 0, y = 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("i, x, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_LocalAccessed_InitializerExpressionSyntax() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class MemberInitializerTest { public int x; public int y { get; set; } public static void Main() { int x = 0, y = 0; var i = new MemberInitializerTest() /*<bind>*/ { x = x, y = y } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, y, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_NestedObjectInitializer() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class Goo { public int z; } public class MemberInitializerTest { public int x; public Goo y { get; set; } public static void Main() { int x = 0, z = 0; var i = new MemberInitializerTest() { x = x, y = /*<bind>*/ { z = z } /*</bind>*/ }; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("z", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("z", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, z, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestObjectInitializerExpression_VariableCaptured() { var analysis = CompileAndAnalyzeDataFlowExpression(@" public class Goo { public delegate int D(); public D z; } public class MemberInitializerTest { public int x; public Goo y { get; set; } public static void Main() { int x = 0, z = 0; var i = new MemberInitializerTest() /*<bind>*/ { x = x, y = { z = () => z } } /*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("z", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("z", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, z, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestWithExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable record B(string? X) { static void M1(B b1) { var x = ""hello""; _ = /*<bind>*/b1 with { X = x }/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("b1, x", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { List<int> list = /*<bind>*/ new List<int>() { 1, 2, 3, 4, 5 } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression_LocalAccessed() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { int x = 1; List<int> list = new List<int>() /*<bind>*/ { x } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestCollectionInitializerExpression_ComplexElementInitializer() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public static int Main() { int x = 1; List<int> list = new List<int>() { /*<bind>*/ { x } /*</bind>*/ }; return 0; } } "); // Nice to have: "x" flows in, "x" read inside, "list, x" written outside. Assert.False(analysis.Succeeded); } [Fact] public void TestCollectionInitializerExpression_VariableCaptured() { var analysis = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Collections; class Test { public delegate int D(); public static int Main() { int x = 1; List<D> list = new List<D>() /*<bind>*/ { () => x } /*</bind>*/; return 0; } } "); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("x", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, list", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void ObjectInitializerInField() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class C { public Func<int, int, int> dele; } public class Test { C c = /*<bind>*/new C { dele = delegate(int x, int y) { return x + y; } }/*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact] public void CollectionInitializerInField() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; class C { public Func<int, int, int> dele; } public class Test { List<Func<int, int, int>> list = /*<bind>*/new List<Func<int, int, int>>() { (x, y) => { return x + y; } }/*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact(), WorkItem(529329, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529329")] public void QueryAsFieldInitializer() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; using System.Collections.Generic; using System.Collections; class Test { public IEnumerable e = /*<bind>*/ from x in new[] { 1, 2, 3 } where BadExpression let y = x.ToString() select y /*</bind>*/; } "); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [WorkItem(544361, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544361")] [Fact] public void FullQueryExpression() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System.Linq; class Program { static void Main(string[] args) { var q = /*<bind>*/from arg in args group arg by arg.Length into final select final/*</bind>*/; } }"); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverRead() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); var value = /*<bind>*/x.y/*</bind>*/.z.Value; } }"); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverWritten() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); /*<bind>*/x.y/*</bind>*/.z.Value = 3; } }"); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [WorkItem(669341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669341")] [Fact] public void ReceiverReadAndWritten() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; struct X { public Y y; } struct Y { public Z z; } struct Z { public int Value; } class Test { static void Main() { X x = new X(); /*<bind>*/x.y/*</bind>*/.z.Value += 3; } }"); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); } [Fact] public void UnaryPlus() { // reported at https://social.msdn.microsoft.com/Forums/vstudio/en-US/f5078027-def2-429d-9fef-ab7f240883d2/writteninside-for-unary-operators?forum=roslyn var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Main { static int Main(int a) { /*<bind>*/ return +a; /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [Fact] public void NullCoalescingAssignment() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowMultipleExpressions(@" public class C { public static void Main() { C c; c ??= new C(); object x1; object y1; /*<bind0>*/GetC(x1 = 1).Prop ??= (y1 = 2)/*</bind0>*/; x1.ToString(); y1.ToString(); object x2; object y2; /*<bind1>*/GetC(x2 = 1).Field ??= (y2 = 2)/*</bind1>*/; x2.ToString(); y2.ToString(); } static C GetC(object i) => null; object Prop { get; set; } object Field; } "); var propertyDataFlowAnalysis = dataFlowAnalysisResults.First(); var fieldDataFlowAnalysis = dataFlowAnalysisResults.Skip(1).Single(); assertAllInfo(propertyDataFlowAnalysis, "x1", "y1", "x2", "y2"); assertAllInfo(fieldDataFlowAnalysis, "x2", "y2", "x1", "y1"); void assertAllInfo(DataFlowAnalysis dataFlowAnalysis, string currentX, string currentY, string otherX, string otherY) { Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal(currentX, GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal($"{currentX}, {currentY}", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x1, y1, x2, y2", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal($"{currentX}, {currentY}", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal($"c, {otherX}, {otherY}", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } } [Fact] public void CondAccess_NullCoalescing_DataFlow() { // This test corresponds to ExtractMethodTests.TestFlowStateNullableParameters3 var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { public string M() { string? a = null; string? b = null; return /*<bind>*/(a + b + a)?.ToString()/*</bind>*/ ?? string.Empty; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("this, a, b", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } [Theory] [InlineData("c?.M0(x = 0)")] [InlineData("c!.M0(x = 0)")] public void CondAccess_Equals_DataFlowsOut_01(string leftOperand) { var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { bool M0(object? obj) => false; public static void M(C? c) { int x = 0; if (" + leftOperand + @" == /*<bind>*/c!.M0(x = 0)/*</bind>*/) { x.ToString(); } x.ToString(); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } [Theory] [InlineData("c?.M0(x = 0)")] [InlineData("c!.M0(x = 0)")] public void CondAccess_Equals_DataFlowsOut_02(string leftOperand) { var dataFlowAnalysis = CompileAndAnalyzeDataFlowExpression(@" #nullable enable class C { bool M0(object? obj) => false; public static void M(C? c) { int x = 0; if (" + leftOperand + @" == /*<bind>*/c!.M0(x = 0)/*</bind>*/) { x.ToString(); } } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.AlwaysAssigned)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.DataFlowsOut)); Assert.Equal("c", GetSymbolNamesJoined(dataFlowAnalysis.ReadInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenInside)); Assert.Equal("c, x", GetSymbolNamesJoined(dataFlowAnalysis.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysis.CapturedOutside)); } #endregion #region "Statements" [Fact] public void TestDataReadWrittenIncDecOperator() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static short Main() { short x = 0, y = 1, z = 2; /*<bind>*/ x++; y--; /*</bind>*/ return y; } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.StartPointIsReachable); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTernaryExpressionWithAssignments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ int z = x ? y = 1 : y = 2; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegion() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements( @"class C { public static void Main(string[] args) { int i; return; /*<bind>*/ i = i + 1; /*</bind>*/ int j = i; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegion2() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements( @"class C { public static void Main(string[] args) { string i = 0, j = 0, k = 0, l = 0; goto l1; /*<bind>*/ Console.WriteLine(i); j = 1; l1: Console.WriteLine(j); k = 1; goto l2; Console.WriteLine(k); l = 1; l3: Console.WriteLine(l); i = 1; /*</bind>*/ l2: Console.WriteLine(i + j + k + l); goto l3; } }"); Assert.Equal("j, l", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i, k", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [WorkItem(542231, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542231")] [Fact] public void TestUnreachableRegionInExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression( @"class C { public static bool Main() { int i, j; return false && /*<bind>*/((i = i + 1) == 2 || (j = i) == 3)/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); } [Fact] public void TestDeclarationWithSelfReferenceAndTernaryOperator() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x = true ? 1 : x; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestDeclarationWithTernaryOperatorAndAssignment() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x, z, y = true ? 1 : x = z; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x, z, y", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestDictionaryInitializer() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Goo() { int i, j; /*<bind>*/ var s = new Dictionary<int, int>() {[i = j = 1] = 2 }; /*</bind>*/ System.Console.WriteLine(i + j); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.StartPointIsReachable); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("s", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i, j, s", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("i, j, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } [WorkItem(542435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542435")] [Fact] public void NullArgsToAnalyzeControlFlowStatements() { var compilation = CreateCompilation(@" class C { static void Main() { int i = 10; } } "); var semanticModel = compilation.GetSemanticModel(compilation.SyntaxTrees[0]); var statement = compilation.SyntaxTrees[0].GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().First(); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(statement, null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(null, statement)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeControlFlow(null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow(null, statement)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow(statement, null)); Assert.Throws<ArgumentNullException>(() => semanticModel.AnalyzeDataFlow((StatementSyntax)null)); } [WorkItem(542507, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542507")] [Fact] public void DateFlowAnalyzeForLocalWithInvalidRHS() { // Case 1 var analysis = CompileAndAnalyzeDataFlowStatements(@" using System; public class Test { public delegate int D(); public void goo(ref D d) { /*<bind>*/ d = { return 10;}; /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); // Case 2 analysis = CompileAndAnalyzeDataFlowStatements(@" using System; public class Gen<T> { public void DefaultTest() { /*<bind>*/ object obj = default (new Gen<T>()); /*</bind>*/ } } "); Assert.Equal("obj", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [Fact] public void TestEntryPoints01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F() { goto L1; // 1 /*<bind>*/ L1: ; /*</bind>*/ goto L1; // 2 } }"); Assert.Equal(1, analysis.EntryPoints.Count()); } [Fact] public void TestExitPoints01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { L1: ; // 1 /*<bind>*/ if (x == 0) goto L1; if (x == 1) goto L2; if (x == 3) goto L3; L3: ; /*</bind>*/ L2: ; // 2 } }"); Assert.Equal(2, analysis.ExitPoints.Count()); } [Fact] public void TestRegionCompletesNormally01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ goto L1; /*</bind>*/ L1: ; } }"); Assert.True(analysis.StartPointIsReachable); Assert.False(analysis.EndPointIsReachable); } [Fact] public void TestRegionCompletesNormally02() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ x = 2; /*</bind>*/ } }"); Assert.True(analysis.EndPointIsReachable); } [Fact] public void TestRegionCompletesNormally03() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { public void F(int x) { /*<bind>*/ if (x == 0) return; /*</bind>*/ } }"); Assert.True(analysis.EndPointIsReachable); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestVariablesDeclared01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a; /*<bind>*/ int b; int x, y = 1; { var z = ""a""; } /*</bind>*/ int c; } }"); Assert.Equal("b, x, y, z", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [Fact] public void TestVariablesInitializedWithSelfReference() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int x = x = 1; int y, z = 1; /*</bind>*/ } }"); Assert.Equal("x, y, z", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("x, z", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void AlwaysAssignedUnreachable() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int y; /*<bind>*/ if (x == 1) { y = 2; return; } else { y = 3; throw new Exception(); } /*</bind>*/ int = y; } }"); Assert.Equal("y", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [WorkItem(538170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538170")] [Fact] public void TestVariablesDeclared02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) /*<bind>*/ { int a; int b; int x, y = 1; { string z = ""a""; } int c; } /*</bind>*/ }"); Assert.Equal("a, b, x, y, z, c", GetSymbolNamesJoined(analysis.VariablesDeclared)); } [WorkItem(541280, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541280")] [Fact] public void TestVariablesDeclared03() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F() /*<bind>*/ { int a = 0; long a = 1; } /*</bind>*/ }"); Assert.Equal("a, a", GetSymbolNamesJoined(analysis.VariablesDeclared)); var intsym = analysis.VariablesDeclared.First() as ILocalSymbol; var longsym = analysis.VariablesDeclared.Last() as ILocalSymbol; Assert.Equal("Int32", intsym.Type.Name); Assert.Equal("Int64", longsym.Type.Name); } [WorkItem(539229, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539229")] [Fact] public void UnassignedVariableFlowsOut01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main(string[] args) { int i = 10; /*<bind>*/ int j = j + i; /*</bind>*/ Console.Write(i); Console.Write(j); } }"); Assert.Equal("j", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("j", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i, j", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("i, j", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("j", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestDataFlowsIn01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y = 2; /*<bind>*/ int b = a + x + 3; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("x, a", GetSymbolNamesJoined(analysis.DataFlowsIn)); } [Fact] public void TestOutParameter01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(out T t) where T : class, new() { /*<bind>*/ T t1; Test(out t1); t = t1; /*</bind>*/ System.Console.WriteLine(t1.ToString()); } } "); Assert.Equal("this", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("t, t1", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y; /*<bind>*/ if (x == 1) y = x = 2; /*</bind>*/ int c = a + 4 + x + y; } }"); Assert.Equal("x, y", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [WorkItem(538146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538146")] [Fact] public void TestDataFlowsOut02() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void Test(string[] args) { /*<bind>*/ int s = 10, i = 1; int b = s + i; /*</bind>*/ System.Console.WriteLine(s); System.Console.WriteLine(i); } }"); Assert.Equal("s, i", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut03() { var analysis = CompileAndAnalyzeDataFlowStatements( @"using System.Text; class Program { private static string Main() { StringBuilder builder = new StringBuilder(); /*<bind>*/ builder.Append(""Hello""); builder.Append("" From ""); builder.Append("" Roslyn""); /*</bind>*/ return builder.ToString(); } }"); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut04() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(out int x) { /*<bind>*/ x = 12; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut05() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(out int x) { /*<bind>*/ x = 12; return; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut06() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i = 1; while (b) { /*<bind>*/ i = i + 1; /*</bind>*/ } } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("b", GetSymbolNamesJoined(analysis.ReadOutside)); } [Fact] public void TestDataFlowsOut07() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i; /*<bind>*/ i = 2; goto next; /*</bind>*/ next: int j = i; } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(analysis.ReadOutside)); } [WorkItem(540793, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540793")] [Fact] public void TestDataFlowsOut08() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void F(bool b) { int i = 2; try { /*<bind>*/ i = 1; /*</bind>*/ } finally { int j = i; } } }"); Assert.Equal("i", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut09() { var analysis = CompileAndAnalyzeDataFlowStatements(@"class Program { void Test(string[] args) { int i; string s; /*<bind>*/i = 10; s = args[0] + i.ToString();/*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestDataFlowsOut10() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main(string[] args) { int x = 10; /*<bind>*/ int y; if (x == 10) y = 5; /*</bind>*/ Console.WriteLine(y); } } "); Assert.Equal("y", GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact] public void TestAlwaysAssigned01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a = 1, y = 1; /*<bind>*/ if (x == 2) a = 3; else a = 4; x = 4; if (x == 3) y = 12; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("x, a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssigned02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ const int a = 1; /*</bind>*/ } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [WorkItem(540795, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540795")] [Fact] public void TestAlwaysAssigned03() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Always { public void F() { ushort x = 0, y = 1, z; /*<bind>*/ x++; return; uint z = y; /*</bind>*/ } }"); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestReadInside01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(out T t) where T : class, new() { /*<bind>*/ T t1; Test(out t1); t = t1; /*</bind>*/ System.Console.WriteLine(t1.ToString()); } } "); Assert.Equal("this, t1", GetSymbolNamesJoined(analysis.ReadInside)); } [Fact] public void TestAlwaysAssignedDuplicateVariables() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a, a, b, b; b = 1; /*</bind>*/ } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAccessedInsideOutside() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { int a, b, c, d, e, f, g, h, i; a = 1; c = b = a + x; /*<bind>*/ d = c; e = f = d; /*</bind>*/ g = e; h = i = g; } }"); Assert.Equal("c, d", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Equal("d, e, f", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("x, a, e, g", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, b, c, g, h, i", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void TestAlwaysAssignedThroughParenthesizedExpression() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a = 1, b, c, d, e; b = 2; (c) = 3; ((d)) = 4; /*</bind>*/ } }"); Assert.Equal("a, b, c, d", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedThroughCheckedExpression() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int e, f, g; checked(e) = 5; (unchecked(f)) = 5; /*</bind>*/ } }"); Assert.Equal("e, f", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedUsingAlternateNames() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int green, blue, red, yellow, brown; @green = 1; blu\u0065 = 2; re܏d = 3; yellow\uFFF9 = 4; @brown\uFFF9 = 5; /*</bind>*/ } }"); Assert.Equal("green, blue, red, yellow, brown", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedViaPassingAsOutParameter() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { public void F(int x) { /*<bind>*/ int a; G(out a); /*</bind>*/ } void G(out int x) { x = 1; } }"); Assert.Equal("a", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestAlwaysAssignedWithExcludedAssignment() { var analysis = CompileAndAnalyzeDataFlowStatements(@" partial class C { public void F(int x) { /*<bind>*/ int a, b; G(a = x = 1); H(b = 2); /*</bind>*/ } partial void G(int x); partial void H(int x); partial void H(int x) { } }"); Assert.Equal("b", GetSymbolNamesJoined(analysis.AlwaysAssigned)); } [Fact] public void TestDeclarationWithSelfReference() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { /*<bind>*/ int x = x; /*</bind>*/ } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithAssignments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (x) y = 1; else y = 2; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithConstantCondition() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (true) y = x; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestIfStatementWithNonConstantCondition() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { bool x = true; int y; /*<bind>*/ if (true | x) y = x; /*</bind>*/ y.ToString(); } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } // [Obsolete] // [Fact] // public void TestNonStatementSelection() // { // var analysisResults = CompileAndAnalyzeControlAndDataFlowRegion(@" //class C { // static void Main() // { // // /*<bind>*/ //int // /*</bind>*/ // x = 1; // } //} //"); // var controlFlowAnalysisResults = analysisResults.Item1; // var dataFlowAnalysisResults = analysisResults.Item2; // Assert.True(controlFlowAnalysisResults.Succeeded); // Assert.True(dataFlowAnalysisResults.Succeeded); // Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); // Assert.True(controlFlowAnalysisResults.EndPointIsReachable); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)); // Assert.Equal("x", GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)); // } [Fact] public void TestInvocation() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { int x = 1, y = 1; /*<bind>*/ Goo(x); /*</bind>*/ } static void Goo(int x) { } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestInvocationWithAssignmentInArguments() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { static void Main() { int x = 1, y = 1; /*<bind>*/ Goo(x = y, y = 2); /*</bind>*/ int z = x + y; } static void Goo(int x, int y) { } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact, WorkItem(538979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538979")] public void AssertFromInvalidLocalDeclaration() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; public class MyClass { public static int Main() { variant /*<bind>*/ v = new byte(2) /*</bind>*/; // CS0246 byte b = v; // CS1729 return 1; } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); } [Fact, WorkItem(538979, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538979")] public void AssertFromInvalidKeywordAsExpr() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class B : A { public float M() { /*<bind>*/ { return base; // CS0175 } /*</bind>*/ } } class A {} "); var controlFlowAnalysisResults = analysisResults.Item1; //var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); } [WorkItem(539071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539071")] [Fact] public void AssertFromFoldConstantEnumConversion() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" enum E { x, y, z } class Test { static int Main() { /*<bind>*/ E v = E.x; if (v != (E)((int)E.z - 1)) return 0; /*</bind>*/ return 1; } } "); var controlFlowAnalysisResults = analysisResults.Item1; //var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); } [Fact] public void ByRefParameterNotInAppropriateCollections2() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void Test<T>(ref T t) { /*<bind>*/ T t1 = GetValue<T>(ref t); /*</bind>*/ System.Console.WriteLine(t1.ToString()); } T GetValue<T>(ref T t) { return t; } } "); Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("t1", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("t, t1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, t", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void UnreachableDeclaration() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void F() { /*<bind>*/ int x; /*</bind>*/ System.Console.WriteLine(x); } } "); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void Parameters01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { void F(int x, ref int y, out int z) { /*<bind>*/ y = z = 3; /*</bind>*/ } } "); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(528308, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528308")] [Fact] public void RegionForIfElseIfWithoutElse() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class Test { ushort TestCase(ushort p) { /*<bind>*/ if (p > 0) { return --p; } else if (p < 0) { return ++p; } /*</bind>*/ // else { return 0; } } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Empty(controlFlowAnalysisResults.EntryPoints); Assert.Equal(2, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } // [Obsolete] // [Fact] // public void TestBadRegion() // { // var analysisResults = CompileAndAnalyzeControlAndDataFlowRegion(@" //class C { // static void Main() // { // int a = 1; // int b = 1; // // if(a > 1) // /*<bind>*/ // a = 1; // b = 2; // /*</bind>*/ // } //} //"); // var controlFlowAnalysisResults = analysisResults.Item1; // var dataFlowAnalysisResults = analysisResults.Item2; // Assert.False(controlFlowAnalysisResults.Succeeded); // Assert.False(dataFlowAnalysisResults.Succeeded); // Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); // Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); // Assert.True(controlFlowAnalysisResults.EndPointIsReachable); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.VariablesDeclared)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.AlwaysAssigned)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsIn)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.DataFlowsOut)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.ReadOutside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenInside)); // Assert.Null(GetSymbolNamesSortedAndJoined(dataFlowAnalysisResults.WrittenOutside)); // } [WorkItem(541331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541331")] [Fact] public void AttributeOnAccessorInvalid() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class C { public class AttributeX : Attribute { } public int Prop { get /*<bind>*/{ return 1; }/*</bind>*/ protected [AttributeX] set { } } } "); var controlFlowAnalysisResults = analysisResults.Item1; Assert.Empty(controlFlowAnalysisResults.EntryPoints); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); } [WorkItem(541585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541585")] [Fact] public void BadAssignThis() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" class Program { static void Main(string[] args) { /*<bind>*/ this = new S(); /*</bind>*/ } } struct S { }"); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ReturnStatements.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(528623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528623")] [Fact] public void TestElementAccess01() { var analysis = CompileAndAnalyzeDataFlowStatements(@" public class Test { public void M(long[] p) { var v = new long[] { 1, 2, 3 }; /*<bind>*/ v[0] = p[0]; p[0] = v[1]; /*</bind>*/ v[1] = v[0]; p[2] = p[0]; } } "); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.DataFlowsIn)); // By Design Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.ReadInside)); // By Design Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("p, v", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, p, v", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(541947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541947")] [Fact] public void BindPropertyAccessorBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public int P { get /*<bind>*/ { return 0; } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.False(ctrlFlows.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); } [WorkItem(8926, "DevDiv_Projects/Roslyn")] [WorkItem(542346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542346")] [WorkItem(528775, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528775")] [Fact] public void BindEventAccessorBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public delegate void D(); public event D E { add { /*NA*/ } remove /*<bind>*/ { /*NA*/ } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.True(ctrlFlows.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlows.VariablesDeclared)); } [WorkItem(541980, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541980")] [Fact] public void BindDuplicatedAccessor() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public class A { public int P { get { return 1;} get /*<bind>*/ { return 0; } /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; var tmp = ctrlFlows.EndPointIsReachable; // ensure no exception thrown Assert.Empty(dataFlows.VariablesDeclared); } [WorkItem(543737, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543737")] [Fact] public void BlockSyntaxInAttributeDecl() { { var compilation = CreateCompilation(@" [Attribute(delegate.Class)] public class C { public static int Main () { return 1; } } "); var tree = compilation.SyntaxTrees.First(); var index = tree.GetCompilationUnitRoot().ToFullString().IndexOf(".Class)", StringComparison.Ordinal); var tok = tree.GetCompilationUnitRoot().FindToken(index); var node = tok.Parent as StatementSyntax; Assert.Null(node); } { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" [Attribute(x => { /*<bind>*/int y = 12;/*</bind>*/ })] public class C { public static int Main () { return 1; } } "); Assert.False(results.Item1.Succeeded); Assert.False(results.Item2.Succeeded); } } [Fact, WorkItem(529273, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529273")] public void IncrementDecrementOnNullable() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class C { void M(ref sbyte p1, ref sbyte? p2) { byte? local_0 = 2; short? local_1; ushort non_nullable = 99; /*<bind>*/ p1++; p2 = (sbyte?) (local_0.Value - 1); local_1 = (byte)(p2.Value + 1); var ret = local_1.HasValue ? local_1.Value : 0; --non_nullable; /*</bind>*/ } } "); Assert.Equal("ret", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("p1, p2, local_1, non_nullable, ret", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("p1, local_0, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("p1, p2", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("p1, p2, local_0, local_1, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("p1, p2", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p1, p2, local_1, non_nullable, ret", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, p1, p2, local_0, non_nullable", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(17971, "https://github.com/dotnet/roslyn/issues/17971")] [Fact] public void VariablesDeclaredInBrokenForeach() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" struct S { static void Main(string[] args) { /*<bind>*/ Console.WriteLine(1); foreach () Console.WriteLine(2); /*</bind>*/ } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact] [WorkItem(4950, "https://github.com/dotnet/roslyn/issues/4950")] public void RegionWithUnsafeBlock() { var source = @"using System; class Program { static void Main(string[] args) { object value = args; // start IntPtr p; unsafe { object t = value; p = IntPtr.Zero; } // end Console.WriteLine(p); } } "; foreach (string keyword in new[] { "unsafe", "checked", "unchecked" }) { var compilation = CreateCompilation(source.Replace("unsafe", keyword)); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var stmt1 = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().Where(n => n.ToString() == "IntPtr p;").Single(); var stmt2 = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<StatementSyntax>().Where(n => n.ToString().StartsWith(keyword)).First(); var dataFlowAnalysisResults = model.AnalyzeDataFlow(stmt1, stmt2); Assert.True(dataFlowAnalysisResults.Succeeded); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, value, p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("args, p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("p, t", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } } #endregion #region "lambda" [Fact] [WorkItem(41600, "https://github.com/dotnet/roslyn/pull/41600")] public void DataFlowAnalysisLocalFunctions10() { var dataFlow = CompileAndAnalyzeDataFlowExpression(@" class C { public void M() { bool Dummy(params object[] x) {return true;} try {} catch when (/*<bind>*/TakeOutParam(out var x1)/*</bind>*/ && x1 > 0) { Dummy(x1); } var x4 = 11; Dummy(x4); try {} catch when (TakeOutParam(out var x4) && x4 > 0) { Dummy(x4); } try {} catch when (x6 && TakeOutParam(out var x6)) { Dummy(x6); } try {} catch when (TakeOutParam(out var x7) && x7 > 0) { var x7 = 12; Dummy(x7); } try {} catch when (TakeOutParam(out var x8) && x8 > 0) { Dummy(x8); } System.Console.WriteLine(x8); try {} catch when (TakeOutParam(out var x9) && x9 > 0) { Dummy(x9); try {} catch when (TakeOutParam(out var x9) && x9 > 0) // 2 { Dummy(x9); } } try {} catch when (TakeOutParam(y10, out var x10)) { var y10 = 12; Dummy(y10); } // try {} // catch when (TakeOutParam(y11, out var x11) // { // let y11 = 12; // Dummy(y11); // } try {} catch when (Dummy(TakeOutParam(out var x14), TakeOutParam(out var x14), // 2 x14)) { Dummy(x14); } try {} catch (System.Exception x15) when (Dummy(TakeOutParam(out var x15), x15)) { Dummy(x15); } static bool TakeOutParam(out int x) { x = 123; return true; } static bool TakeOutParam(object y, out int x) { x = 123; return true; } } } "); Assert.True(dataFlow.Succeeded); Assert.Null(GetSymbolNamesJoined(dataFlow.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedOutside)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlow.DataFlowsIn)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnEntry)); Assert.Equal("this, x1", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlow.ReadInside)); Assert.Equal("x1", GetSymbolNamesJoined(dataFlow.WrittenInside)); Assert.Equal("this, x1, x4, x4, x6, x7, x7, x8, x9, x9, y10, x14, x15, x, x", GetSymbolNamesJoined(dataFlow.ReadOutside)); Assert.Equal("this, x, x4, x4, x6, x7, x7, x8, x9, x9, x10, " + "y10, x14, x14, x15, x15, x, y, x", GetSymbolNamesJoined(dataFlow.WrittenOutside)); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void DataFlowAnalysisLocalFunctions9() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" class C { int Testing; void M() { local(); /*<bind>*/ NewMethod(); /*</bind>*/ Testing = 5; void local() { } } void NewMethod() { } }"); var dataFlow = results.dataFlowAnalysis; Assert.True(dataFlow.Succeeded); Assert.Null(GetSymbolNamesJoined(dataFlow.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlow.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlow.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlow.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlow.WrittenOutside)); var controlFlow = results.controlFlowAnalysis; Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions01() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { local(); /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.False(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions02() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ local(); System.Console.WriteLine(0); /*</bind>*/ void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions03() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ local(); void local() { throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions04() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { System.Console.WriteLine(0); local(); void local() { /*<bind>*/ throw null; /*</bind>*/ } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.False(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions05() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { local(); void local() { /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ throw null; } } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] [WorkItem(39946, "https://github.com/dotnet/roslyn/issues/39946")] public void ControlFlowAnalysisLocalFunctions06() { var controlFlow = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { void local() { throw null; } /*<bind>*/ System.Console.WriteLine(0); /*</bind>*/ } }"); Assert.True(controlFlow.Succeeded); Assert.True(controlFlow.StartPointIsReachable); Assert.True(controlFlow.EndPointIsReachable); } [Fact] public void TestReturnStatements03() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; /*<bind>*/ if (x == 1) return; Func<int,int> f = (int i) => { return i+1; }; if (x == 2) return; /*</bind>*/ } }"); Assert.Equal(2, analysis.ExitPoints.Count()); } [Fact] public void TestReturnStatements04() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; if (x == 1) return; Func<int,int> f = (int i) => { /*<bind>*/ return i+1; /*</bind>*/ } ; if (x == 2) return; } }"); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestReturnStatements05() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(int x) { if (x == 0) return; if (x == 1) return; /*<bind>*/ Func<int,int?> f = (int i) => { return i == 1 ? i+1 : null; } ; /*</bind>*/ if (x == 2) return; } }"); Assert.True(analysis.Succeeded); Assert.Empty(analysis.ReturnStatements); } [Fact] public void TestReturnStatements06() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public void F(uint? x) { if (x == null) return; if (x.Value == 1) return; /*<bind>*/ Func<uint?, ulong?> f = (i) => { return i.Value +1; } ; if (x.Value == 2) return; /*</bind>*/ } }"); Assert.True(analysis.Succeeded); Assert.Equal(1, analysis.ExitPoints.Count()); } [WorkItem(541198, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541198")] [Fact] public void TestReturnStatements07() { var analysis = CompileAndAnalyzeControlFlowStatements(@" using System; class C { public int F(int x) { Func<int,int> f = (int i) => { goto XXX; /*<bind>*/ return 1; /*</bind>*/ } ; } }"); Assert.Equal(1, analysis.ExitPoints.Count()); } [Fact] public void TestMultipleLambdaExpressions() { var analysis = CompileAndAnalyzeDataFlowExpression(@" class C { void M() { int i; N(/*<bind>*/() => { M(); }/*</bind>*/, () => { i++; }); } void N(System.Action x, System.Action y) { } }"); Assert.True(analysis.Succeeded); Assert.Equal("this, i", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("this", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("i", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact] public void TestReturnFromLambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; class Program { static void Main(string[] args) { int i = 1; Func<int> lambda = () => { /*<bind>*/return i;/*</bind>*/ }; } } "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, i, lambda", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void DataFlowsOutLambda01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main(string[] args) { int i = 12; D d = () => { /*<bind>*/ i = 14; return; /*</bind>*/ }; int j = i; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void DataFlowsOutLambda02() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main() { int? i = 12; D d = () => { /*<bind>*/ i = 14; /*</bind>*/ return; }; int j = i.Value; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [Fact] public void DataFlowsOutLambda03() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; delegate void D(); class Program { static void Main(string[] args) { int i = 12; D d = () => { /*<bind>*/ i = 14; /*</bind>*/ }; int j = i; } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); } [WorkItem(538984, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538984")] [Fact] public void TestReadInside02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void Method() { System.Func<int, int> a = x => /*<bind>*/x * x/*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, a, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestCaptured02() { var analysis = CompileAndAnalyzeDataFlowStatements(@" using System; class C { int field = 123; public void F(int x) { const int a = 1, y = 1; /*<bind>*/ Func<int> lambda = () => x + y + field; /*</bind>*/ int c = a + 4 + y; } }"); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y, lambda", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); } [Fact, WorkItem(539648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539648"), WorkItem(529185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529185")] public void ReturnsInsideLambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; class Program { delegate R Func<T, R>(T t); static void Main(string[] args) { /*<bind>*/ Func<int, int> f = (arg) => { int s = 3; return s; }; /*</bind>*/ f.Invoke(2); } }"); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Empty(controlFlowAnalysisResults.ReturnStatements); Assert.Equal("f", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, f", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("f, arg, s", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); } [WorkItem(539861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539861")] [Fact] public void VariableDeclaredLambda01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; class Program { delegate void TestDelegate(ref int x); static void Main(string[] args) { /*<bind>*/ TestDelegate testDel = (ref int x) => { }; /*</bind>*/ int p = 2; testDel(ref p); Console.WriteLine(p); } } "); //var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, testDel", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("testDel, x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("testDel, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); } [WorkItem(539861, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539861")] [Fact] public void VariableDeclaredLambda02() { var results1 = CompileAndAnalyzeDataFlowStatements(@" using System; class Program { delegate void TestDelegate(ref int? x); static void Main() { /*<bind>*/ TestDelegate testDel = (ref int? x) => { int y = x; x.Value = 10; }; /*</bind>*/ int? p = 2; testDel(ref p); Console.WriteLine(p); } } "); Assert.Equal("testDel, x, y", GetSymbolNamesJoined(results1.VariablesDeclared)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(results1.Captured)); Assert.Null(GetSymbolNamesJoined(results1.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results1.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results1.DataFlowsIn)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results1.DefinitelyAssignedOnEntry)); Assert.Equal("testDel", GetSymbolNamesJoined(results1.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results1.ReadInside)); Assert.Equal("testDel, p", GetSymbolNamesJoined(results1.ReadOutside)); Assert.Equal("testDel, x, y", GetSymbolNamesJoined(results1.WrittenInside)); Assert.Equal("p", GetSymbolNamesJoined(results1.WrittenOutside)); } [WorkItem(540449, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540449")] [Fact] public void AnalysisInsideLambdas() { var results1 = CompileAndAnalyzeDataFlowExpression(@" using System; class C { static void Main() { Func<int, int> f = p => { int x = 1; int y = 1; return /*<bind>*/1 + (x=2) + p + y/*</bind>*/; }; } } "); Assert.Equal("x", GetSymbolNamesJoined(results1.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(results1.Captured)); Assert.Null(GetSymbolNamesJoined(results1.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results1.CapturedOutside)); Assert.Equal("p, y", GetSymbolNamesJoined(results1.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results1.DataFlowsOut)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results1.DefinitelyAssignedOnEntry)); Assert.Equal("p, x, y", GetSymbolNamesJoined(results1.DefinitelyAssignedOnExit)); Assert.Equal("p, y", GetSymbolNamesJoined(results1.ReadInside)); Assert.Null(GetSymbolNamesJoined(results1.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results1.WrittenInside)); Assert.Equal("f, p, x, y", GetSymbolNamesJoined(results1.WrittenOutside)); } [WorkItem(528622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528622")] [Fact] public void AlwaysAssignedParameterLambda() { var dataFlows = CompileAndAnalyzeDataFlowExpression(@" using System; internal class Test { void M(sbyte[] ary) { /*<bind>*/ ( (Action<short>)(x => { Console.Write(x); }) )(ary[0])/*</bind>*/; } } "); Assert.Null(GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlows.Captured)); Assert.Equal("ary", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("ary, x", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Equal("this, ary", GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [WorkItem(541946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541946")] [Fact] public void LambdaInTernaryWithEmptyBody() { var results = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; public delegate void D(); public class A { void M() { int i = 0; /*<bind>*/ D d = true ? (D)delegate { i++; } : delegate { }; /*</bind>*/ } } "); var ctrlFlows = results.Item1; var dataFlows = results.Item2; Assert.True(ctrlFlows.EndPointIsReachable); Assert.Equal("d", GetSymbolNamesJoined(dataFlows.VariablesDeclared)); Assert.Equal("d", GetSymbolNamesJoined(dataFlows.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.Captured)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlows.DataFlowsOut)); Assert.Equal("this, i", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnEntry)); Assert.Equal("this, i, d", GetSymbolNamesJoined(dataFlows.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlows.ReadInside)); Assert.Equal("i, d", GetSymbolNamesJoined(dataFlows.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlows.ReadOutside)); Assert.Equal("this, i", GetSymbolNamesJoined(dataFlows.WrittenOutside)); } [Fact] public void ForEachVariableInLambda() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class Program { static void Main() { var nums = new int?[] { 4, 5 }; foreach (var num in /*<bind>*/nums/*</bind>*/) { Func<int, int> f = x => x + num.Value; Console.WriteLine(f(0)); } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("num, f, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, f, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543398, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543398")] [Fact] public void LambdaBlockSyntax() { var source = @" using System; class c1 { void M() { var a = 0; foreach(var l in """") { Console.WriteLine(l); a = (int) l; l = (char) a; } Func<int> f = ()=> { var c = a; a = c; return 0; }; var b = 0; Console.WriteLine(b); } }"; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CSharpCompilation.Create("FlowAnalysis", syntaxTrees: new[] { tree }); var model = comp.GetSemanticModel(tree); var methodBlock = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BlockSyntax>().First(); var foreachStatement = methodBlock.DescendantNodes().OfType<ForEachStatementSyntax>().First(); var foreachBlock = foreachStatement.DescendantNodes().OfType<BlockSyntax>().First(); var lambdaExpression = methodBlock.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().First(); var lambdaBlock = lambdaExpression.DescendantNodes().OfType<BlockSyntax>().First(); var flowAnalysis = model.AnalyzeDataFlow(methodBlock); Assert.Equal(4, flowAnalysis.ReadInside.Count()); Assert.Equal(5, flowAnalysis.WrittenInside.Count()); Assert.Equal(5, flowAnalysis.VariablesDeclared.Count()); flowAnalysis = model.AnalyzeDataFlow(foreachBlock); Assert.Equal(2, flowAnalysis.ReadInside.Count()); Assert.Equal(2, flowAnalysis.WrittenInside.Count()); Assert.Equal(0, flowAnalysis.VariablesDeclared.Count()); flowAnalysis = model.AnalyzeDataFlow(lambdaBlock); Assert.Equal(2, flowAnalysis.ReadInside.Count()); Assert.Equal(2, flowAnalysis.WrittenInside.Count()); Assert.Equal(1, flowAnalysis.VariablesDeclared.Count()); } [Fact] public void StaticLambda_01() { var source = @" using System; class C { static void Main() { int x = 42; Action fn = static () => Console.Write(x); fn(); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,48): error CS8820: A static anonymous function cannot contain a reference to 'x'. // Action fn = static () => Console.Write(x); Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(9, 48) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("x", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } [Fact] public void StaticLambda_02() { var source = @" using System; class C { static void Main() { int x = 42; Action fn = static () => { int y = x; x = 43; Console.Write(y); }; fn(); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,21): error CS8820: A static anonymous function cannot contain a reference to 'x'. // int y = x; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(11, 21), // (12,13): error CS8820: A static anonymous function cannot contain a reference to 'x'. // x = 43; Diagnostic(ErrorCode.ERR_StaticAnonymousFunctionCannotCaptureVariable, "x").WithArguments("x").WithLocation(12, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("x, y", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } [Fact] public void StaticLambda_03() { var source = @" using System; class C { public static int x = 42; static void Main() { Action fn = static () => { int y = x; x = 43; Console.Write(y); }; fn(); } } "; verify(source); verify(source.Replace("static (", "(")); void verify(string source) { var verifier = CompileAndVerify(source, parseOptions: TestOptions.Regular9, expectedOutput: "42"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(node); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.ReadInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.WrittenInside)); Assert.Equal("y", GetSymbolNamesJoined(flowAnalysis.VariablesDeclared)); } } #endregion #region "query expressions" [Fact] public void QueryExpression01() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 1, 2, 3, 4 }; /*<bind>*/ var q2 = from x in nums where (x > 2) where x > 3 select x; /*</bind>*/ } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("q2", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, q2", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new sbyte[] { 1, 2, 3, 4 }; var q2 = from x in nums where (x > 2) select /*<bind>*/ x+1 /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression03() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int?[] { 1, 2, null, 4 }; var q2 = from x in nums group x.Value + 1 by /*<bind>*/ x.Value % 2 /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression04() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new uint[] { 1, 2, 3, 4 }; var q2 = from int x in nums where x < 3 select /*<bind>*/ x /*</bind>*/; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void QueryExpression05() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new sbyte[] { 1, 2, 3, 4 }; var q2 = from int x in nums where x < 3 group /*<bind>*/ x /*</bind>*/ by x%2; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, q2, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541916, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541916")] [Fact] public void ForEachVariableInQueryExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 4, 5 }; foreach (var num in nums) { var q = from n in /*<bind>*/ nums /*</bind>*/ select num; } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, q, n", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541945, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541945")] [Fact] public void ForVariableInQueryExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Linq; class Program { static void Main() { var nums = new int[] { 4, 5 }; for (int num = 0; num < 10; num++) { var q = from n in /*<bind>*/ nums /*</bind>*/ select num; } } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("nums, num", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("nums", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("num", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("nums, num, q, n", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541926, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541926")] [Fact] public void Bug8863() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System.Linq; class C { static void Main(string[] args) { /*<bind>*/ var temp = from x in ""abc"" let z = x.ToString() select z into w select w; /*</bind>*/ } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal("temp, x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("temp", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args, temp", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("temp, x, z, w", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void Bug9415() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { var q1 = from x in new int[] { /*<bind>*/4/*</bind>*/, 5 } orderby x select x; } }"); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args, q1, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543546")] [Fact] public void GroupByClause() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System.Linq; public class Test { public static void Main() { var strings = new string[] { }; var q = from s in strings select s into t /*<bind>*/group t by t.Length/*</bind>*/; } }"); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [WorkItem(1291, "https://github.com/dotnet/roslyn/issues/1291")] [Fact] public void CaptureInQuery() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System.Linq; public class Test { public static void Main(int[] data) { int y = 1; { int x = 2; var f2 = from a in data select a + y; var f3 = from a in data where x > 0 select a; var f4 = from a in data let b = 1 where /*<bind>*/M(() => b)/*</bind>*/ select a + b; var f5 = from c in data where M(() => c) select c; } } private static bool M(Func<int> f) => true; }"); var dataFlowAnalysisResults = analysisResults; Assert.Equal("y, x, b", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("b", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Equal("y, x", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); } #endregion query expressions #region "switch statement tests" [Fact] public void LocalInOtherSwitchCase() { var dataFlows = CompileAndAnalyzeDataFlowExpression( @"using System; using System.Linq; public class Test { public static void Main() { int ret = 6; switch (ret) { case 1: int i = 10; break; case 2: var q1 = from j in new int[] { 3, 4 } select /*<bind>*/i/*</bind>*/; break; } } }"); Assert.Empty(dataFlows.DataFlowsOut); } [WorkItem(541639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541639")] [Fact] public void VariableDeclInsideSwitchCaptureInLambdaExpr() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { public static void Main() { switch (10) { default: int i = 10; Func<int> f1 = () => /*<bind>*/i/*</bind>*/; break; } } } "); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i, f1", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(541710, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541710")] [Fact] public void ArrayCreationExprInForEachInsideSwitchSection() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { switch ('2') { default: break; case '2': foreach (var i100 in new int[] {4, /*<bind>*/5/*</bind>*/ }) { } break; } } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Empty(dataFlowAnalysisResults.DataFlowsIn); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Empty(dataFlowAnalysisResults.ReadInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("i100", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void RegionInsideSwitchExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { switch ('2') { default: break; case '2': switch (/*<bind>*/'2'/*</bind>*/) { case '2': break; } break; } } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Empty(dataFlowAnalysisResults.DataFlowsIn); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Empty(dataFlowAnalysisResults.ReadInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void NullableAsSwitchExpression() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" using System; class C { public void F(ulong? p) { /*<bind>*/ switch (p) { case null: break; case 1: goto case null; default: break; } /*</bind>*/ } } "); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("p", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("this, p", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(17281, "https://github.com/dotnet/roslyn/issues/17281")] public void DiscardVsVariablesDeclared() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class A { } class Test { private void Repro(A node) { /*<bind>*/ switch (node) { case A _: break; case Unknown: break; default: return; } /*</bind>*/ } }"); Assert.Empty(dataFlowAnalysisResults.Captured); Assert.Empty(dataFlowAnalysisResults.CapturedInside); Assert.Empty(dataFlowAnalysisResults.CapturedOutside); Assert.Empty(dataFlowAnalysisResults.VariablesDeclared); Assert.Empty(dataFlowAnalysisResults.AlwaysAssigned); Assert.Equal("node", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Empty(dataFlowAnalysisResults.DataFlowsOut); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("node", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Empty(dataFlowAnalysisResults.WrittenInside); Assert.Equal("this, node", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } #endregion #region "Misc." [Fact, WorkItem(11298, "DevDiv_Projects/Roslyn")] public void BaseExpressionSyntax() { var source = @" using System; public class BaseClass { public virtual void MyMeth() { } } public class MyClass : BaseClass { public override void MyMeth() { base.MyMeth(); } delegate BaseClass D(); public void OtherMeth() { D f = () => base; } public static void Main() { } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var invocation = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var flowAnalysis = model.AnalyzeDataFlow(invocation); Assert.Empty(flowAnalysis.Captured); Assert.Empty(flowAnalysis.CapturedInside); Assert.Empty(flowAnalysis.CapturedOutside); Assert.Equal("MyClass this", flowAnalysis.DataFlowsIn.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.DataFlowsOut); Assert.Equal("MyClass this", flowAnalysis.ReadInside.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.WrittenInside); Assert.Equal("MyClass this", flowAnalysis.WrittenOutside.Single().ToTestDisplayString()); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single(); flowAnalysis = model.AnalyzeDataFlow(lambda); Assert.Equal("MyClass this", flowAnalysis.Captured.Single().ToTestDisplayString()); Assert.Equal("MyClass this", flowAnalysis.DataFlowsIn.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.DataFlowsOut); Assert.Equal("MyClass this", flowAnalysis.ReadInside.Single().ToTestDisplayString()); Assert.Empty(flowAnalysis.WrittenInside); Assert.Equal("this, f", GetSymbolNamesJoined(flowAnalysis.WrittenOutside)); } [WorkItem(543101, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543101")] [Fact] public void AnalysisInsideBaseClause() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { A(int x) : this(/*<bind>*/x.ToString()/*</bind>*/) { } A(string x) { } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [WorkItem(543758, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543758")] [Fact] public void BlockSyntaxOfALambdaInAttributeArg() { var controlFlowAnalysisResults = CompileAndAnalyzeControlFlowStatements(@" class Test { [Attrib(() => /*<bind>*/{ }/*</bind>*/)] public static void Main() { } } "); Assert.False(controlFlowAnalysisResults.Succeeded); } [WorkItem(529196, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529196")] [Fact()] public void DefaultValueOfOptionalParam() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowExpression(@" public class Derived { public void Goo(int x = /*<bind>*/ 2 /*</bind>*/) { } } "); Assert.True(dataFlowAnalysisResults.Succeeded); } [Fact] public void GenericStructureCycle() { var source = @"struct S<T> { public S<S<T>> F; } class C { static void M() { S<object> o; } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetFirstNode<StatementSyntax>(tree, root.ToFullString().IndexOf("S<object> o", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); Assert.Equal("o", GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(545372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545372")] [Fact] public void AnalysisInSyntaxError01() { var source = @"using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; class Program { static void Main(string[] args) { Expression<Func<int>> f3 = () => if (args == null) {}; } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetLastNode<StatementSyntax>(tree, root.ToFullString().IndexOf("if", StringComparison.Ordinal)); Assert.Equal("if (args == null) {}", statement.ToFullString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("args, f3", GetSymbolNamesJoined(analysis.WrittenOutside)); } [WorkItem(546964, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546964")] [Fact] public void AnalysisWithMissingMember() { var source = @"class C { void Goo(string[] args) { foreach (var s in args) { this.EditorOperations = 1; } } }"; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetLastNode<StatementSyntax>(tree, root.ToFullString().IndexOf("EditorOperations", StringComparison.Ordinal)); Assert.Equal("this.EditorOperations = 1;", statement.ToString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); var v = analysis.DataFlowsOut; } [Fact, WorkItem(547059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547059")] public void ObjectInitIncompleteCodeInQuery() { var source = @" using System.Collections.Generic; using System.Linq; class Program { static void Main() { var symlist = new List<ISymbol>(); var expList = from s in symlist select new ExportedSymbol() { S } } public interface ISymbol { } public class ExportedSymbol { public ISymbol Symbol; public byte UseBits; } "; var compilation = CreateEmptyCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var statement = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BlockSyntax>().FirstOrDefault(); var expectedtext = @" { var symlist = new List<ISymbol>(); var expList = from s in symlist select new ExportedSymbol() { S } } "; Assert.Equal(expectedtext, statement.ToFullString()); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); } [Fact] public void StaticSetterAssignedInCtor() { var source = @"class C { C() { P = new object(); } static object P { get; set; } }"; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetCompilationUnitRoot(); var statement = GetFirstNode<StatementSyntax>(tree, root.ToFullString().IndexOf("P = new object()", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(statement); Assert.True(analysis.Succeeded); } [Fact] public void FieldBeforeAssignedInStructCtor() { var source = @"struct S { object value; S(object x) { S.Equals(value , value); this.value = null; } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,18): error CS0170: Use of possibly unassigned field 'value' // S.Equals(value , value); Diagnostic(ErrorCode.ERR_UseDefViolationField, "value").WithArguments("value") ); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var root = tree.GetRoot(); var expression = GetLastNode<ExpressionSyntax>(tree, root.ToFullString().IndexOf("value ", StringComparison.Ordinal)); var analysis = model.AnalyzeDataFlow(expression); Assert.True(analysis.Succeeded); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); } [Fact, WorkItem(14110, "https://github.com/dotnet/roslyn/issues/14110")] public void Test14110() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { var (a0, b0) = (1, 2); (var c0, int d0) = (3, 4); bool e0 = a0 is int f0; bool g0 = a0 is var h0; M(out int i0); M(out var j0); /*<bind>*/ var (a, b) = (1, 2); (var c, int d) = (3, 4); bool e = a is int f; bool g = a is var h; M(out int i); M(out var j); /*</bind>*/ var (a1, b1) = (1, 2); (var c1, int d1) = (3, 4); bool e1 = a1 is int f1; bool g1 = a1 is var h1; M(out int i1); M(out var j1); } static void M(out int z) => throw null; } "); Assert.Equal("a, b, c, d, e, f, g, h, i, j", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact, WorkItem(15640, "https://github.com/dotnet/roslyn/issues/15640")] public void Test15640() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" using System; class Programand { static void Main() { foreach (var (a0, b0) in new[] { (1, 2) }) {} /*<bind>*/ foreach (var (a, b) in new[] { (1, 2) }) {} /*</bind>*/ foreach (var (a1, b1) in new[] { (1, 2) }) {} } } "); Assert.Equal("a, b", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); } [Fact] public void RegionAnalysisLocalFunctions() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ void Local() { } /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions2() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ Local(); /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions3() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ Action a = Local; /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions4() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ var a = new Action(Local); /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions5() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { void Local() { /*<bind>*/ int x = 0; x++; x = M(x + 1); /*</bind>*/ } Local(); } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions6() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { var a = new Action(() => { void Local() { /*<bind>*/ int x = 0; x++; x = M(x + 1); /*</bind>*/ } }); a(); } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions7() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { void Local() { } /*<bind>*/ var a = (Action)Local; /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void RegionAnalysisLocalFunctions8() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { static void Main() { int x = 0; void Local() { x++; } Local(); /*<bind>*/ x++; x = M(x + 1); /*</bind>*/ } int M(int i) => i; }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void LocalFuncCapture1() { var results = CompileAndAnalyzeDataFlowStatements(@" public static class SomeClass { private static void Repro( int arg ) { /*<bind>*/int localValue = arg;/*</bind>*/ int LocalCapture() => arg; } }"); Assert.True(results.Succeeded); Assert.Equal("arg", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("arg", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("arg", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("arg", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("arg, localValue", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("localValue", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("arg", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("arg", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("localValue", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture2() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; Local(); /*<bind>*/int y = x;/*</bind>*/ int Local() { x = 0; } } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture3() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; /*<bind>*/int y = x;/*</bind>*/ Local(); int Local() => x; } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture4() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x, y = 0; /*<bind>*/x = y;/*</bind>*/ Local(); int Local() => x; } }"); Assert.True(results.Succeeded); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(results.AlwaysAssigned)); Assert.Equal("y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("this, y", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.UnsafeAddressTaken)); } [Fact] public void LocalFuncCapture5() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { int x = 0; void M() { /*<bind>*/ int L(int a) => x; /*</bind>*/ L(); } }"); Assert.Equal("this", GetSymbolNamesJoined(results.Captured)); Assert.Equal("this", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(results.WrittenOutside)); } [Fact] public void LocalFuncCapture6() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M(int x) { int y; int z; void Local() { /*<bind>*/ x++; y = 0; y++; /*</bind>*/ } Local(); } }"); Assert.Equal("x, y", GetSymbolNamesJoined(results.Captured)); Assert.Equal("x, y", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); // TODO(https://github.com/dotnet/roslyn/issues/14214): This is wrong. // Both x and y should flow out. Assert.Equal("y", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this, x", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.AlwaysAssigned)); } [Fact] public void LocalFuncCapture7() { var results = CompileAndAnalyzeDataFlowStatements(@" class C { void M() { int x; void L() { /*<bind>*/ int y = 0; y++; x = 0; /*</bind>*/ } x++; } }"); Assert.Equal("x", GetSymbolNamesJoined(results.Captured)); Assert.Equal("x", GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("x, y", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("x", GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("this, x", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(results.AlwaysAssigned)); } [Fact, WorkItem(37421, "https://github.com/dotnet/roslyn/issues/37421")] public void LocalFuncCapture8() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { int field = 123; void M(int x) { int a = 1, y = 1; int Outside() => x+field; /*<bind>*/ int Inside() => y; /*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("y", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact, WorkItem(37421, "https://github.com/dotnet/roslyn/issues/37421")] public void LocalFuncCapture9() { var analysis = CompileAndAnalyzeDataFlowStatements(@" class C { int field = 123; void M(int x) { int a = 1, y = 1; int Outside() => x+field; Inside(); /*<bind>*/ int Inside() => y; /*</bind>*/ } }"); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.Captured)); Assert.Equal("y", GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Equal("this, x", GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("this, x, a, y", GetSymbolNamesJoined(analysis.WrittenOutside)); } [Fact] public void AssignmentInsideLocal01() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ x = 1; /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal02() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 1) { x = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal03() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if (false) { x = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); // This is a conservative approximation, ignoring whether the branch containing // the assignment is reachable Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal04() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ x = 1; /*</bind>*/ x = 1; } Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] [WorkItem(39569, "https://github.com/dotnet/roslyn/issues/39569")] public void AssignmentInsideLocal05() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { x = 1; } /*<bind>*/ Local(); /*</bind>*/ System.Console.WriteLine(x); } } "); // Right now region analysis requires bound nodes for each variable and value being // assigned. This doesn't work with the current local function analysis because we only // store the slots, not the full boundnode of every assignment (which is impossible // anyway). This should be: // Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal06() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; /*<bind>*/ void Local() { x = 1; } /*</bind>*/ Local(); System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal07() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; /*<bind>*/ void Local() { x = 1; } Local(); /*</bind>*/ System.Console.WriteLine(x); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal08() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 0) { x = 1; return; } else { y = 1; } /*</bind>*/ } Local(); System.Console.WriteLine(x); System.Console.WriteLine(y); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact] public void AssignmentInsideLocal09() { var dataFlowAnalysisResults = CompileAndAnalyzeDataFlowStatements(@" class Program { static void Main() { int x = 3, y = 4; void Local() { /*<bind>*/ if ("""".Length == 0) { x = 1; return; } else { y = 1; throw new Exception(); } /*</bind>*/ } Local(); System.Console.WriteLine(x); System.Console.WriteLine(y); } } "); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); // N.B. This is not as precise as possible. The branch assigning y is unreachable, so // the result does not technically flow out. This is a conservative approximation. Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); } [Fact, WorkItem(25043, "https://github.com/dotnet/roslyn/issues/25043")] public void FallThroughInSwitch_01() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ switch (true) { case true: void f() { } } /*</bind>*/ } }"); Assert.Equal(0, analysis.EntryPoints.Count()); } [Fact, WorkItem(25043, "https://github.com/dotnet/roslyn/issues/25043")] public void FallThroughInSwitch_02() { var analysis = CompileAndAnalyzeControlFlowStatements(@" class C { void M() { /*<bind>*/ switch (true) { case true when true: void f() { } } /*</bind>*/ } }"); Assert.Equal(0, analysis.EntryPoints.Count()); } [Fact] public void AnalysisOfTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = /*<bind>*/(x, y) == (x = 0, 1)/*</bind>*/; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfNestedTupleInTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = (1, (2, 3)) == (0, /*<bind>*/(x = 0, y)/*</bind>*/); } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfExpressionInTupleEquality() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { void M() { int x = 0; int y = 0; _ = (1, 2) == (0, /*<bind>*/(x = 0) + y/*</bind>*/); } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("y", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x, y", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfMixedDeconstruction() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class A { bool M() { int x = 0; string y; /*<bind>*/ (x, (y, var z)) = (x, ("""", true)) /*</bind>*/ return z; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("z", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x, y, z", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertyGetter_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { int _myProp; int MyProp { get => /*<bind>*/this._myProp;/*</bind>*/ set => this._myProp = value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertySetter_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { int _myProp; int MyProp { get => this._myProp; set => /*<bind>*/this._myProp = value;/*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertyGetter_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { int _myProp; int MyProp { get => /*<bind>*/this._myProp;/*</bind>*/ set => this._myProp = value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfPropertySetter_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { int _myProp; int MyProp { get => this._myProp; set => /*<bind>*/this._myProp = value;/*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventAdder_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { EventHandler _myEvent; event EventHandler MyEvent { add => /*<bind>*/ this._myEvent += value; /*</bind>*/ remove => this._myEvent -= value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventRemover_Inside_ReferenceType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class MyClass { EventHandler _myEvent; event EventHandler MyEvent { add => this._myEvent += value; remove => /*<bind>*/ this._myEvent -= value; /*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventAdder_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { EventHandler _myEvent; event EventHandler MyEvent { add => /*<bind>*/ this._myEvent += value; /*</bind>*/ remove => this._myEvent -= value; } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void AnalysisOfEventRemover_Inside_ValueType() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" struct MyStruct { EventHandler _myEvent; event EventHandler MyEvent { add => this._myEvent += value; remove => /*<bind>*/ this._myEvent -= value; /*</bind>*/ } } "); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("this", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, value", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(27969, "https://github.com/dotnet/roslyn/issues/27969")] public void CodeInInitializer01() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { object P { get; } = Create(nameof(P), /*<bind>*/x => true/*</bind>*/); static object Create(string name, Func<string, bool> f) => throw null; } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(27969, "https://github.com/dotnet/roslyn/issues/27969")] public void CodeInInitializer02() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" using System; class C { object P { get; } = Create(P, /*<bind>*/x => true/*</bind>*/); static object Create(object name, Func<string, bool> f) => throw null; } "); var dataFlowAnalysisResults = analysisResults; Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(19845, "https://github.com/dotnet/roslyn/issues/19845")] public void CodeInInitializer03() { var analysisResults = CompileAndAnalyzeDataFlowExpression(@" class C { static int X { get; set; } int Y = /*<bind>*/X/*</bind>*/; }"); var dataFlowAnalysisResults = analysisResults; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(26028, "https://github.com/dotnet/roslyn/issues/26028")] public void BrokenForeach01() { var source = @"class C { void M() { foreach (var x } } "; var compilation = CreateCompilation(source); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); // The foreach loop is broken, so its embedded statement is filled in during syntax error recovery. It is zero-width. var stmt = tree.GetCompilationUnitRoot().DescendantNodesAndSelf().OfType<ForEachStatementSyntax>().Single().Statement; Assert.Equal(0, stmt.Span.Length); var dataFlowAnalysisResults = model.AnalyzeDataFlow(stmt); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, x", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] [WorkItem(30548, "https://github.com/dotnet/roslyn/issues/30548")] public void SymbolInDataFlowInButNotInReadInside() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp39 { class Program { void Method(out object test) { test = null; var a = test != null; /*<bind>*/if (a) { return; } if (A == a) { test = new object(); }/*</bind>*/ } } }"); var dataFlowAnalysisResults = analysisResults.Item2; Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("test", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("this, test, a", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact, WorkItem(37427, "https://github.com/dotnet/roslyn/issues/37427")] public void RegionWithLocalFunctions() { // local functions inside the region var s1 = @" class A { static void M(int p) { int i, j; i = 1; /*<bind>*/ int L1() => 1; int k; j = i; int L2() => 2; /*</bind>*/ k = j; } } "; // local functions outside the region var s2 = @" class A { static void M(int p) { int i, j; i = 1; int L1() => 1; /*<bind>*/ int k; j = i; /*</bind>*/ int L2() => 2; k = j; } } "; foreach (var s in new[] { s1, s2 }) { var analysisResults = CompileAndAnalyzeDataFlowStatements(s); var dataFlowAnalysisResults = analysisResults; Assert.True(dataFlowAnalysisResults.Succeeded); Assert.Equal("k", GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.Captured)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.CapturedOutside)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Equal("j", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("p, i, k", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } } [Fact] public void TestAddressOfUnassignedStructLocal_02() { // This test demonstrates that "data flow analysis" pays attention to private fields // of structs imported from metadata. var libSource = @" public struct Struct { private string Field; }"; var libraryReference = CreateCompilation(libSource).EmitToImageReference(); var analysis = CompileAndAnalyzeDataFlowExpression(@" class Program { static void Main() { Struct x; // considered not definitely assigned because it has a field Struct * px = /*<bind>*/&x/*</bind>*/; // address taken of an unassigned variable } } ", libraryReference); Assert.Equal("x", GetSymbolNamesJoined(analysis.AlwaysAssigned)); Assert.Null(GetSymbolNamesJoined(analysis.Captured)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedInside)); Assert.Null(GetSymbolNamesJoined(analysis.CapturedOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.UnsafeAddressTaken)); Assert.Null(GetSymbolNamesJoined(analysis.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(analysis.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(analysis.DefinitelyAssignedOnEntry)); Assert.Equal("x", GetSymbolNamesJoined(analysis.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(analysis.ReadInside)); Assert.Null(GetSymbolNamesJoined(analysis.ReadOutside)); Assert.Equal("x", GetSymbolNamesJoined(analysis.WrittenInside)); Assert.Equal("px", GetSymbolNamesJoined(analysis.WrittenOutside)); } #endregion #region "Used Local Functions" [Fact] public void RegionAnalysisUsedLocalFunctions() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ void Local() { } /*</bind>*/ } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Null(GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions2() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions3() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { } void Unused(){ } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions4() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Second(); } void Second() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions5() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions6() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions7() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Second(); } void Second() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions8() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ System.Action a = new System.Action(Local); /*</bind>*/ void Local() { Second(); } void Second() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Second, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions9() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ static void Local() { Sub(); void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions10() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ void Local() { Sub(); static void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions11() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Local(); /*</bind>*/ static void Local() { Sub(); static void Sub() { } } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions12() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions13() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions14() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions15() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions16() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions17() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions18() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { Action a = () => Local(); /*<bind>*/ a(); /*</bind>*/ static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Null(GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadInside)); Assert.Null(GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions19() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = () => Local(); /*</bind>*/ a(); static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Equal("a", GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Equal("a", GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions20() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions21() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ void Local() { Sub(); void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions22() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ static void Local() { } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local", GetSymbolNamesJoined(results.UsedLocalFunctions)); } [Fact] public void RegionAnalysisUsedLocalFunctions23() { var results = CompileAndAnalyzeDataFlowStatements(@" using System; class C { static void Main() { /*<bind>*/ Action a = Local; /*</bind>*/ static void Local() { Sub(); static void Sub(); } } }"); Assert.True(results.Succeeded); Assert.Null(GetSymbolNamesJoined(results.Captured)); Assert.Null(GetSymbolNamesJoined(results.CapturedInside)); Assert.Null(GetSymbolNamesJoined(results.CapturedOutside)); Assert.Equal("a", GetSymbolNamesJoined(results.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(results.DataFlowsOut)); Assert.Null(GetSymbolNamesJoined(results.DefinitelyAssignedOnEntry)); Assert.Equal("a", GetSymbolNamesJoined(results.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(results.ReadInside)); Assert.Equal("a", GetSymbolNamesJoined(results.WrittenInside)); Assert.Null(GetSymbolNamesJoined(results.ReadOutside)); Assert.Null(GetSymbolNamesJoined(results.WrittenOutside)); Assert.Equal("Local, Sub", GetSymbolNamesJoined(results.UsedLocalFunctions)); } #endregion #region "Top level statements" [Fact] public void TestTopLevelStatements() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; /*<bind>*/ Console.Write(1); Console.Write(2); Console.Write(3); Console.Write(4); Console.Write(5); /*</bind>*/ "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(0, controlFlowAnalysisResults.ExitPoints.Count()); Assert.True(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTopLevelStatements_Lambda() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; int i = 1; Func<int> lambda = () => { /*<bind>*/return i;/*</bind>*/ }; "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("i, args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("i, args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("i", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("i, lambda, args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } [Fact] public void TestTopLevelStatements_LambdaCapturingArgs() { var analysisResults = CompileAndAnalyzeControlAndDataFlowStatements(@" using System; using System.Linq; Func<int> lambda = () => { /*<bind>*/return args.Length;/*</bind>*/ }; "); var controlFlowAnalysisResults = analysisResults.Item1; var dataFlowAnalysisResults = analysisResults.Item2; Assert.Equal(0, controlFlowAnalysisResults.EntryPoints.Count()); Assert.Equal(1, controlFlowAnalysisResults.ExitPoints.Count()); Assert.False(controlFlowAnalysisResults.EndPointIsReachable); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.VariablesDeclared)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsIn)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.DataFlowsOut)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnEntry)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.DefinitelyAssignedOnExit)); Assert.Equal("args", GetSymbolNamesJoined(dataFlowAnalysisResults.ReadInside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.ReadOutside)); Assert.Null(GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenInside)); Assert.Equal("lambda, args", GetSymbolNamesJoined(dataFlowAnalysisResults.WrittenOutside)); } #endregion } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Features/Core/Portable/SignatureHelp/AbstractSignatureHelpProvider.SymbolKeySignatureHelpItem.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.Threading; namespace Microsoft.CodeAnalysis.SignatureHelp { internal abstract partial class AbstractSignatureHelpProvider { internal class SymbolKeySignatureHelpItem : SignatureHelpItem, IEquatable<SymbolKeySignatureHelpItem> { public SymbolKey? SymbolKey { get; } public SymbolKeySignatureHelpItem( ISymbol symbol, bool isVariadic, Func<CancellationToken, IEnumerable<TaggedText>>? documentationFactory, IEnumerable<TaggedText> prefixParts, IEnumerable<TaggedText> separatorParts, IEnumerable<TaggedText> suffixParts, IEnumerable<SignatureHelpParameter> parameters, IEnumerable<TaggedText>? descriptionParts) : base(isVariadic, documentationFactory, prefixParts, separatorParts, suffixParts, parameters, descriptionParts) { SymbolKey = symbol?.GetSymbolKey(); } public override bool Equals(object? obj) => Equals(obj as SymbolKeySignatureHelpItem); public bool Equals(SymbolKeySignatureHelpItem? obj) { return ReferenceEquals(this, obj) || (obj?.SymbolKey != null && SymbolKey != null && CodeAnalysis.SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: false).Equals(SymbolKey.Value, obj.SymbolKey.Value)); } public override int GetHashCode() { if (SymbolKey == null) { return 0; } var comparer = CodeAnalysis.SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: false); return comparer.GetHashCode(SymbolKey.Value); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading; namespace Microsoft.CodeAnalysis.SignatureHelp { internal abstract partial class AbstractSignatureHelpProvider { internal class SymbolKeySignatureHelpItem : SignatureHelpItem, IEquatable<SymbolKeySignatureHelpItem> { public SymbolKey? SymbolKey { get; } public SymbolKeySignatureHelpItem( ISymbol symbol, bool isVariadic, Func<CancellationToken, IEnumerable<TaggedText>>? documentationFactory, IEnumerable<TaggedText> prefixParts, IEnumerable<TaggedText> separatorParts, IEnumerable<TaggedText> suffixParts, IEnumerable<SignatureHelpParameter> parameters, IEnumerable<TaggedText>? descriptionParts) : base(isVariadic, documentationFactory, prefixParts, separatorParts, suffixParts, parameters, descriptionParts) { SymbolKey = symbol?.GetSymbolKey(); } public override bool Equals(object? obj) => Equals(obj as SymbolKeySignatureHelpItem); public bool Equals(SymbolKeySignatureHelpItem? obj) { return ReferenceEquals(this, obj) || (obj?.SymbolKey != null && SymbolKey != null && CodeAnalysis.SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: false).Equals(SymbolKey.Value, obj.SymbolKey.Value)); } public override int GetHashCode() { if (SymbolKey == null) { return 0; } var comparer = CodeAnalysis.SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: false); return comparer.GetHashCode(SymbolKey.Value); } } } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Features/Core/Portable/ExtractMethod/IExtractMethodService.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.ExtractMethod { internal interface IExtractMethodService : ILanguageService { Task<ExtractMethodResult> ExtractMethodAsync(Document document, TextSpan textSpan, bool localFunction, OptionSet options = null, CancellationToken cancellationToken = default); } }
// Licensed to the .NET Foundation under one or more 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.ExtractMethod { internal interface IExtractMethodService : ILanguageService { Task<ExtractMethodResult> ExtractMethodAsync(Document document, TextSpan textSpan, bool localFunction, OptionSet options = null, CancellationToken cancellationToken = default); } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Workspaces/CoreTest/SolutionTests/SolutionTestHelpers.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 Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests.Persistence; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { internal static class SolutionTestHelpers { public static Workspace CreateWorkspace(Type[]? additionalParts = null) => new AdhocWorkspace(FeaturesTestCompositions.Features.AddParts(additionalParts).GetHostServices()); public static Workspace CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() { var workspace = CreateWorkspace(new[] { typeof(TestProjectCacheService), typeof(TestTemporaryStorageService) }); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(CacheOptions.RecoverableTreeLengthThreshold, 0))); return workspace; } public static Project AddEmptyProject(Solution solution, string languageName = LanguageNames.CSharp) { var id = ProjectId.CreateNewId(); return solution.AddProject( ProjectInfo.Create( id, VersionStamp.Default, name: "TestProject", assemblyName: "TestProject", language: languageName)).GetRequiredProject(id); } #nullable disable public static void TestProperty<T, TValue>(T instance, Func<T, TValue, T> factory, Func<T, TValue> getter, TValue validNonDefaultValue, bool defaultThrows = false) where T : class { Assert.NotEqual<TValue>(default, validNonDefaultValue); var instanceWithValue = factory(instance, validNonDefaultValue); Assert.Equal(validNonDefaultValue, getter(instanceWithValue)); // the factory returns the unchanged instance if the value is unchanged: var instanceWithValue2 = factory(instanceWithValue, validNonDefaultValue); Assert.Same(instanceWithValue2, instanceWithValue); if (defaultThrows) { Assert.Throws<ArgumentNullException>(() => factory(instance, default)); } else { Assert.NotNull(factory(instance, default)); } } public static void TestListProperty<T, TValue>(T instance, Func<T, IEnumerable<TValue>, T> factory, Func<T, IEnumerable<TValue>> getter, TValue item, bool allowDuplicates) where T : class { var boxedItems = (IEnumerable<TValue>)ImmutableArray.Create(item); TestProperty(instance, factory, getter, boxedItems, defaultThrows: false); var instanceWithNoItem = factory(instance, null); Assert.Empty(getter(instanceWithNoItem)); var instanceWithItem = factory(instanceWithNoItem, boxedItems); // the factory preserves the identity of a boxed immutable array: Assert.Same(boxedItems, getter(instanceWithItem)); Assert.Same(instanceWithNoItem, factory(instanceWithNoItem, null)); Assert.Same(instanceWithNoItem, factory(instanceWithNoItem, Array.Empty<TValue>())); Assert.Same(instanceWithNoItem, factory(instanceWithNoItem, ImmutableArray<TValue>.Empty)); // the factory makes an immutable copy if given a mutable list: var mutableItems = new[] { item }; var instanceWithMutableItems = factory(instanceWithNoItem, mutableItems); var items = getter(instanceWithMutableItems); Assert.NotSame(mutableItems, items); // null item: Assert.Throws<ArgumentNullException>(() => factory(instanceWithNoItem, new TValue[] { item, default })); // duplicate item: if (allowDuplicates) { var boxedDupItems = (IEnumerable<TValue>)ImmutableArray.Create(item, item); Assert.Same(boxedDupItems, getter(factory(instanceWithNoItem, boxedDupItems))); } else { Assert.Throws<ArgumentException>(() => factory(instanceWithNoItem, new TValue[] { item, item })); } } #nullable enable } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests.Persistence; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { internal static class SolutionTestHelpers { public static Workspace CreateWorkspace(Type[]? additionalParts = null) => new AdhocWorkspace(FeaturesTestCompositions.Features.AddParts(additionalParts).GetHostServices()); public static Workspace CreateWorkspaceWithRecoverableSyntaxTreesAndWeakCompilations() { var workspace = CreateWorkspace(new[] { typeof(TestProjectCacheService), typeof(TestTemporaryStorageService) }); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(CacheOptions.RecoverableTreeLengthThreshold, 0))); return workspace; } public static Project AddEmptyProject(Solution solution, string languageName = LanguageNames.CSharp) { var id = ProjectId.CreateNewId(); return solution.AddProject( ProjectInfo.Create( id, VersionStamp.Default, name: "TestProject", assemblyName: "TestProject", language: languageName)).GetRequiredProject(id); } #nullable disable public static void TestProperty<T, TValue>(T instance, Func<T, TValue, T> factory, Func<T, TValue> getter, TValue validNonDefaultValue, bool defaultThrows = false) where T : class { Assert.NotEqual<TValue>(default, validNonDefaultValue); var instanceWithValue = factory(instance, validNonDefaultValue); Assert.Equal(validNonDefaultValue, getter(instanceWithValue)); // the factory returns the unchanged instance if the value is unchanged: var instanceWithValue2 = factory(instanceWithValue, validNonDefaultValue); Assert.Same(instanceWithValue2, instanceWithValue); if (defaultThrows) { Assert.Throws<ArgumentNullException>(() => factory(instance, default)); } else { Assert.NotNull(factory(instance, default)); } } public static void TestListProperty<T, TValue>(T instance, Func<T, IEnumerable<TValue>, T> factory, Func<T, IEnumerable<TValue>> getter, TValue item, bool allowDuplicates) where T : class { var boxedItems = (IEnumerable<TValue>)ImmutableArray.Create(item); TestProperty(instance, factory, getter, boxedItems, defaultThrows: false); var instanceWithNoItem = factory(instance, null); Assert.Empty(getter(instanceWithNoItem)); var instanceWithItem = factory(instanceWithNoItem, boxedItems); // the factory preserves the identity of a boxed immutable array: Assert.Same(boxedItems, getter(instanceWithItem)); Assert.Same(instanceWithNoItem, factory(instanceWithNoItem, null)); Assert.Same(instanceWithNoItem, factory(instanceWithNoItem, Array.Empty<TValue>())); Assert.Same(instanceWithNoItem, factory(instanceWithNoItem, ImmutableArray<TValue>.Empty)); // the factory makes an immutable copy if given a mutable list: var mutableItems = new[] { item }; var instanceWithMutableItems = factory(instanceWithNoItem, mutableItems); var items = getter(instanceWithMutableItems); Assert.NotSame(mutableItems, items); // null item: Assert.Throws<ArgumentNullException>(() => factory(instanceWithNoItem, new TValue[] { item, default })); // duplicate item: if (allowDuplicates) { var boxedDupItems = (IEnumerable<TValue>)ImmutableArray.Create(item, item); Assert.Same(boxedDupItems, getter(factory(instanceWithNoItem, boxedDupItems))); } else { Assert.Throws<ArgumentException>(() => factory(instanceWithNoItem, new TValue[] { item, item })); } } #nullable enable } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/EditorFeatures/VisualBasicTest/BraceMatching/BraceHighlightingTests.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.Editor.Implementation.BraceMatching Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.Tagging Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Tagging Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.BraceMatching <[UseExportProvider]> Public Class BraceHighlightingTests Private Shared Function Enumerable(Of t)(ParamArray array() As t) As IEnumerable(Of t) Return array End Function Private Async Function ProduceTagsAsync(workspace As TestWorkspace, buffer As ITextBuffer, position As Integer) As Tasks.Task(Of IEnumerable(Of ITagSpan(Of BraceHighlightTag))) WpfTestRunner.RequireWpfFact($"{NameOf(BraceHighlightingTests)}.{NameOf(Me.ProduceTagsAsync)} creates asynchronous taggers") Dim producer = New BraceHighlightingViewTaggerProvider( workspace.ExportProvider.GetExportedValue(Of IThreadingContext), workspace.GetService(Of IBraceMatchingService), AsynchronousOperationListenerProvider.NullProvider) Dim doc = buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().FirstOrDefault() Dim context = New TaggerContext(Of BraceHighlightTag)( doc, buffer.CurrentSnapshot, New SnapshotPoint(buffer.CurrentSnapshot, position)) Await producer.GetTestAccessor().ProduceTagsAsync(context) Return context.tagSpans End Function <WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)> Public Async Function TestParens() As Tasks.Task Using workspace = TestWorkspace.CreateVisualBasic( "Module Module1 Function Goo(x As Integer) As Integer End Function End Module") Dim buffer = workspace.Documents.First().GetTextBuffer() ' Before open parens Dim result = Await ProduceTagsAsync(workspace, buffer, 31) Assert.True(result.IsEmpty()) ' At open parens result = Await ProduceTagsAsync(workspace, buffer, 32) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(32, 33), Span.FromBounds(45, 46)))) ' After open parens result = Await ProduceTagsAsync(workspace, buffer, 33) Assert.True(result.IsEmpty()) ' Before close parens result = Await ProduceTagsAsync(workspace, buffer, 44) Assert.True(result.IsEmpty()) ' At close parens result = Await ProduceTagsAsync(workspace, buffer, 45) Assert.True(result.IsEmpty()) ' After close parens result = Await ProduceTagsAsync(workspace, buffer, 46) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(32, 33), Span.FromBounds(45, 46)))) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)> Public Async Function TestNestedTouchingItems() As Tasks.Task Using workspace = TestWorkspace.CreateVisualBasic( "Module Module1 <SomeAttr(New With {.name = ""test""})> Sub Goo() End Sub End Module") Dim buffer = workspace.Documents.First().GetTextBuffer() ' pos 0 on second line is 16 ' Before < Dim result = Await ProduceTagsAsync(workspace, buffer, 19) Assert.True(result.IsEmpty) ' On < result = Await ProduceTagsAsync(workspace, buffer, 20) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(20, 21), Span.FromBounds(56, 57)))) ' After < result = Await ProduceTagsAsync(workspace, buffer, 21) Assert.True(result.IsEmpty) ' Before ( result = Await ProduceTagsAsync(workspace, buffer, 28) Assert.True(result.IsEmpty) ' On ( result = Await ProduceTagsAsync(workspace, buffer, 29) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(29, 30), Span.FromBounds(55, 56)))) ' After ( result = Await ProduceTagsAsync(workspace, buffer, 30) Assert.True(result.IsEmpty) ' Before { result = Await ProduceTagsAsync(workspace, buffer, 38) Assert.True(result.IsEmpty) ' On { result = Await ProduceTagsAsync(workspace, buffer, 39) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(39, 40), Span.FromBounds(54, 55)))) ' After { result = Await ProduceTagsAsync(workspace, buffer, 40) Assert.True(result.IsEmpty) ' x is any character, | is the cursor in the following comments '|"})> result = Await ProduceTagsAsync(workspace, buffer, 53) Assert.True(result.IsEmpty) ' "|})> result = Await ProduceTagsAsync(workspace, buffer, 54) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(48, 49), Span.FromBounds(53, 54)))) ' }|)> result = Await ProduceTagsAsync(workspace, buffer, 55) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(39, 40), Span.FromBounds(54, 55)))) ' })|> result = Await ProduceTagsAsync(workspace, buffer, 56) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(29, 30), Span.FromBounds(55, 56)))) ' })>| result = Await ProduceTagsAsync(workspace, buffer, 57) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(20, 21), Span.FromBounds(56, 57)))) ' })>x| result = Await ProduceTagsAsync(workspace, buffer, 58) Assert.True(result.IsEmpty) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)> Public Async Function TestUnnestedTouchingItems() As Tasks.Task Using workspace = TestWorkspace.CreateVisualBasic( "Module Module1 Dim arr()() As Integer End Module") Dim buffer = workspace.Documents.First().GetTextBuffer() ' x is any character, | is the cursor in the following comments ' |x()() Dim result = Await ProduceTagsAsync(workspace, buffer, 26) Assert.True(result.IsEmpty) ' |()() result = Await ProduceTagsAsync(workspace, buffer, 27) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(27, 28), Span.FromBounds(28, 29)))) ' (|)() result = Await ProduceTagsAsync(workspace, buffer, 28) Assert.True(result.IsEmpty) ' ()|() result = Await ProduceTagsAsync(workspace, buffer, 29) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(27, 28), Span.FromBounds(28, 29), Span.FromBounds(29, 30), Span.FromBounds(30, 31)))) ' ()(|) result = Await ProduceTagsAsync(workspace, buffer, 30) Assert.True(result.IsEmpty) ' ()()| result = Await ProduceTagsAsync(workspace, buffer, 31) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(29, 30), Span.FromBounds(30, 31)))) ' ()()x| result = Await ProduceTagsAsync(workspace, buffer, 32) Assert.True(result.IsEmpty) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)> Public Async Function TestAngles() As Tasks.Task Using workspace = TestWorkspace.CreateVisualBasic( "Module Module1 <Attribute()> Sub Goo() Dim x = 2 > 3 Dim y = 4 > 5 Dim z = <element></element> End Sub End Module") Dim buffer = workspace.Documents.First().GetTextBuffer() Dim line4start = buffer.CurrentSnapshot.GetLineFromLineNumber(3).Start.Position Dim line5start = buffer.CurrentSnapshot.GetLineFromLineNumber(4).Start.Position Dim line6start = buffer.CurrentSnapshot.GetLineFromLineNumber(5).Start.Position ' 2| > 3 Dim result = Await ProduceTagsAsync(workspace, buffer, 15 + line4start) Assert.True(result.IsEmpty) ' 2 |> 3 result = Await ProduceTagsAsync(workspace, buffer, 16 + line4start) Assert.True(result.IsEmpty) ' 2 >| 3 result = Await ProduceTagsAsync(workspace, buffer, 17 + line4start) Assert.True(result.IsEmpty) ' 2 > |3 result = Await ProduceTagsAsync(workspace, buffer, 18 + line4start) Assert.True(result.IsEmpty) ' 4| > 5 result = Await ProduceTagsAsync(workspace, buffer, 15 + line5start) Assert.True(result.IsEmpty) ' 4 |> 5 result = Await ProduceTagsAsync(workspace, buffer, 16 + line5start) Assert.True(result.IsEmpty) ' 4 >| 5 result = Await ProduceTagsAsync(workspace, buffer, 17 + line5start) Assert.True(result.IsEmpty) ' 4 > |5 result = Await ProduceTagsAsync(workspace, buffer, 18 + line5start) Assert.True(result.IsEmpty) ' |<element></element> result = Await ProduceTagsAsync(workspace, buffer, 16 + line6start) Assert.True(result.IsEmpty) ' <element>| </element> result = Await ProduceTagsAsync(workspace, buffer, 25 + line6start) Assert.True(result.IsEmpty) ' <element> |</element> result = Await ProduceTagsAsync(workspace, buffer, 26 + line6start) Assert.True(result.IsEmpty) ' <element></element>| result = Await ProduceTagsAsync(workspace, buffer, 36 + line6start) Assert.True(result.IsEmpty) End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Implementation.BraceMatching Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.CodeAnalysis.Editor.Tagging Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.Shared.TestHooks Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Tagging Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.BraceMatching <[UseExportProvider]> Public Class BraceHighlightingTests Private Shared Function Enumerable(Of t)(ParamArray array() As t) As IEnumerable(Of t) Return array End Function Private Async Function ProduceTagsAsync(workspace As TestWorkspace, buffer As ITextBuffer, position As Integer) As Tasks.Task(Of IEnumerable(Of ITagSpan(Of BraceHighlightTag))) WpfTestRunner.RequireWpfFact($"{NameOf(BraceHighlightingTests)}.{NameOf(Me.ProduceTagsAsync)} creates asynchronous taggers") Dim producer = New BraceHighlightingViewTaggerProvider( workspace.ExportProvider.GetExportedValue(Of IThreadingContext), workspace.GetService(Of IBraceMatchingService), AsynchronousOperationListenerProvider.NullProvider) Dim doc = buffer.CurrentSnapshot.GetRelatedDocumentsWithChanges().FirstOrDefault() Dim context = New TaggerContext(Of BraceHighlightTag)( doc, buffer.CurrentSnapshot, New SnapshotPoint(buffer.CurrentSnapshot, position)) Await producer.GetTestAccessor().ProduceTagsAsync(context) Return context.tagSpans End Function <WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)> Public Async Function TestParens() As Tasks.Task Using workspace = TestWorkspace.CreateVisualBasic( "Module Module1 Function Goo(x As Integer) As Integer End Function End Module") Dim buffer = workspace.Documents.First().GetTextBuffer() ' Before open parens Dim result = Await ProduceTagsAsync(workspace, buffer, 31) Assert.True(result.IsEmpty()) ' At open parens result = Await ProduceTagsAsync(workspace, buffer, 32) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(32, 33), Span.FromBounds(45, 46)))) ' After open parens result = Await ProduceTagsAsync(workspace, buffer, 33) Assert.True(result.IsEmpty()) ' Before close parens result = Await ProduceTagsAsync(workspace, buffer, 44) Assert.True(result.IsEmpty()) ' At close parens result = Await ProduceTagsAsync(workspace, buffer, 45) Assert.True(result.IsEmpty()) ' After close parens result = Await ProduceTagsAsync(workspace, buffer, 46) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(32, 33), Span.FromBounds(45, 46)))) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)> Public Async Function TestNestedTouchingItems() As Tasks.Task Using workspace = TestWorkspace.CreateVisualBasic( "Module Module1 <SomeAttr(New With {.name = ""test""})> Sub Goo() End Sub End Module") Dim buffer = workspace.Documents.First().GetTextBuffer() ' pos 0 on second line is 16 ' Before < Dim result = Await ProduceTagsAsync(workspace, buffer, 19) Assert.True(result.IsEmpty) ' On < result = Await ProduceTagsAsync(workspace, buffer, 20) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(20, 21), Span.FromBounds(56, 57)))) ' After < result = Await ProduceTagsAsync(workspace, buffer, 21) Assert.True(result.IsEmpty) ' Before ( result = Await ProduceTagsAsync(workspace, buffer, 28) Assert.True(result.IsEmpty) ' On ( result = Await ProduceTagsAsync(workspace, buffer, 29) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(29, 30), Span.FromBounds(55, 56)))) ' After ( result = Await ProduceTagsAsync(workspace, buffer, 30) Assert.True(result.IsEmpty) ' Before { result = Await ProduceTagsAsync(workspace, buffer, 38) Assert.True(result.IsEmpty) ' On { result = Await ProduceTagsAsync(workspace, buffer, 39) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(39, 40), Span.FromBounds(54, 55)))) ' After { result = Await ProduceTagsAsync(workspace, buffer, 40) Assert.True(result.IsEmpty) ' x is any character, | is the cursor in the following comments '|"})> result = Await ProduceTagsAsync(workspace, buffer, 53) Assert.True(result.IsEmpty) ' "|})> result = Await ProduceTagsAsync(workspace, buffer, 54) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(48, 49), Span.FromBounds(53, 54)))) ' }|)> result = Await ProduceTagsAsync(workspace, buffer, 55) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(39, 40), Span.FromBounds(54, 55)))) ' })|> result = Await ProduceTagsAsync(workspace, buffer, 56) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(29, 30), Span.FromBounds(55, 56)))) ' })>| result = Await ProduceTagsAsync(workspace, buffer, 57) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(20, 21), Span.FromBounds(56, 57)))) ' })>x| result = Await ProduceTagsAsync(workspace, buffer, 58) Assert.True(result.IsEmpty) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)> Public Async Function TestUnnestedTouchingItems() As Tasks.Task Using workspace = TestWorkspace.CreateVisualBasic( "Module Module1 Dim arr()() As Integer End Module") Dim buffer = workspace.Documents.First().GetTextBuffer() ' x is any character, | is the cursor in the following comments ' |x()() Dim result = Await ProduceTagsAsync(workspace, buffer, 26) Assert.True(result.IsEmpty) ' |()() result = Await ProduceTagsAsync(workspace, buffer, 27) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(27, 28), Span.FromBounds(28, 29)))) ' (|)() result = Await ProduceTagsAsync(workspace, buffer, 28) Assert.True(result.IsEmpty) ' ()|() result = Await ProduceTagsAsync(workspace, buffer, 29) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(27, 28), Span.FromBounds(28, 29), Span.FromBounds(29, 30), Span.FromBounds(30, 31)))) ' ()(|) result = Await ProduceTagsAsync(workspace, buffer, 30) Assert.True(result.IsEmpty) ' ()()| result = Await ProduceTagsAsync(workspace, buffer, 31) Assert.True(result.Select(Function(ts) ts.Span.Span).SetEquals(Enumerable(Span.FromBounds(29, 30), Span.FromBounds(30, 31)))) ' ()()x| result = Await ProduceTagsAsync(workspace, buffer, 32) Assert.True(result.IsEmpty) End Using End Function <WpfFact, Trait(Traits.Feature, Traits.Features.BraceHighlighting)> Public Async Function TestAngles() As Tasks.Task Using workspace = TestWorkspace.CreateVisualBasic( "Module Module1 <Attribute()> Sub Goo() Dim x = 2 > 3 Dim y = 4 > 5 Dim z = <element></element> End Sub End Module") Dim buffer = workspace.Documents.First().GetTextBuffer() Dim line4start = buffer.CurrentSnapshot.GetLineFromLineNumber(3).Start.Position Dim line5start = buffer.CurrentSnapshot.GetLineFromLineNumber(4).Start.Position Dim line6start = buffer.CurrentSnapshot.GetLineFromLineNumber(5).Start.Position ' 2| > 3 Dim result = Await ProduceTagsAsync(workspace, buffer, 15 + line4start) Assert.True(result.IsEmpty) ' 2 |> 3 result = Await ProduceTagsAsync(workspace, buffer, 16 + line4start) Assert.True(result.IsEmpty) ' 2 >| 3 result = Await ProduceTagsAsync(workspace, buffer, 17 + line4start) Assert.True(result.IsEmpty) ' 2 > |3 result = Await ProduceTagsAsync(workspace, buffer, 18 + line4start) Assert.True(result.IsEmpty) ' 4| > 5 result = Await ProduceTagsAsync(workspace, buffer, 15 + line5start) Assert.True(result.IsEmpty) ' 4 |> 5 result = Await ProduceTagsAsync(workspace, buffer, 16 + line5start) Assert.True(result.IsEmpty) ' 4 >| 5 result = Await ProduceTagsAsync(workspace, buffer, 17 + line5start) Assert.True(result.IsEmpty) ' 4 > |5 result = Await ProduceTagsAsync(workspace, buffer, 18 + line5start) Assert.True(result.IsEmpty) ' |<element></element> result = Await ProduceTagsAsync(workspace, buffer, 16 + line6start) Assert.True(result.IsEmpty) ' <element>| </element> result = Await ProduceTagsAsync(workspace, buffer, 25 + line6start) Assert.True(result.IsEmpty) ' <element> |</element> result = Await ProduceTagsAsync(workspace, buffer, 26 + line6start) Assert.True(result.IsEmpty) ' <element></element>| result = Await ProduceTagsAsync(workspace, buffer, 36 + line6start) Assert.True(result.IsEmpty) End Using End Function End Class End Namespace
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Workspaces/Core/Portable/LanguageServices/SemanticsFactsService/SemanticFacts/AbstractSemanticFactsService.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; namespace Microsoft.CodeAnalysis.LanguageServices { internal abstract partial class AbstractSemanticFactsService : ISemanticFacts { public string GenerateNameForExpression(SemanticModel semanticModel, SyntaxNode expression, bool capitalize, CancellationToken cancellationToken) => SemanticFacts.GenerateNameForExpression(semanticModel, expression, capitalize, 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; namespace Microsoft.CodeAnalysis.LanguageServices { internal abstract partial class AbstractSemanticFactsService : ISemanticFacts { public string GenerateNameForExpression(SemanticModel semanticModel, SyntaxNode expression, bool capitalize, CancellationToken cancellationToken) => SemanticFacts.GenerateNameForExpression(semanticModel, expression, capitalize, cancellationToken); } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/VisualStudio/Core/Test/CodeModel/MethodXML/MethodXMLTests_VBInvocations.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.MethodXML Partial Public Class MethodXMLTests <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBInvocations_InvocationWithoutMe() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Goo() End Sub Sub Goo() End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="3"> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <ThisReference/> </Expression> <Name>Goo</Name> </NameRef> </Expression> </MethodCall> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBInvocations_InvocationWithMe() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Me.Goo() End Sub Sub Goo() End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="3"> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <ThisReference/> </Expression> <Name>Goo</Name> </NameRef> </Expression> </MethodCall> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBInvocations_WithArrayInitializer1() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class C $$Sub M() Me.list.AddRange(New String() { "goo", "bar", "baz" }) End Sub Dim list As System.Collections.ArrayList End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="3"> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>list</Name> </NameRef> </Expression> <Name>AddRange</Name> </NameRef> </Expression> <Argument> <Expression> <NewArray> <ArrayType rank="1"> <Type>System.String</Type> </ArrayType> <Bound> <Expression> <Literal> <Number>3</Number> </Literal> </Expression> </Bound> <Expression> <Literal> <String>goo</String> </Literal> </Expression> <Expression> <Literal> <String>bar</String> </Literal> </Expression> <Expression> <Literal> <String>baz</String> </Literal> </Expression> </NewArray> </Expression> </Argument> </MethodCall> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBInvocations_InvokeOnCast() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class C $$Sub M() Dim o As Object = New String("."c, 10) Dim s = CType(o, System.String).ToString() End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>System.Object</Type> <Name>o</Name> <Expression> <NewClass> <Type>System.String</Type> <Argument> <Expression> <Literal> <Char>.</Char> </Literal> </Expression> </Argument> <Argument> <Expression> <Literal> <Number type="System.Int32">10</Number> </Literal> </Expression> </Argument> </NewClass> </Expression> </Local> <Local line="4"> <Type>System.String</Type> <Name>s</Name> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <Cast> <Type>System.String</Type> <Expression> <NameRef variablekind="local"> <Name>o</Name> </NameRef> </Expression> </Cast> </Expression> <Name>ToString</Name> </NameRef> </Expression> </MethodCall> </Expression> </Local> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBInvocations_InvokeFixInCast() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1" EmbedVbCoreRuntime="true"/> <Document> Imports Microsoft.VisualBasic Class C $$Sub M() Dim b = CByte(Fix(10)) End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="4"> <Type>System.Byte</Type> <Name>b</Name> <Expression> <Cast> <Type>System.Byte</Type> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <Literal> <Type>Microsoft.VisualBasic.Conversion</Type> </Literal> </Expression> <Name>Fix</Name> </NameRef> </Expression> <Argument> <Expression> <Literal> <Number type="System.Int32">10</Number> </Literal> </Expression> </Argument> </MethodCall> </Expression> </Cast> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(870422, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/870422")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_MethodCallWithoutTypeQualification() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() c = Global.Microsoft.VisualBasic.ChrW(13) End Sub Private c As String End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="3"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>c</Name> </NameRef> </Expression> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <Literal> <Type>Microsoft.VisualBasic.Strings</Type> </Literal> </Expression> <Name>ChrW</Name> </NameRef> </Expression> <Argument> <Expression> <Literal> <Number type="System.Int32">13</Number> </Literal> </Expression> </Argument> </MethodCall> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.MethodXML Partial Public Class MethodXMLTests <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBInvocations_InvocationWithoutMe() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Goo() End Sub Sub Goo() End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="3"> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <ThisReference/> </Expression> <Name>Goo</Name> </NameRef> </Expression> </MethodCall> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBInvocations_InvocationWithMe() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() Me.Goo() End Sub Sub Goo() End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="3"> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <ThisReference/> </Expression> <Name>Goo</Name> </NameRef> </Expression> </MethodCall> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBInvocations_WithArrayInitializer1() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class C $$Sub M() Me.list.AddRange(New String() { "goo", "bar", "baz" }) End Sub Dim list As System.Collections.ArrayList End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="3"> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>list</Name> </NameRef> </Expression> <Name>AddRange</Name> </NameRef> </Expression> <Argument> <Expression> <NewArray> <ArrayType rank="1"> <Type>System.String</Type> </ArrayType> <Bound> <Expression> <Literal> <Number>3</Number> </Literal> </Expression> </Bound> <Expression> <Literal> <String>goo</String> </Literal> </Expression> <Expression> <Literal> <String>bar</String> </Literal> </Expression> <Expression> <Literal> <String>baz</String> </Literal> </Expression> </NewArray> </Expression> </Argument> </MethodCall> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBInvocations_InvokeOnCast() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class C $$Sub M() Dim o As Object = New String("."c, 10) Dim s = CType(o, System.String).ToString() End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="3"> <Type>System.Object</Type> <Name>o</Name> <Expression> <NewClass> <Type>System.String</Type> <Argument> <Expression> <Literal> <Char>.</Char> </Literal> </Expression> </Argument> <Argument> <Expression> <Literal> <Number type="System.Int32">10</Number> </Literal> </Expression> </Argument> </NewClass> </Expression> </Local> <Local line="4"> <Type>System.String</Type> <Name>s</Name> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <Cast> <Type>System.String</Type> <Expression> <NameRef variablekind="local"> <Name>o</Name> </NameRef> </Expression> </Cast> </Expression> <Name>ToString</Name> </NameRef> </Expression> </MethodCall> </Expression> </Local> </Block> Test(definition, expected) End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBInvocations_InvokeFixInCast() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1" EmbedVbCoreRuntime="true"/> <Document> Imports Microsoft.VisualBasic Class C $$Sub M() Dim b = CByte(Fix(10)) End Sub End Class </Document> </Project> </Workspace> Dim expected = <Block> <Local line="4"> <Type>System.Byte</Type> <Name>b</Name> <Expression> <Cast> <Type>System.Byte</Type> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <Literal> <Type>Microsoft.VisualBasic.Conversion</Type> </Literal> </Expression> <Name>Fix</Name> </NameRef> </Expression> <Argument> <Expression> <Literal> <Number type="System.Int32">10</Number> </Literal> </Expression> </Argument> </MethodCall> </Expression> </Cast> </Expression> </Local> </Block> Test(definition, expected) End Sub <WorkItem(870422, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/870422")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModelMethodXml)> Public Sub TestVBAssignments_MethodCallWithoutTypeQualification() Dim definition = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <CompilationOptions RootNamespace="ClassLibrary1"/> <Document> Public Class Class1 $$Sub M() c = Global.Microsoft.VisualBasic.ChrW(13) End Sub Private c As String End Class </Document> </Project> </Workspace> Dim expected = <Block> <ExpressionStatement line="3"> <Expression> <Assignment> <Expression> <NameRef variablekind="field"> <Expression> <ThisReference/> </Expression> <Name>c</Name> </NameRef> </Expression> <Expression> <MethodCall> <Expression> <NameRef variablekind="method"> <Expression> <Literal> <Type>Microsoft.VisualBasic.Strings</Type> </Literal> </Expression> <Name>ChrW</Name> </NameRef> </Expression> <Argument> <Expression> <Literal> <Number type="System.Int32">13</Number> </Literal> </Expression> </Argument> </MethodCall> </Expression> </Assignment> </Expression> </ExpressionStatement> </Block> Test(definition, expected) End Sub End Class End Namespace
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Compilers/Core/Portable/Symbols/IPointerTypeSymbol.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.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a pointer type such as "int *". Pointer types /// are used only in unsafe code. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IPointerTypeSymbol : ITypeSymbol { /// <summary> /// Gets the type of the storage location that an instance of the pointer type points to. /// </summary> ITypeSymbol PointedAtType { get; } /// <summary> /// Custom modifiers associated with the pointer type, or an empty array if there are none. /// </summary> /// <remarks> /// Some managed languages may represent special information about the pointer type /// as a custom modifier on either the pointer type or the element type, or /// both. /// </remarks> ImmutableArray<CustomModifier> CustomModifiers { 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. using System.Collections.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a pointer type such as "int *". Pointer types /// are used only in unsafe code. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface IPointerTypeSymbol : ITypeSymbol { /// <summary> /// Gets the type of the storage location that an instance of the pointer type points to. /// </summary> ITypeSymbol PointedAtType { get; } /// <summary> /// Custom modifiers associated with the pointer type, or an empty array if there are none. /// </summary> /// <remarks> /// Some managed languages may represent special information about the pointer type /// as a custom modifier on either the pointer type or the element type, or /// both. /// </remarks> ImmutableArray<CustomModifier> CustomModifiers { get; } } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/VisualStudio/Core/Def/Implementation/CommonControls/MemberSelectionViewModel.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.ComponentModel; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls { internal class MemberSelectionViewModel : AbstractNotifyPropertyChanged { private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly ImmutableDictionary<ISymbol, Task<ImmutableArray<ISymbol>>> _symbolToDependentsMap; private readonly ImmutableDictionary<ISymbol, PullMemberUpSymbolViewModel> _symbolToMemberViewMap; public MemberSelectionViewModel( IUIThreadOperationExecutor uiThreadOperationExecutor, ImmutableArray<PullMemberUpSymbolViewModel> members, ImmutableDictionary<ISymbol, Task<ImmutableArray<ISymbol>>> dependentsMap, TypeKind destinationTypeKind = TypeKind.Class) { _uiThreadOperationExecutor = uiThreadOperationExecutor; // Use public property to hook property change events up Members = members; _symbolToDependentsMap = dependentsMap; _symbolToMemberViewMap = members.ToImmutableDictionary(memberViewModel => memberViewModel.Symbol); UpdateMembersBasedOnDestinationKind(destinationTypeKind); } public ImmutableArray<PullMemberUpSymbolViewModel> CheckedMembers => Members.WhereAsArray(m => m.IsChecked && m.IsCheckable); private ImmutableArray<PullMemberUpSymbolViewModel> _members; public ImmutableArray<PullMemberUpSymbolViewModel> Members { get => _members; set { var oldMembers = _members; if (SetProperty(ref _members, value)) { // If we have registered for events before, remove the handlers // to be a good citizen in the world if (!oldMembers.IsDefaultOrEmpty) { foreach (var oldMember in oldMembers) { oldMember.PropertyChanged -= MemberPropertyChangedHandler; } } foreach (var member in _members) { member.PropertyChanged += MemberPropertyChangedHandler; } } } } private void MemberPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(PullMemberUpSymbolViewModel.IsChecked)) { // Hook the CheckedMembers property change to each individual member checked status change NotifyPropertyChanged(nameof(CheckedMembers)); } } public void SelectPublic() => SelectMembers(Members.WhereAsArray(v => v.Symbol.DeclaredAccessibility == Accessibility.Public)); public void SelectAll() => SelectMembers(Members); internal void DeselectAll() => SelectMembers(Members, isChecked: false); public void SelectDependents() { var checkedMembers = Members .WhereAsArray(member => member.IsChecked && member.IsCheckable); var result = _uiThreadOperationExecutor.Execute( title: ServicesVSResources.Pull_Members_Up, defaultDescription: ServicesVSResources.Calculating_dependents, allowCancellation: true, showProgress: true, context => { foreach (var member in Members) { _symbolToDependentsMap[member.Symbol].Wait(context.UserCancellationToken); } }); if (result == UIThreadOperationStatus.Completed) { foreach (var member in checkedMembers) { var membersToSelected = FindDependentsRecursively(member.Symbol).SelectAsArray(symbol => _symbolToMemberViewMap[symbol]); SelectMembers(membersToSelected); } } } public ImmutableArray<(ISymbol member, bool makeAbstract)> GetSelectedMembers() => Members. Where(memberSymbolView => memberSymbolView.IsChecked && memberSymbolView.IsCheckable). SelectAsArray(memberViewModel => (member: memberViewModel.Symbol, makeAbstract: memberViewModel.IsMakeAbstractCheckable && memberViewModel.MakeAbstract)); public void UpdateMembersBasedOnDestinationKind(TypeKind destinationType) { var fields = Members.WhereAsArray(memberViewModel => memberViewModel.Symbol.IsKind(SymbolKind.Field)); var makeAbstractEnabledCheckboxes = Members. WhereAsArray(memberViewModel => !memberViewModel.Symbol.IsKind(SymbolKind.Field) && !memberViewModel.Symbol.IsAbstract); var isInterface = destinationType == TypeKind.Interface; // Disable field check box and make abstract if destination is interface foreach (var member in fields) { member.IsCheckable = !isInterface; member.TooltipText = isInterface ? ServicesVSResources.Interface_cannot_have_field : string.Empty; } foreach (var member in makeAbstractEnabledCheckboxes) { member.IsMakeAbstractCheckable = !isInterface; } } private void SelectMembers(ImmutableArray<PullMemberUpSymbolViewModel> members, bool isChecked = true) { foreach (var member in members.Where(viewModel => viewModel.IsCheckable)) { member.IsChecked = isChecked; } } private ImmutableHashSet<ISymbol> FindDependentsRecursively(ISymbol member) { var queue = new Queue<ISymbol>(); // Under situation like two methods call each other, this hashset is used to // prevent the infinity loop. var visited = new HashSet<ISymbol>(); var result = new HashSet<ISymbol>(); queue.Enqueue(member); visited.Add(member); while (!queue.IsEmpty()) { var currentMember = queue.Dequeue(); result.Add(currentMember); visited.Add(currentMember); foreach (var dependent in _symbolToDependentsMap[currentMember].Result) { if (!visited.Contains(dependent)) { queue.Enqueue(dependent); } } } return result.ToImmutableHashSet(); } } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.PullMemberUp.MainDialog; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CommonControls { internal class MemberSelectionViewModel : AbstractNotifyPropertyChanged { private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly ImmutableDictionary<ISymbol, Task<ImmutableArray<ISymbol>>> _symbolToDependentsMap; private readonly ImmutableDictionary<ISymbol, PullMemberUpSymbolViewModel> _symbolToMemberViewMap; public MemberSelectionViewModel( IUIThreadOperationExecutor uiThreadOperationExecutor, ImmutableArray<PullMemberUpSymbolViewModel> members, ImmutableDictionary<ISymbol, Task<ImmutableArray<ISymbol>>> dependentsMap, TypeKind destinationTypeKind = TypeKind.Class) { _uiThreadOperationExecutor = uiThreadOperationExecutor; // Use public property to hook property change events up Members = members; _symbolToDependentsMap = dependentsMap; _symbolToMemberViewMap = members.ToImmutableDictionary(memberViewModel => memberViewModel.Symbol); UpdateMembersBasedOnDestinationKind(destinationTypeKind); } public ImmutableArray<PullMemberUpSymbolViewModel> CheckedMembers => Members.WhereAsArray(m => m.IsChecked && m.IsCheckable); private ImmutableArray<PullMemberUpSymbolViewModel> _members; public ImmutableArray<PullMemberUpSymbolViewModel> Members { get => _members; set { var oldMembers = _members; if (SetProperty(ref _members, value)) { // If we have registered for events before, remove the handlers // to be a good citizen in the world if (!oldMembers.IsDefaultOrEmpty) { foreach (var oldMember in oldMembers) { oldMember.PropertyChanged -= MemberPropertyChangedHandler; } } foreach (var member in _members) { member.PropertyChanged += MemberPropertyChangedHandler; } } } } private void MemberPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(PullMemberUpSymbolViewModel.IsChecked)) { // Hook the CheckedMembers property change to each individual member checked status change NotifyPropertyChanged(nameof(CheckedMembers)); } } public void SelectPublic() => SelectMembers(Members.WhereAsArray(v => v.Symbol.DeclaredAccessibility == Accessibility.Public)); public void SelectAll() => SelectMembers(Members); internal void DeselectAll() => SelectMembers(Members, isChecked: false); public void SelectDependents() { var checkedMembers = Members .WhereAsArray(member => member.IsChecked && member.IsCheckable); var result = _uiThreadOperationExecutor.Execute( title: ServicesVSResources.Pull_Members_Up, defaultDescription: ServicesVSResources.Calculating_dependents, allowCancellation: true, showProgress: true, context => { foreach (var member in Members) { _symbolToDependentsMap[member.Symbol].Wait(context.UserCancellationToken); } }); if (result == UIThreadOperationStatus.Completed) { foreach (var member in checkedMembers) { var membersToSelected = FindDependentsRecursively(member.Symbol).SelectAsArray(symbol => _symbolToMemberViewMap[symbol]); SelectMembers(membersToSelected); } } } public ImmutableArray<(ISymbol member, bool makeAbstract)> GetSelectedMembers() => Members. Where(memberSymbolView => memberSymbolView.IsChecked && memberSymbolView.IsCheckable). SelectAsArray(memberViewModel => (member: memberViewModel.Symbol, makeAbstract: memberViewModel.IsMakeAbstractCheckable && memberViewModel.MakeAbstract)); public void UpdateMembersBasedOnDestinationKind(TypeKind destinationType) { var fields = Members.WhereAsArray(memberViewModel => memberViewModel.Symbol.IsKind(SymbolKind.Field)); var makeAbstractEnabledCheckboxes = Members. WhereAsArray(memberViewModel => !memberViewModel.Symbol.IsKind(SymbolKind.Field) && !memberViewModel.Symbol.IsAbstract); var isInterface = destinationType == TypeKind.Interface; // Disable field check box and make abstract if destination is interface foreach (var member in fields) { member.IsCheckable = !isInterface; member.TooltipText = isInterface ? ServicesVSResources.Interface_cannot_have_field : string.Empty; } foreach (var member in makeAbstractEnabledCheckboxes) { member.IsMakeAbstractCheckable = !isInterface; } } private void SelectMembers(ImmutableArray<PullMemberUpSymbolViewModel> members, bool isChecked = true) { foreach (var member in members.Where(viewModel => viewModel.IsCheckable)) { member.IsChecked = isChecked; } } private ImmutableHashSet<ISymbol> FindDependentsRecursively(ISymbol member) { var queue = new Queue<ISymbol>(); // Under situation like two methods call each other, this hashset is used to // prevent the infinity loop. var visited = new HashSet<ISymbol>(); var result = new HashSet<ISymbol>(); queue.Enqueue(member); visited.Add(member); while (!queue.IsEmpty()) { var currentMember = queue.Dequeue(); result.Add(currentMember); visited.Add(currentMember); foreach (var dependent in _symbolToDependentsMap[currentMember].Result) { if (!visited.Contains(dependent)) { queue.Enqueue(dependent); } } } return result.ToImmutableHashSet(); } } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/VisualStudio/Core/Def/EditorConfigSettings/SettingsEditorPane.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.Design; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.Internal.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Analyzers.View; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Analyzers.ViewModel; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.View; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.ViewModel; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.View; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.ViewModel; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.TextManager.Interop; using static Microsoft.VisualStudio.VSConstants; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings { internal sealed partial class SettingsEditorPane : WindowPane, IOleComponent, IVsDeferredDocView, IVsLinkedUndoClient, IVsWindowSearch { private readonly IVsEditorAdaptersFactoryService _vsEditorAdaptersFactoryService; private readonly IThreadingContext _threadingContext; private readonly ISettingsAggregator _settingsDataProviderService; private readonly IWpfTableControlProvider _controlProvider; private readonly ITableManagerProvider _tableMangerProvider; private readonly string _fileName; private readonly IVsTextLines _textBuffer; private readonly Workspace _workspace; private uint _componentId; private IOleUndoManager? _undoManager; private SettingsEditorControl? _control; public SettingsEditorPane(IVsEditorAdaptersFactoryService vsEditorAdaptersFactoryService, IThreadingContext threadingContext, ISettingsAggregator settingsDataProviderService, IWpfTableControlProvider controlProvider, ITableManagerProvider tableMangerProvider, string fileName, IVsTextLines textBuffer, Workspace workspace) : base(null) { _vsEditorAdaptersFactoryService = vsEditorAdaptersFactoryService; _threadingContext = threadingContext; _settingsDataProviderService = settingsDataProviderService; _controlProvider = controlProvider; _tableMangerProvider = tableMangerProvider; _fileName = fileName; _textBuffer = textBuffer; _workspace = workspace; } protected override void Initialize() { base.Initialize(); // Create and initialize the editor if (_componentId == default && this.TryGetService<SOleComponentManager, IOleComponentManager>(out var componentManager)) { var componentRegistrationInfo = new[] { new OLECRINFO { cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO)), grfcrf = (uint)_OLECRF.olecrfNeedIdleTime | (uint)_OLECRF.olecrfNeedPeriodicIdleTime, grfcadvf = (uint)_OLECADVF.olecadvfModal | (uint)_OLECADVF.olecadvfRedrawOff | (uint)_OLECADVF.olecadvfWarningsOff, uIdleTimeInterval = 100 } }; var hr = componentManager.FRegisterComponent(this, componentRegistrationInfo, out _componentId); _ = ErrorHandler.Succeeded(hr); } if (this.TryGetService<SOleUndoManager, IOleUndoManager>(out _undoManager)) { var linkCapableUndoMgr = (IVsLinkCapableUndoManager)_undoManager; if (linkCapableUndoMgr is not null) { _ = linkCapableUndoMgr.AdviseLinkedUndoClient(this); } } // hook up our panel _control = new SettingsEditorControl( GetWhitespaceView(), GetCodeStyleView(), GetAnalyzerView(), _workspace, _fileName, _threadingContext, _vsEditorAdaptersFactoryService, _textBuffer); Content = _control; RegisterIndependentView(true); if (this.TryGetService<IMenuCommandService>(out var menuCommandService)) { AddCommand(menuCommandService, GUID_VSStandardCommandSet97, (int)VSStd97CmdID.NewWindow, new EventHandler(OnNewWindow), new EventHandler(OnQueryNewWindow)); AddCommand(menuCommandService, GUID_VSStandardCommandSet97, (int)VSStd97CmdID.ViewCode, new EventHandler(OnViewCode), new EventHandler(OnQueryViewCode)); } ISettingsEditorView GetWhitespaceView() { var dataProvider = _settingsDataProviderService.GetSettingsProvider<WhitespaceSetting>(_fileName); if (dataProvider is null) { throw new InvalidOperationException("Unable to get whitespace settings"); } var viewModel = new WhitespaceViewModel(dataProvider, _controlProvider, _tableMangerProvider); return new WhitespaceSettingsView(viewModel); } ISettingsEditorView GetCodeStyleView() { var dataProvider = _settingsDataProviderService.GetSettingsProvider<CodeStyleSetting>(_fileName); if (dataProvider is null) { throw new InvalidOperationException("Unable to get code style settings"); } var viewModel = new CodeStyleSettingsViewModel(dataProvider, _controlProvider, _tableMangerProvider); return new CodeStyleSettingsView(viewModel); } ISettingsEditorView GetAnalyzerView() { var dataProvider = _settingsDataProviderService.GetSettingsProvider<AnalyzerSetting>(_fileName); if (dataProvider is null) { throw new InvalidOperationException("Unable to get analyzer settings"); } var viewModel = new AnalyzerSettingsViewModel(dataProvider, _controlProvider, _tableMangerProvider); return new AnalyzerSettingsView(viewModel); } } private void OnQueryNewWindow(object sender, EventArgs e) { var command = (OleMenuCommand)sender; command.Enabled = true; } private void OnNewWindow(object sender, EventArgs e) { NewWindow(); } private void OnQueryViewCode(object sender, EventArgs e) { var command = (OleMenuCommand)sender; command.Enabled = true; } private void OnViewCode(object sender, EventArgs e) { ViewCode(); } private void NewWindow() { if (this.TryGetService<SVsUIShellOpenDocument, IVsUIShellOpenDocument>(out var uishellOpenDocument) && this.TryGetService<SVsWindowFrame, IVsWindowFrame>(out var windowFrameOrig)) { var logicalView = Guid.Empty; var hr = uishellOpenDocument.OpenCopyOfStandardEditor(windowFrameOrig, ref logicalView, out var windowFrameNew); if (windowFrameNew != null) { hr = windowFrameNew.Show(); } _ = ErrorHandler.ThrowOnFailure(hr); } } private void ViewCode() { var sourceCodeTextEditorGuid = VsEditorFactoryGuid.TextEditor_guid; // Open the referenced document using our editor. VsShellUtilities.OpenDocumentWithSpecificEditor(this, _fileName, sourceCodeTextEditorGuid, LOGVIEWID_Primary, out _, out _, out var frame); _ = ErrorHandler.ThrowOnFailure(frame.Show()); } protected override void OnClose() { // unhook from Undo related services if (_undoManager != null) { var linkCapableUndoMgr = (IVsLinkCapableUndoManager)_undoManager; if (linkCapableUndoMgr != null) { _ = linkCapableUndoMgr.UnadviseLinkedUndoClient(); } // Throw away the undo stack etc. // It is important to "zombify" the undo manager when the owning object is shutting down. // This is done by calling IVsLifetimeControlledObject.SeverReferencesToOwner on the undoManager. // This call will clear the undo and redo stacks. This is particularly important to do if // your undo units hold references back to your object. It is also important if you use // "mdtStrict" linked undo transactions as this sample does (see IVsLinkedUndoTransactionManager). // When one object involved in linked undo transactions clears its undo/redo stacks, then // the stacks of the other documents involved in the linked transaction will also be cleared. var lco = (IVsLifetimeControlledObject)_undoManager; _ = lco.SeverReferencesToOwner(); _undoManager = null; } if (this.TryGetService<SOleComponentManager, IOleComponentManager>(out var componentManager)) { _ = componentManager.FRevokeComponent(_componentId); } _control?.OnClose(); Dispose(true); base.OnClose(); } public int FDoIdle(uint grfidlef) { if (_control is not null) { _control.SynchronizeSettings(); } return S_OK; } /// <summary> /// Registers an independent view with the IVsTextManager so that it knows /// the user is working with a view over the text buffer. This will trigger /// the text buffer to prompt the user whether to reload the file if it is /// edited outside of the environment. /// </summary> /// <param name="subscribe">True to subscribe, false to unsubscribe</param> private void RegisterIndependentView(bool subscribe) { if (this.TryGetService<SVsTextManager, IVsTextManager>(out var textManager)) { _ = subscribe ? textManager.RegisterIndependentView(this, _textBuffer) : textManager.UnregisterIndependentView(this, _textBuffer); } } /// <summary> /// Helper function used to add commands using IMenuCommandService /// </summary> /// <param name="menuCommandService"> The IMenuCommandService interface.</param> /// <param name="menuGroup"> This guid represents the menu group of the command.</param> /// <param name="cmdID"> The command ID of the command.</param> /// <param name="commandEvent"> An EventHandler which will be called whenever the command is invoked.</param> /// <param name="queryEvent"> An EventHandler which will be called whenever we want to query the status of /// the command. If null is passed in here then no EventHandler will be added.</param> private static void AddCommand(IMenuCommandService menuCommandService, Guid menuGroup, int cmdID, EventHandler commandEvent, EventHandler queryEvent) { // Create the OleMenuCommand from the menu group, command ID, and command event var menuCommandID = new CommandID(menuGroup, cmdID); var command = new OleMenuCommand(commandEvent, menuCommandID); // Add an event handler to BeforeQueryStatus if one was passed in if (null != queryEvent) { command.BeforeQueryStatus += queryEvent; } // Add the command using our IMenuCommandService instance menuCommandService.AddCommand(command); } public int get_DocView(out IntPtr ppUnkDocView) { ppUnkDocView = Marshal.GetIUnknownForObject(this); return S_OK; } public int get_CmdUIGuid(out Guid pGuidCmdId) { pGuidCmdId = SettingsEditorFactory.SettingsEditorFactoryGuid; return S_OK; } public int FReserved1(uint dwReserved, uint message, IntPtr wParam, IntPtr lParam) => S_OK; public int FPreTranslateMessage(MSG[] pMsg) => S_OK; public void OnEnterState(uint uStateID, int fEnter) { } public void OnAppActivate(int fActive, uint dwOtherThreadID) { } public void OnLoseActivation() { } public void OnActivationChange(IOleComponent pic, int fSameComponent, OLECRINFO[] pcrinfo, int fHostIsActivating, OLECHOSTINFO[] pchostinfo, uint dwReserved) { } public int FContinueMessageLoop(uint uReason, IntPtr pvLoopData, MSG[] pMsgPeeked) => S_OK; public int FQueryTerminate(int fPromptUser) => 1; //true public void Terminate() { } public IntPtr HwndGetWindow(uint dwWhich, uint dwReserved) => IntPtr.Zero; public int OnInterveningUnitBlockingLinkedUndo() => E_FAIL; public IVsSearchTask? CreateSearch(uint dwCookie, IVsSearchQuery pSearchQuery, IVsSearchCallback pSearchCallback) { if (_control is not null) { var tables = _control.GetTableControls(); return new SearchTask(dwCookie, pSearchQuery, pSearchCallback, tables, _threadingContext); } return null; } public void ClearSearch() { _threadingContext.ThrowIfNotOnUIThread(); if (_control is not null) { var tables = _control.GetTableControls(); // remove filter on tablar data controls foreach (var tableControl in tables) { _ = tableControl.SetFilter(string.Empty, null); } } } public void ProvideSearchSettings(IVsUIDataSource pSearchSettings) { SetIntValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.ControlMaxWidth, 200); SetIntValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.SearchStartType, (int)VSSEARCHSTARTTYPE.SST_DELAYED); SetIntValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.SearchStartDelay, 100); SetBoolValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.SearchUseMRU, true); SetBoolValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.PrefixFilterMRUItems, false); SetIntValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.MaximumMRUItems, 25); SetStringValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.SearchWatermark, ServicesVSResources.Search_Settings); SetBoolValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.SearchPopupAutoDropdown, false); SetStringValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.ControlBorderThickness, "1"); SetIntValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.SearchProgressType, (int)VSSEARCHPROGRESSTYPE.SPT_INDETERMINATE); void SetBoolValue(IVsUIDataSource source, string property, bool value) { var valueProp = BuiltInPropertyValue.FromBool(value); _ = source.SetValue(property, valueProp); } void SetIntValue(IVsUIDataSource source, string property, int value) { var valueProp = BuiltInPropertyValue.Create(value); _ = source.SetValue(property, valueProp); } void SetStringValue(IVsUIDataSource source, string property, string value) { var valueProp = BuiltInPropertyValue.Create(value); _ = source.SetValue(property, valueProp); } } public bool OnNavigationKeyDown(uint dwNavigationKey, uint dwModifiers) => false; public bool SearchEnabled { get; } = true; public Guid Category { get; } = new Guid("1BE8950F-AF27-4B71-8D54-1F7FFEFDC237"); public IVsEnumWindowSearchFilters? SearchFiltersEnum => null; public IVsEnumWindowSearchOptions? SearchOptionsEnum => 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.ComponentModel.Design; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings; using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.Internal.VisualStudio.PlatformUI; using Microsoft.Internal.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Analyzers.View; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Analyzers.ViewModel; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.View; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.CodeStyle.ViewModel; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.View; using Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Whitespace.ViewModel; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.TextManager.Interop; using static Microsoft.VisualStudio.VSConstants; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings { internal sealed partial class SettingsEditorPane : WindowPane, IOleComponent, IVsDeferredDocView, IVsLinkedUndoClient, IVsWindowSearch { private readonly IVsEditorAdaptersFactoryService _vsEditorAdaptersFactoryService; private readonly IThreadingContext _threadingContext; private readonly ISettingsAggregator _settingsDataProviderService; private readonly IWpfTableControlProvider _controlProvider; private readonly ITableManagerProvider _tableMangerProvider; private readonly string _fileName; private readonly IVsTextLines _textBuffer; private readonly Workspace _workspace; private uint _componentId; private IOleUndoManager? _undoManager; private SettingsEditorControl? _control; public SettingsEditorPane(IVsEditorAdaptersFactoryService vsEditorAdaptersFactoryService, IThreadingContext threadingContext, ISettingsAggregator settingsDataProviderService, IWpfTableControlProvider controlProvider, ITableManagerProvider tableMangerProvider, string fileName, IVsTextLines textBuffer, Workspace workspace) : base(null) { _vsEditorAdaptersFactoryService = vsEditorAdaptersFactoryService; _threadingContext = threadingContext; _settingsDataProviderService = settingsDataProviderService; _controlProvider = controlProvider; _tableMangerProvider = tableMangerProvider; _fileName = fileName; _textBuffer = textBuffer; _workspace = workspace; } protected override void Initialize() { base.Initialize(); // Create and initialize the editor if (_componentId == default && this.TryGetService<SOleComponentManager, IOleComponentManager>(out var componentManager)) { var componentRegistrationInfo = new[] { new OLECRINFO { cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO)), grfcrf = (uint)_OLECRF.olecrfNeedIdleTime | (uint)_OLECRF.olecrfNeedPeriodicIdleTime, grfcadvf = (uint)_OLECADVF.olecadvfModal | (uint)_OLECADVF.olecadvfRedrawOff | (uint)_OLECADVF.olecadvfWarningsOff, uIdleTimeInterval = 100 } }; var hr = componentManager.FRegisterComponent(this, componentRegistrationInfo, out _componentId); _ = ErrorHandler.Succeeded(hr); } if (this.TryGetService<SOleUndoManager, IOleUndoManager>(out _undoManager)) { var linkCapableUndoMgr = (IVsLinkCapableUndoManager)_undoManager; if (linkCapableUndoMgr is not null) { _ = linkCapableUndoMgr.AdviseLinkedUndoClient(this); } } // hook up our panel _control = new SettingsEditorControl( GetWhitespaceView(), GetCodeStyleView(), GetAnalyzerView(), _workspace, _fileName, _threadingContext, _vsEditorAdaptersFactoryService, _textBuffer); Content = _control; RegisterIndependentView(true); if (this.TryGetService<IMenuCommandService>(out var menuCommandService)) { AddCommand(menuCommandService, GUID_VSStandardCommandSet97, (int)VSStd97CmdID.NewWindow, new EventHandler(OnNewWindow), new EventHandler(OnQueryNewWindow)); AddCommand(menuCommandService, GUID_VSStandardCommandSet97, (int)VSStd97CmdID.ViewCode, new EventHandler(OnViewCode), new EventHandler(OnQueryViewCode)); } ISettingsEditorView GetWhitespaceView() { var dataProvider = _settingsDataProviderService.GetSettingsProvider<WhitespaceSetting>(_fileName); if (dataProvider is null) { throw new InvalidOperationException("Unable to get whitespace settings"); } var viewModel = new WhitespaceViewModel(dataProvider, _controlProvider, _tableMangerProvider); return new WhitespaceSettingsView(viewModel); } ISettingsEditorView GetCodeStyleView() { var dataProvider = _settingsDataProviderService.GetSettingsProvider<CodeStyleSetting>(_fileName); if (dataProvider is null) { throw new InvalidOperationException("Unable to get code style settings"); } var viewModel = new CodeStyleSettingsViewModel(dataProvider, _controlProvider, _tableMangerProvider); return new CodeStyleSettingsView(viewModel); } ISettingsEditorView GetAnalyzerView() { var dataProvider = _settingsDataProviderService.GetSettingsProvider<AnalyzerSetting>(_fileName); if (dataProvider is null) { throw new InvalidOperationException("Unable to get analyzer settings"); } var viewModel = new AnalyzerSettingsViewModel(dataProvider, _controlProvider, _tableMangerProvider); return new AnalyzerSettingsView(viewModel); } } private void OnQueryNewWindow(object sender, EventArgs e) { var command = (OleMenuCommand)sender; command.Enabled = true; } private void OnNewWindow(object sender, EventArgs e) { NewWindow(); } private void OnQueryViewCode(object sender, EventArgs e) { var command = (OleMenuCommand)sender; command.Enabled = true; } private void OnViewCode(object sender, EventArgs e) { ViewCode(); } private void NewWindow() { if (this.TryGetService<SVsUIShellOpenDocument, IVsUIShellOpenDocument>(out var uishellOpenDocument) && this.TryGetService<SVsWindowFrame, IVsWindowFrame>(out var windowFrameOrig)) { var logicalView = Guid.Empty; var hr = uishellOpenDocument.OpenCopyOfStandardEditor(windowFrameOrig, ref logicalView, out var windowFrameNew); if (windowFrameNew != null) { hr = windowFrameNew.Show(); } _ = ErrorHandler.ThrowOnFailure(hr); } } private void ViewCode() { var sourceCodeTextEditorGuid = VsEditorFactoryGuid.TextEditor_guid; // Open the referenced document using our editor. VsShellUtilities.OpenDocumentWithSpecificEditor(this, _fileName, sourceCodeTextEditorGuid, LOGVIEWID_Primary, out _, out _, out var frame); _ = ErrorHandler.ThrowOnFailure(frame.Show()); } protected override void OnClose() { // unhook from Undo related services if (_undoManager != null) { var linkCapableUndoMgr = (IVsLinkCapableUndoManager)_undoManager; if (linkCapableUndoMgr != null) { _ = linkCapableUndoMgr.UnadviseLinkedUndoClient(); } // Throw away the undo stack etc. // It is important to "zombify" the undo manager when the owning object is shutting down. // This is done by calling IVsLifetimeControlledObject.SeverReferencesToOwner on the undoManager. // This call will clear the undo and redo stacks. This is particularly important to do if // your undo units hold references back to your object. It is also important if you use // "mdtStrict" linked undo transactions as this sample does (see IVsLinkedUndoTransactionManager). // When one object involved in linked undo transactions clears its undo/redo stacks, then // the stacks of the other documents involved in the linked transaction will also be cleared. var lco = (IVsLifetimeControlledObject)_undoManager; _ = lco.SeverReferencesToOwner(); _undoManager = null; } if (this.TryGetService<SOleComponentManager, IOleComponentManager>(out var componentManager)) { _ = componentManager.FRevokeComponent(_componentId); } _control?.OnClose(); Dispose(true); base.OnClose(); } public int FDoIdle(uint grfidlef) { if (_control is not null) { _control.SynchronizeSettings(); } return S_OK; } /// <summary> /// Registers an independent view with the IVsTextManager so that it knows /// the user is working with a view over the text buffer. This will trigger /// the text buffer to prompt the user whether to reload the file if it is /// edited outside of the environment. /// </summary> /// <param name="subscribe">True to subscribe, false to unsubscribe</param> private void RegisterIndependentView(bool subscribe) { if (this.TryGetService<SVsTextManager, IVsTextManager>(out var textManager)) { _ = subscribe ? textManager.RegisterIndependentView(this, _textBuffer) : textManager.UnregisterIndependentView(this, _textBuffer); } } /// <summary> /// Helper function used to add commands using IMenuCommandService /// </summary> /// <param name="menuCommandService"> The IMenuCommandService interface.</param> /// <param name="menuGroup"> This guid represents the menu group of the command.</param> /// <param name="cmdID"> The command ID of the command.</param> /// <param name="commandEvent"> An EventHandler which will be called whenever the command is invoked.</param> /// <param name="queryEvent"> An EventHandler which will be called whenever we want to query the status of /// the command. If null is passed in here then no EventHandler will be added.</param> private static void AddCommand(IMenuCommandService menuCommandService, Guid menuGroup, int cmdID, EventHandler commandEvent, EventHandler queryEvent) { // Create the OleMenuCommand from the menu group, command ID, and command event var menuCommandID = new CommandID(menuGroup, cmdID); var command = new OleMenuCommand(commandEvent, menuCommandID); // Add an event handler to BeforeQueryStatus if one was passed in if (null != queryEvent) { command.BeforeQueryStatus += queryEvent; } // Add the command using our IMenuCommandService instance menuCommandService.AddCommand(command); } public int get_DocView(out IntPtr ppUnkDocView) { ppUnkDocView = Marshal.GetIUnknownForObject(this); return S_OK; } public int get_CmdUIGuid(out Guid pGuidCmdId) { pGuidCmdId = SettingsEditorFactory.SettingsEditorFactoryGuid; return S_OK; } public int FReserved1(uint dwReserved, uint message, IntPtr wParam, IntPtr lParam) => S_OK; public int FPreTranslateMessage(MSG[] pMsg) => S_OK; public void OnEnterState(uint uStateID, int fEnter) { } public void OnAppActivate(int fActive, uint dwOtherThreadID) { } public void OnLoseActivation() { } public void OnActivationChange(IOleComponent pic, int fSameComponent, OLECRINFO[] pcrinfo, int fHostIsActivating, OLECHOSTINFO[] pchostinfo, uint dwReserved) { } public int FContinueMessageLoop(uint uReason, IntPtr pvLoopData, MSG[] pMsgPeeked) => S_OK; public int FQueryTerminate(int fPromptUser) => 1; //true public void Terminate() { } public IntPtr HwndGetWindow(uint dwWhich, uint dwReserved) => IntPtr.Zero; public int OnInterveningUnitBlockingLinkedUndo() => E_FAIL; public IVsSearchTask? CreateSearch(uint dwCookie, IVsSearchQuery pSearchQuery, IVsSearchCallback pSearchCallback) { if (_control is not null) { var tables = _control.GetTableControls(); return new SearchTask(dwCookie, pSearchQuery, pSearchCallback, tables, _threadingContext); } return null; } public void ClearSearch() { _threadingContext.ThrowIfNotOnUIThread(); if (_control is not null) { var tables = _control.GetTableControls(); // remove filter on tablar data controls foreach (var tableControl in tables) { _ = tableControl.SetFilter(string.Empty, null); } } } public void ProvideSearchSettings(IVsUIDataSource pSearchSettings) { SetIntValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.ControlMaxWidth, 200); SetIntValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.SearchStartType, (int)VSSEARCHSTARTTYPE.SST_DELAYED); SetIntValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.SearchStartDelay, 100); SetBoolValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.SearchUseMRU, true); SetBoolValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.PrefixFilterMRUItems, false); SetIntValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.MaximumMRUItems, 25); SetStringValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.SearchWatermark, ServicesVSResources.Search_Settings); SetBoolValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.SearchPopupAutoDropdown, false); SetStringValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.ControlBorderThickness, "1"); SetIntValue(pSearchSettings, SearchSettingsDataSource.PropertyNames.SearchProgressType, (int)VSSEARCHPROGRESSTYPE.SPT_INDETERMINATE); void SetBoolValue(IVsUIDataSource source, string property, bool value) { var valueProp = BuiltInPropertyValue.FromBool(value); _ = source.SetValue(property, valueProp); } void SetIntValue(IVsUIDataSource source, string property, int value) { var valueProp = BuiltInPropertyValue.Create(value); _ = source.SetValue(property, valueProp); } void SetStringValue(IVsUIDataSource source, string property, string value) { var valueProp = BuiltInPropertyValue.Create(value); _ = source.SetValue(property, valueProp); } } public bool OnNavigationKeyDown(uint dwNavigationKey, uint dwModifiers) => false; public bool SearchEnabled { get; } = true; public Guid Category { get; } = new Guid("1BE8950F-AF27-4B71-8D54-1F7FFEFDC237"); public IVsEnumWindowSearchFilters? SearchFiltersEnum => null; public IVsEnumWindowSearchOptions? SearchOptionsEnum => null; } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/ExpressionEvaluator/Package/ExpressionEvaluatorPackage.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <TargetFramework>net472</TargetFramework> <!-- VSIX --> <GeneratePkgDefFile>true</GeneratePkgDefFile> <IncludeAssemblyInVSIXContainer>false</IncludeAssemblyInVSIXContainer> <IncludeDebugSymbolsInVSIXContainer>false</IncludeDebugSymbolsInVSIXContainer> <IncludeDebugSymbolsInLocalVSIXDeployment>false</IncludeDebugSymbolsInLocalVSIXDeployment> <ExtensionInstallationRoot>$(CommonExtensionInstallationRoot)</ExtensionInstallationRoot> <ExtensionInstallationFolder>Microsoft\ManagedLanguages\VBCSharp\ExpressionEvaluators</ExtensionInstallationFolder> <!-- VS Insertion --> <VisualStudioInsertionComponent>Microsoft.CodeAnalysis.LanguageServices</VisualStudioInsertionComponent> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\VisualStudio\Setup\Roslyn.VisualStudio.Setup.csproj"> <Name>VisualStudioSetup</Name> <ReferenceOutputAssembly>false</ReferenceOutputAssembly> <IncludeOutputGroupsInVSIX>SatelliteDllsProjectOutputGroup</IncludeOutputGroupsInVSIX> <Private>False</Private> </ProjectReference> <ProjectReference Include="..\Core\Source\ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionCompiler.csproj"> <Name>ExpressionCompiler</Name> <IncludeOutputGroupsInVSIX>BuiltProjectOutputGroup;SatelliteDllsProjectOutputGroup</IncludeOutputGroupsInVSIX> <IncludeOutputGroupsInVSIXLocalOnly>DebugSymbolsProjectOutputGroup</IncludeOutputGroupsInVSIXLocalOnly> <ForceIncludeInVSIX>true</ForceIncludeInVSIX> <PkgDefEntry>BindingRedirect</PkgDefEntry> </ProjectReference> <ProjectReference Include="..\Core\Source\FunctionResolver\Microsoft.CodeAnalysis.FunctionResolver.csproj"> <Name>FunctionResolver</Name> <IncludeOutputGroupsInVSIX>BuiltProjectOutputGroup%3bVsdConfigOutputGroup;SatelliteDllsProjectOutputGroup</IncludeOutputGroupsInVSIX> <IncludeOutputGroupsInVSIXLocalOnly>DebugSymbolsProjectOutputGroup</IncludeOutputGroupsInVSIXLocalOnly> <ForceIncludeInVSIX>true</ForceIncludeInVSIX> <AdditionalProperties>TargetFramework=netstandard1.3</AdditionalProperties> <PkgDefEntry>BindingRedirect</PkgDefEntry> </ProjectReference> <ProjectReference Include="..\Core\Source\ResultProvider\Portable\Microsoft.CodeAnalysis.ResultProvider.csproj"> <Name>ResultProvider.Portable</Name> <IncludeOutputGroupsInVSIX>BuiltProjectOutputGroup;SatelliteDllsProjectOutputGroup</IncludeOutputGroupsInVSIX> <IncludeOutputGroupsInVSIXLocalOnly>DebugSymbolsProjectOutputGroup</IncludeOutputGroupsInVSIXLocalOnly> <ForceIncludeInVSIX>true</ForceIncludeInVSIX> <PkgDefEntry>BindingRedirect</PkgDefEntry> </ProjectReference> <ProjectReference Include="..\CSharp\Source\ExpressionCompiler\Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.csproj"> <Name>CSharpExpressionCompiler</Name> <IncludeOutputGroupsInVSIX>BuiltProjectOutputGroup%3bVsdConfigOutputGroup;SatelliteDllsProjectOutputGroup</IncludeOutputGroupsInVSIX> <IncludeOutputGroupsInVSIXLocalOnly>DebugSymbolsProjectOutputGroup</IncludeOutputGroupsInVSIXLocalOnly> <ForceIncludeInVSIX>true</ForceIncludeInVSIX> <PkgDefEntry>BindingRedirect</PkgDefEntry> </ProjectReference> <ProjectReference Include="..\CSharp\Source\ResultProvider\Portable\Microsoft.CodeAnalysis.CSharp.ResultProvider.csproj"> <Name>CSharpResultProvider.Portable</Name> <IncludeOutputGroupsInVSIX>BuiltProjectOutputGroup%3bVsdConfigOutputGroup;SatelliteDllsProjectOutputGroup</IncludeOutputGroupsInVSIX> <IncludeOutputGroupsInVSIXLocalOnly>DebugSymbolsProjectOutputGroup</IncludeOutputGroupsInVSIXLocalOnly> <ForceIncludeInVSIX>true</ForceIncludeInVSIX> <PkgDefEntry>BindingRedirect</PkgDefEntry> </ProjectReference> <ProjectReference Include="..\VisualBasic\Source\ExpressionCompiler\Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.vbproj"> <Name>BasicExpressionCompiler</Name> <IncludeOutputGroupsInVSIX>BuiltProjectOutputGroup%3bVsdConfigOutputGroup;SatelliteDllsProjectOutputGroup</IncludeOutputGroupsInVSIX> <IncludeOutputGroupsInVSIXLocalOnly>DebugSymbolsProjectOutputGroup</IncludeOutputGroupsInVSIXLocalOnly> <ForceIncludeInVSIX>true</ForceIncludeInVSIX> <PkgDefEntry>BindingRedirect</PkgDefEntry> </ProjectReference> <ProjectReference Include="..\VisualBasic\Source\ResultProvider\Portable\Microsoft.CodeAnalysis.VisualBasic.ResultProvider.vbproj"> <Name>BasicResultProvider.Portable</Name> <IncludeOutputGroupsInVSIX>BuiltProjectOutputGroup%3bVsdConfigOutputGroup;SatelliteDllsProjectOutputGroup</IncludeOutputGroupsInVSIX> <IncludeOutputGroupsInVSIXLocalOnly>DebugSymbolsProjectOutputGroup</IncludeOutputGroupsInVSIXLocalOnly> <ForceIncludeInVSIX>true</ForceIncludeInVSIX> <PkgDefEntry>BindingRedirect</PkgDefEntry> </ProjectReference> </ItemGroup> <ItemGroup> <Reference Include="System" /> </ItemGroup> <ItemGroup> <None Include="source.extension.vsixmanifest"> <SubType>Designer</SubType> </None> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.ServiceHub.Framework" Version="$(MicrosoftServiceHubFrameworkVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.SDK.Analyzers" Version="$(MicrosoftVisualStudioSDKAnalyzersVersion)" PrivateAssets="all" /> <PackageReference Include="Microsoft.VisualStudio.Shell.15.0" Version="$(MicrosoftVisualStudioShell150Version)" /> <PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Validation" Version="$(MicrosoftVisualStudioValidationVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> <PackageReference Include="Microsoft.ServiceHub.Framework" Version="$(MicrosoftServiceHubFrameworkVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Validation" Version="$(MicrosoftVisualStudioValidationVersion)" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <TargetFramework>net472</TargetFramework> <!-- VSIX --> <GeneratePkgDefFile>true</GeneratePkgDefFile> <IncludeAssemblyInVSIXContainer>false</IncludeAssemblyInVSIXContainer> <IncludeDebugSymbolsInVSIXContainer>false</IncludeDebugSymbolsInVSIXContainer> <IncludeDebugSymbolsInLocalVSIXDeployment>false</IncludeDebugSymbolsInLocalVSIXDeployment> <ExtensionInstallationRoot>$(CommonExtensionInstallationRoot)</ExtensionInstallationRoot> <ExtensionInstallationFolder>Microsoft\ManagedLanguages\VBCSharp\ExpressionEvaluators</ExtensionInstallationFolder> <!-- VS Insertion --> <VisualStudioInsertionComponent>Microsoft.CodeAnalysis.LanguageServices</VisualStudioInsertionComponent> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\VisualStudio\Setup\Roslyn.VisualStudio.Setup.csproj"> <Name>VisualStudioSetup</Name> <ReferenceOutputAssembly>false</ReferenceOutputAssembly> <IncludeOutputGroupsInVSIX>SatelliteDllsProjectOutputGroup</IncludeOutputGroupsInVSIX> <Private>False</Private> </ProjectReference> <ProjectReference Include="..\Core\Source\ExpressionCompiler\Microsoft.CodeAnalysis.ExpressionCompiler.csproj"> <Name>ExpressionCompiler</Name> <IncludeOutputGroupsInVSIX>BuiltProjectOutputGroup;SatelliteDllsProjectOutputGroup</IncludeOutputGroupsInVSIX> <IncludeOutputGroupsInVSIXLocalOnly>DebugSymbolsProjectOutputGroup</IncludeOutputGroupsInVSIXLocalOnly> <ForceIncludeInVSIX>true</ForceIncludeInVSIX> <PkgDefEntry>BindingRedirect</PkgDefEntry> </ProjectReference> <ProjectReference Include="..\Core\Source\FunctionResolver\Microsoft.CodeAnalysis.FunctionResolver.csproj"> <Name>FunctionResolver</Name> <IncludeOutputGroupsInVSIX>BuiltProjectOutputGroup%3bVsdConfigOutputGroup;SatelliteDllsProjectOutputGroup</IncludeOutputGroupsInVSIX> <IncludeOutputGroupsInVSIXLocalOnly>DebugSymbolsProjectOutputGroup</IncludeOutputGroupsInVSIXLocalOnly> <ForceIncludeInVSIX>true</ForceIncludeInVSIX> <AdditionalProperties>TargetFramework=netstandard1.3</AdditionalProperties> <PkgDefEntry>BindingRedirect</PkgDefEntry> </ProjectReference> <ProjectReference Include="..\Core\Source\ResultProvider\Portable\Microsoft.CodeAnalysis.ResultProvider.csproj"> <Name>ResultProvider.Portable</Name> <IncludeOutputGroupsInVSIX>BuiltProjectOutputGroup;SatelliteDllsProjectOutputGroup</IncludeOutputGroupsInVSIX> <IncludeOutputGroupsInVSIXLocalOnly>DebugSymbolsProjectOutputGroup</IncludeOutputGroupsInVSIXLocalOnly> <ForceIncludeInVSIX>true</ForceIncludeInVSIX> <PkgDefEntry>BindingRedirect</PkgDefEntry> </ProjectReference> <ProjectReference Include="..\CSharp\Source\ExpressionCompiler\Microsoft.CodeAnalysis.CSharp.ExpressionCompiler.csproj"> <Name>CSharpExpressionCompiler</Name> <IncludeOutputGroupsInVSIX>BuiltProjectOutputGroup%3bVsdConfigOutputGroup;SatelliteDllsProjectOutputGroup</IncludeOutputGroupsInVSIX> <IncludeOutputGroupsInVSIXLocalOnly>DebugSymbolsProjectOutputGroup</IncludeOutputGroupsInVSIXLocalOnly> <ForceIncludeInVSIX>true</ForceIncludeInVSIX> <PkgDefEntry>BindingRedirect</PkgDefEntry> </ProjectReference> <ProjectReference Include="..\CSharp\Source\ResultProvider\Portable\Microsoft.CodeAnalysis.CSharp.ResultProvider.csproj"> <Name>CSharpResultProvider.Portable</Name> <IncludeOutputGroupsInVSIX>BuiltProjectOutputGroup%3bVsdConfigOutputGroup;SatelliteDllsProjectOutputGroup</IncludeOutputGroupsInVSIX> <IncludeOutputGroupsInVSIXLocalOnly>DebugSymbolsProjectOutputGroup</IncludeOutputGroupsInVSIXLocalOnly> <ForceIncludeInVSIX>true</ForceIncludeInVSIX> <PkgDefEntry>BindingRedirect</PkgDefEntry> </ProjectReference> <ProjectReference Include="..\VisualBasic\Source\ExpressionCompiler\Microsoft.CodeAnalysis.VisualBasic.ExpressionCompiler.vbproj"> <Name>BasicExpressionCompiler</Name> <IncludeOutputGroupsInVSIX>BuiltProjectOutputGroup%3bVsdConfigOutputGroup;SatelliteDllsProjectOutputGroup</IncludeOutputGroupsInVSIX> <IncludeOutputGroupsInVSIXLocalOnly>DebugSymbolsProjectOutputGroup</IncludeOutputGroupsInVSIXLocalOnly> <ForceIncludeInVSIX>true</ForceIncludeInVSIX> <PkgDefEntry>BindingRedirect</PkgDefEntry> </ProjectReference> <ProjectReference Include="..\VisualBasic\Source\ResultProvider\Portable\Microsoft.CodeAnalysis.VisualBasic.ResultProvider.vbproj"> <Name>BasicResultProvider.Portable</Name> <IncludeOutputGroupsInVSIX>BuiltProjectOutputGroup%3bVsdConfigOutputGroup;SatelliteDllsProjectOutputGroup</IncludeOutputGroupsInVSIX> <IncludeOutputGroupsInVSIXLocalOnly>DebugSymbolsProjectOutputGroup</IncludeOutputGroupsInVSIXLocalOnly> <ForceIncludeInVSIX>true</ForceIncludeInVSIX> <PkgDefEntry>BindingRedirect</PkgDefEntry> </ProjectReference> </ItemGroup> <ItemGroup> <Reference Include="System" /> </ItemGroup> <ItemGroup> <None Include="source.extension.vsixmanifest"> <SubType>Designer</SubType> </None> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.ServiceHub.Framework" Version="$(MicrosoftServiceHubFrameworkVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Imaging.Interop.14.0.DesignTime" Version="$(MicrosoftVisualStudioImagingInterop140DesignTimeVersion)" /> <PackageReference Include="Microsoft.VisualStudio.SDK.Analyzers" Version="$(MicrosoftVisualStudioSDKAnalyzersVersion)" PrivateAssets="all" /> <PackageReference Include="Microsoft.VisualStudio.Shell.15.0" Version="$(MicrosoftVisualStudioShell150Version)" /> <PackageReference Include="Microsoft.VisualStudio.Threading" Version="$(MicrosoftVisualStudioThreadingVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Validation" Version="$(MicrosoftVisualStudioValidationVersion)" /> <PackageReference Include="Newtonsoft.Json" Version="$(NewtonsoftJsonVersion)" /> <PackageReference Include="Microsoft.ServiceHub.Framework" Version="$(MicrosoftServiceHubFrameworkVersion)" /> <PackageReference Include="Microsoft.VisualStudio.Validation" Version="$(MicrosoftVisualStudioValidationVersion)" /> </ItemGroup> </Project>
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/ExpressionEvaluator/Core/Source/FunctionResolver/VisualBasic/Keywords.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; namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator { internal sealed partial class MemberSignatureParser { // From SyntaxFacts.GetReservedKeywordKinds(). (See // VisualBasicParsingTests.Keywords() which verifies the lists are in sync.) private static ImmutableHashSet<string> GetKeywords(StringComparer comparer) { return ImmutableHashSet.CreateRange( comparer, new[] { "AddressOf", "AddHandler", "Alias", "And", "AndAlso", "As", "Boolean", "ByRef", "Byte", "ByVal", "Call", "Case", "Catch", "CBool", "CByte", "CChar", "CDate", "CDec", "CDbl", "Char", "CInt", "Class", "CLng", "CObj", "Const", "Continue", "CSByte", "CShort", "CSng", "CStr", "CType", "CUInt", "CULng", "CUShort", "Date", "Decimal", "Declare", "Default", "Delegate", "Dim", "DirectCast", "Do", "Double", "Each", "Else", "ElseIf", "End", "Enum", "Erase", "Error", "Event", "Exit", "False", "Finally", "For", "Friend", "Function", "Get", "GetType", "GetXmlNamespace", "Global", "GoTo", "Handles", "If", "Implements", "Imports", "In", "Inherits", "Integer", "Interface", "Is", "IsNot", "Let", "Lib", "Like", "Long", "Loop", "Me", "Mod", "Module", "MustInherit", "MustOverride", "MyBase", "MyClass", "NameOf", "Namespace", "Narrowing", "Next", "New", "Not", "Nothing", "NotInheritable", "NotOverridable", "Object", "Of", "On", "Operator", "Option", "Optional", "Or", "OrElse", "Overloads", "Overridable", "Overrides", "ParamArray", "Partial", "Private", "Property", "Protected", "Public", "RaiseEvent", "ReadOnly", "ReDim", "REM", "RemoveHandler", "Resume", "Return", "SByte", "Select", "Set", "Shadows", "Shared", "Short", "Single", "Static", "Step", "Stop", "String", "Structure", "Sub", "SyncLock", "Then", "Throw", "To", "True", "Try", "TryCast", "TypeOf", "UInteger", "ULong", "UShort", "Using", "When", "While", "Widening", "With", "WithEvents", "WriteOnly", "Xor", "EndIf", "Gosub", "Variant", "Wend", }); } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator { internal sealed partial class MemberSignatureParser { // From SyntaxFacts.GetReservedKeywordKinds(). (See // VisualBasicParsingTests.Keywords() which verifies the lists are in sync.) private static ImmutableHashSet<string> GetKeywords(StringComparer comparer) { return ImmutableHashSet.CreateRange( comparer, new[] { "AddressOf", "AddHandler", "Alias", "And", "AndAlso", "As", "Boolean", "ByRef", "Byte", "ByVal", "Call", "Case", "Catch", "CBool", "CByte", "CChar", "CDate", "CDec", "CDbl", "Char", "CInt", "Class", "CLng", "CObj", "Const", "Continue", "CSByte", "CShort", "CSng", "CStr", "CType", "CUInt", "CULng", "CUShort", "Date", "Decimal", "Declare", "Default", "Delegate", "Dim", "DirectCast", "Do", "Double", "Each", "Else", "ElseIf", "End", "Enum", "Erase", "Error", "Event", "Exit", "False", "Finally", "For", "Friend", "Function", "Get", "GetType", "GetXmlNamespace", "Global", "GoTo", "Handles", "If", "Implements", "Imports", "In", "Inherits", "Integer", "Interface", "Is", "IsNot", "Let", "Lib", "Like", "Long", "Loop", "Me", "Mod", "Module", "MustInherit", "MustOverride", "MyBase", "MyClass", "NameOf", "Namespace", "Narrowing", "Next", "New", "Not", "Nothing", "NotInheritable", "NotOverridable", "Object", "Of", "On", "Operator", "Option", "Optional", "Or", "OrElse", "Overloads", "Overridable", "Overrides", "ParamArray", "Partial", "Private", "Property", "Protected", "Public", "RaiseEvent", "ReadOnly", "ReDim", "REM", "RemoveHandler", "Resume", "Return", "SByte", "Select", "Set", "Shadows", "Shared", "Short", "Single", "Static", "Step", "Stop", "String", "Structure", "Sub", "SyncLock", "Then", "Throw", "To", "True", "Try", "TryCast", "TypeOf", "UInteger", "ULong", "UShort", "Using", "When", "While", "Widening", "With", "WithEvents", "WriteOnly", "Xor", "EndIf", "Gosub", "Variant", "Wend", }); } } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Compilers/VisualBasic/Portable/Declarations/SingleNamespaceDeclaration.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Linq Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ' Note: Namespace Global has empty string as a name, as well as namespaces with errors Friend Class SingleNamespaceDeclaration Inherits SingleNamespaceOrTypeDeclaration Private ReadOnly _children As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) Public Property HasImports As Boolean Public ReadOnly IsPartOfRootNamespace As Boolean Public Sub New(name As String, hasImports As Boolean, syntaxReference As SyntaxReference, nameLocation As Location, children As ImmutableArray(Of SingleNamespaceOrTypeDeclaration), Optional isPartOfRootNamespace As Boolean = False) MyBase.New(name, syntaxReference, nameLocation) Me._children = children Me.HasImports = hasImports Me.IsPartOfRootNamespace = isPartOfRootNamespace End Sub ' Is this representing the global namespace ("Namespace Global") Public Overridable ReadOnly Property IsGlobalNamespace As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property Kind As DeclarationKind Get Return DeclarationKind.Namespace End Get End Property Protected Overrides Function GetNamespaceOrTypeDeclarationChildren() As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) Return Me._children End Function ' If this declaration was part of a namespace block, return it, otherwise return nothing. Public Function GetNamespaceBlockSyntax() As NamespaceBlockSyntax If SyntaxReference Is Nothing Then Return Nothing Else Return SyntaxReference.GetSyntax().AncestorsAndSelf().OfType(Of NamespaceBlockSyntax)().FirstOrDefault() End If End Function Private Class Comparer Implements IEqualityComparer(Of SingleNamespaceDeclaration) Private Shadows Function Equals(decl1 As SingleNamespaceDeclaration, decl2 As SingleNamespaceDeclaration) As Boolean Implements IEqualityComparer(Of SingleNamespaceDeclaration).Equals Return IdentifierComparison.Equals(decl1.Name, decl2.Name) End Function Private Shadows Function GetHashCode(decl1 As SingleNamespaceDeclaration) As Integer Implements IEqualityComparer(Of SingleNamespaceDeclaration).GetHashCode Return IdentifierComparison.GetHashCode(decl1.Name) End Function End Class Public Shared ReadOnly EqualityComparer As IEqualityComparer(Of SingleNamespaceDeclaration) = New Comparer() ''' <summary> ''' This function is used to determine the best name of a type or namespace when there are multiple declarations that ''' have the same name but with different spellings. ''' If this declaration is part of the rootnamespace (specified by /rootnamespace:&lt;nsname&gt; this is considered the best name. ''' Otherwise the best name of a type or namespace is the one that String.Compare considers to be less using a Ordinal. ''' In practice this prefers uppercased or camelcased identifiers. ''' </summary> ''' <typeparam name="T"></typeparam> ''' <param name="singleDeclarations">The single declarations.</param> ''' <param name="multipleSpellings">Set to true if there were multiple distinct spellings.</param> Public Overloads Shared Function BestName(Of T As SingleNamespaceDeclaration)(singleDeclarations As ImmutableArray(Of T), ByRef multipleSpellings As Boolean) As String Debug.Assert(Not singleDeclarations.IsEmpty) multipleSpellings = False Dim bestDeclarationName = singleDeclarations(0).Name For declarationIndex = 1 To singleDeclarations.Length - 1 Dim otherName = singleDeclarations(declarationIndex).Name Dim comp = String.Compare(bestDeclarationName, otherName, StringComparison.Ordinal) If comp <> 0 Then multipleSpellings = True ' We detected multiple spellings. If one of the namespaces is part of the rootnamespace ' we can already return from this loop. If singleDeclarations(0).IsPartOfRootNamespace Then Return bestDeclarationName End If If singleDeclarations(declarationIndex).IsPartOfRootNamespace Then Return otherName End If If comp > 0 Then bestDeclarationName = otherName End If End If Next Return bestDeclarationName 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 Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Linq Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ' Note: Namespace Global has empty string as a name, as well as namespaces with errors Friend Class SingleNamespaceDeclaration Inherits SingleNamespaceOrTypeDeclaration Private ReadOnly _children As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) Public Property HasImports As Boolean Public ReadOnly IsPartOfRootNamespace As Boolean Public Sub New(name As String, hasImports As Boolean, syntaxReference As SyntaxReference, nameLocation As Location, children As ImmutableArray(Of SingleNamespaceOrTypeDeclaration), Optional isPartOfRootNamespace As Boolean = False) MyBase.New(name, syntaxReference, nameLocation) Me._children = children Me.HasImports = hasImports Me.IsPartOfRootNamespace = isPartOfRootNamespace End Sub ' Is this representing the global namespace ("Namespace Global") Public Overridable ReadOnly Property IsGlobalNamespace As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property Kind As DeclarationKind Get Return DeclarationKind.Namespace End Get End Property Protected Overrides Function GetNamespaceOrTypeDeclarationChildren() As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) Return Me._children End Function ' If this declaration was part of a namespace block, return it, otherwise return nothing. Public Function GetNamespaceBlockSyntax() As NamespaceBlockSyntax If SyntaxReference Is Nothing Then Return Nothing Else Return SyntaxReference.GetSyntax().AncestorsAndSelf().OfType(Of NamespaceBlockSyntax)().FirstOrDefault() End If End Function Private Class Comparer Implements IEqualityComparer(Of SingleNamespaceDeclaration) Private Shadows Function Equals(decl1 As SingleNamespaceDeclaration, decl2 As SingleNamespaceDeclaration) As Boolean Implements IEqualityComparer(Of SingleNamespaceDeclaration).Equals Return IdentifierComparison.Equals(decl1.Name, decl2.Name) End Function Private Shadows Function GetHashCode(decl1 As SingleNamespaceDeclaration) As Integer Implements IEqualityComparer(Of SingleNamespaceDeclaration).GetHashCode Return IdentifierComparison.GetHashCode(decl1.Name) End Function End Class Public Shared ReadOnly EqualityComparer As IEqualityComparer(Of SingleNamespaceDeclaration) = New Comparer() ''' <summary> ''' This function is used to determine the best name of a type or namespace when there are multiple declarations that ''' have the same name but with different spellings. ''' If this declaration is part of the rootnamespace (specified by /rootnamespace:&lt;nsname&gt; this is considered the best name. ''' Otherwise the best name of a type or namespace is the one that String.Compare considers to be less using a Ordinal. ''' In practice this prefers uppercased or camelcased identifiers. ''' </summary> ''' <typeparam name="T"></typeparam> ''' <param name="singleDeclarations">The single declarations.</param> ''' <param name="multipleSpellings">Set to true if there were multiple distinct spellings.</param> Public Overloads Shared Function BestName(Of T As SingleNamespaceDeclaration)(singleDeclarations As ImmutableArray(Of T), ByRef multipleSpellings As Boolean) As String Debug.Assert(Not singleDeclarations.IsEmpty) multipleSpellings = False Dim bestDeclarationName = singleDeclarations(0).Name For declarationIndex = 1 To singleDeclarations.Length - 1 Dim otherName = singleDeclarations(declarationIndex).Name Dim comp = String.Compare(bestDeclarationName, otherName, StringComparison.Ordinal) If comp <> 0 Then multipleSpellings = True ' We detected multiple spellings. If one of the namespaces is part of the rootnamespace ' we can already return from this loop. If singleDeclarations(0).IsPartOfRootNamespace Then Return bestDeclarationName End If If singleDeclarations(declarationIndex).IsPartOfRootNamespace Then Return otherName End If If comp > 0 Then bestDeclarationName = otherName End If End If Next Return bestDeclarationName End Function End Class End Namespace
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/ObjectListItem.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.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Language.Intellisense; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { using Workspace = Microsoft.CodeAnalysis.Workspace; internal abstract class ObjectListItem { private readonly ProjectId _projectId; private ObjectList _parentList; private readonly ushort _glyphIndex; private readonly bool _isHidden; protected ObjectListItem( ProjectId projectId, StandardGlyphGroup glyphGroup, StandardGlyphItem glyphItem = StandardGlyphItem.GlyphItemPublic, bool isHidden = false) { _projectId = projectId; _glyphIndex = glyphGroup < StandardGlyphGroup.GlyphGroupError ? (ushort)((int)glyphGroup + (int)glyphItem) : (ushort)glyphGroup; _isHidden = isHidden; } internal void SetParentList(ObjectList parentList) { Debug.Assert(_parentList == null); _parentList = parentList; } public virtual bool SupportsGoToDefinition { get { return false; } } public virtual bool SupportsFindAllReferences { get { return false; } } public abstract string DisplayText { get; } public abstract string FullNameText { get; } public abstract string SearchText { get; } public override string ToString() => DisplayText; public ObjectList ParentList { get { return _parentList; } } public ObjectListKind ParentListKind { get { return _parentList != null ? _parentList.Kind : ObjectListKind.None; } } public ProjectId ProjectId { get { return _projectId; } } public Compilation GetCompilation(Workspace workspace) { var project = workspace.CurrentSolution.GetProject(_projectId); if (project == null) { return null; } return project .GetCompilationAsync(CancellationToken.None) .WaitAndGetResult_ObjectBrowser(CancellationToken.None); } public ushort GlyphIndex { get { return _glyphIndex; } } public bool IsHidden { get { return _isHidden; } } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Language.Intellisense; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { using Workspace = Microsoft.CodeAnalysis.Workspace; internal abstract class ObjectListItem { private readonly ProjectId _projectId; private ObjectList _parentList; private readonly ushort _glyphIndex; private readonly bool _isHidden; protected ObjectListItem( ProjectId projectId, StandardGlyphGroup glyphGroup, StandardGlyphItem glyphItem = StandardGlyphItem.GlyphItemPublic, bool isHidden = false) { _projectId = projectId; _glyphIndex = glyphGroup < StandardGlyphGroup.GlyphGroupError ? (ushort)((int)glyphGroup + (int)glyphItem) : (ushort)glyphGroup; _isHidden = isHidden; } internal void SetParentList(ObjectList parentList) { Debug.Assert(_parentList == null); _parentList = parentList; } public virtual bool SupportsGoToDefinition { get { return false; } } public virtual bool SupportsFindAllReferences { get { return false; } } public abstract string DisplayText { get; } public abstract string FullNameText { get; } public abstract string SearchText { get; } public override string ToString() => DisplayText; public ObjectList ParentList { get { return _parentList; } } public ObjectListKind ParentListKind { get { return _parentList != null ? _parentList.Kind : ObjectListKind.None; } } public ProjectId ProjectId { get { return _projectId; } } public Compilation GetCompilation(Workspace workspace) { var project = workspace.CurrentSolution.GetProject(_projectId); if (project == null) { return null; } return project .GetCompilationAsync(CancellationToken.None) .WaitAndGetResult_ObjectBrowser(CancellationToken.None); } public ushort GlyphIndex { get { return _glyphIndex; } } public bool IsHidden { get { return _isHidden; } } } }
-1
dotnet/roslyn
55,739
EnC - Allow changing names of previously synthesized record member parameters
Fixes https://github.com/dotnet/roslyn/issues/55732
davidwengier
2021-08-19T23:45:50Z
2021-08-20T17:30:31Z
6ff82a995eebcb2e21c3bad5ac8163ce5fd05db8
2f6768efa3f5575bae411524bb11364b2208c2c4
EnC - Allow changing names of previously synthesized record member parameters. Fixes https://github.com/dotnet/roslyn/issues/55732
./src/Compilers/CSharp/Portable/Syntax/DoStatementSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class DoStatementSyntax { public DoStatementSyntax Update(SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) => Update(AttributeLists, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static DoStatementSyntax DoStatement(SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) => DoStatement(attributeLists: default, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class DoStatementSyntax { public DoStatementSyntax Update(SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) => Update(AttributeLists, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static DoStatementSyntax DoStatement(SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) => DoStatement(attributeLists: default, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/EditorFeatures/Core.Wpf/InlineHints/InlineHintsTag.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 System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Formatting; namespace Microsoft.CodeAnalysis.Editor.InlineHints { /// <summary> /// This is the tag which implements the IntraTextAdornmentTag and is meant to create the UIElements that get shown /// in the editor /// </summary> internal class InlineHintsTag : IntraTextAdornmentTag { public const string TagId = "inline hints"; private readonly ITextView _textView; private readonly SnapshotSpan _span; private readonly InlineHint _hint; private readonly InlineHintsTaggerProvider _taggerProvider; private InlineHintsTag( FrameworkElement adornment, ITextView textView, SnapshotSpan span, InlineHint hint, InlineHintsTaggerProvider taggerProvider) : base(adornment, removalCallback: null, PositionAffinity.Predecessor) { _textView = textView; _span = span; _hint = hint; _taggerProvider = taggerProvider; // Sets the tooltip to a string so that the tool tip opening event can be triggered // Tooltip value does not matter at this point because it immediately gets overwritten by the correct // information in the Border_ToolTipOpening event handler adornment.ToolTip = "Quick info"; adornment.ToolTipOpening += Border_ToolTipOpening; } /// <summary> /// Creates the UIElement on call /// Uses PositionAffinity.Predecessor because we want the tag to be associated with the preceding character /// </summary> /// <param name="textView">The view of the editor</param> /// <param name="span">The span that has the location of the hint</param> public static InlineHintsTag Create( InlineHint hint, TextFormattingRunProperties format, IWpfTextView textView, SnapshotSpan span, InlineHintsTaggerProvider taggerProvider, IClassificationFormatMap formatMap, bool classify) { return new InlineHintsTag( CreateElement(hint.DisplayParts, textView, format, formatMap, taggerProvider.TypeMap, classify), textView, span, hint, taggerProvider); } public async Task<IReadOnlyCollection<object>> CreateDescriptionAsync(CancellationToken cancellationToken) { var document = _span.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var taggedText = await _hint.GetDescriptionAsync(document, cancellationToken).ConfigureAwait(false); if (!taggedText.IsDefaultOrEmpty) { var context = new IntellisenseQuickInfoBuilderContext( document, _taggerProvider.ThreadingContext, _taggerProvider.OperationExecutor, _taggerProvider.AsynchronousOperationListener, _taggerProvider.StreamingFindUsagesPresenter); return Implementation.IntelliSense.Helpers.BuildInteractiveTextElements(taggedText, context); } } return Array.Empty<object>(); } private static FrameworkElement CreateElement( ImmutableArray<TaggedText> taggedTexts, IWpfTextView textView, TextFormattingRunProperties format, IClassificationFormatMap formatMap, ClassificationTypeMap typeMap, bool classify) { // Constructs the hint block which gets assigned parameter name and fontstyles according to the options // page. Calculates a inline tag that will be 3/4s the size of a normal line. This shrink size tends to work // well with VS at any zoom level or font size. var block = new TextBlock { FontFamily = format.Typeface.FontFamily, FontSize = 0.75 * format.FontRenderingEmSize, FontStyle = FontStyles.Normal, Foreground = format.ForegroundBrush, // Adds a little bit of padding to the left of the text relative to the border to make the text seem // more balanced in the border Padding = new Thickness(left: 2, top: 0, right: 2, bottom: 0) }; var (trimmedTexts, leftPadding, rightPadding) = Trim(taggedTexts); foreach (var taggedText in trimmedTexts) { var run = new Run(taggedText.ToVisibleDisplayString(includeLeftToRightMarker: true)); if (classify && taggedText.Tag != TextTags.Text) { var properties = formatMap.GetTextProperties(typeMap.GetClassificationType(taggedText.Tag.ToClassificationTypeName())); var brush = properties.ForegroundBrush.Clone(); run.Foreground = brush; } block.Inlines.Add(run); } block.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); // Encapsulates the textblock within a border. Gets foreground/background colors from the options menu. // If the tag is started or followed by a space, we trim that off but represent the space as buffer on hte // left or right side. var left = leftPadding * 5; var right = rightPadding * 5; var border = new Border { Background = format.BackgroundBrush, Child = block, CornerRadius = new CornerRadius(2), VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(left, top: 0, right, bottom: 0), }; // gets pixel distance of baseline to top of the font height var dockPanelHeight = format.Typeface.FontFamily.Baseline * format.FontRenderingEmSize; var dockPanel = new DockPanel { Height = dockPanelHeight, LastChildFill = false, // VerticalAlignment is set to Top because it will rest to the top relative to the stackpanel VerticalAlignment = VerticalAlignment.Top }; dockPanel.Children.Add(border); DockPanel.SetDock(border, Dock.Bottom); var stackPanel = new StackPanel { // Height set to align the baseline of the text within the TextBlock with the baseline of text in the editor Height = dockPanelHeight + (block.DesiredSize.Height - (block.FontFamily.Baseline * block.FontSize)), Orientation = Orientation.Vertical }; stackPanel.Children.Add(dockPanel); // Need to set these properties to avoid unnecessary reformatting because some dependancy properties // affect layout TextOptions.SetTextFormattingMode(stackPanel, TextOptions.GetTextFormattingMode(textView.VisualElement)); TextOptions.SetTextHintingMode(stackPanel, TextOptions.GetTextHintingMode(textView.VisualElement)); TextOptions.SetTextRenderingMode(stackPanel, TextOptions.GetTextRenderingMode(textView.VisualElement)); return stackPanel; } private static (ImmutableArray<TaggedText> texts, int leftPadding, int rightPadding) Trim(ImmutableArray<TaggedText> taggedTexts) { using var _ = ArrayBuilder<TaggedText>.GetInstance(out var result); var leftPadding = 0; var rightPadding = 0; if (taggedTexts.Length == 1) { var first = taggedTexts.First(); var trimStart = first.Text.TrimStart(); var trimBoth = trimStart.TrimEnd(); result.Add(new TaggedText(first.Tag, trimBoth)); leftPadding = first.Text.Length - trimStart.Length; rightPadding = trimStart.Length - trimBoth.Length; } else if (taggedTexts.Length >= 2) { var first = taggedTexts.First(); var trimStart = first.Text.TrimStart(); result.Add(new TaggedText(first.Tag, trimStart)); leftPadding = first.Text.Length - trimStart.Length; for (var i = 1; i < taggedTexts.Length - 1; i++) result.Add(taggedTexts[i]); var last = taggedTexts.Last(); var trimEnd = last.Text.TrimEnd(); result.Add(new TaggedText(last.Tag, trimEnd)); rightPadding = last.Text.Length - trimEnd.Length; } return (result.ToImmutable(), leftPadding, rightPadding); } /// <summary> /// Determines if the border is being moused over and shows the info accordingly /// </summary> private void Border_ToolTipOpening(object sender, ToolTipEventArgs e) { var hintUIElement = (FrameworkElement)sender; e.Handled = true; bool KeepOpen() { var mousePoint = Mouse.GetPosition(hintUIElement); return !(mousePoint.X > hintUIElement.ActualWidth || mousePoint.X < 0 || mousePoint.Y > hintUIElement.ActualHeight || mousePoint.Y < 0); } var toolTipPresenter = _taggerProvider.ToolTipService.CreatePresenter(_textView, new ToolTipParameters(trackMouse: true, ignoreBufferChange: false, KeepOpen)); _ = StartToolTipServiceAsync(toolTipPresenter); } /// <summary> /// Waits for the description to be created and updates the tooltip with the associated information /// </summary> private async Task StartToolTipServiceAsync(IToolTipPresenter toolTipPresenter) { var threadingContext = _taggerProvider.ThreadingContext; var uiList = await Task.Run(() => CreateDescriptionAsync(threadingContext.DisposalToken)).ConfigureAwait(false); await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(threadingContext.DisposalToken); toolTipPresenter.StartOrUpdate(_textView.TextSnapshot.CreateTrackingSpan(_span.Start, _span.Length, SpanTrackingMode.EdgeInclusive), uiList); } } }
// Licensed to the .NET Foundation under one or more 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 System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Elfie.Diagnostics; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Adornments; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Formatting; namespace Microsoft.CodeAnalysis.Editor.InlineHints { /// <summary> /// This is the tag which implements the IntraTextAdornmentTag and is meant to create the UIElements that get shown /// in the editor /// </summary> internal class InlineHintsTag : IntraTextAdornmentTag { public const string TagId = "inline hints"; private readonly ITextView _textView; private readonly SnapshotSpan _span; private readonly InlineHint _hint; private readonly InlineHintsTaggerProvider _taggerProvider; private InlineHintsTag( FrameworkElement adornment, ITextView textView, SnapshotSpan span, InlineHint hint, InlineHintsTaggerProvider taggerProvider) : base(adornment, removalCallback: null, PositionAffinity.Predecessor) { _textView = textView; _span = span; _hint = hint; _taggerProvider = taggerProvider; // Sets the tooltip to a string so that the tool tip opening event can be triggered // Tooltip value does not matter at this point because it immediately gets overwritten by the correct // information in the Border_ToolTipOpening event handler adornment.ToolTip = "Quick info"; adornment.ToolTipOpening += Border_ToolTipOpening; if (_hint.ReplacementTextChange is not null) { adornment.MouseLeftButtonDown += Adornment_MouseLeftButtonDown; } } /// <summary> /// Creates the UIElement on call /// Uses PositionAffinity.Predecessor because we want the tag to be associated with the preceding character /// </summary> /// <param name="textView">The view of the editor</param> /// <param name="span">The span that has the location of the hint</param> public static InlineHintsTag Create( InlineHint hint, TextFormattingRunProperties format, IWpfTextView textView, SnapshotSpan span, InlineHintsTaggerProvider taggerProvider, IClassificationFormatMap formatMap, bool classify) { return new InlineHintsTag( CreateElement(hint.DisplayParts, textView, format, formatMap, taggerProvider.TypeMap, classify), textView, span, hint, taggerProvider); } public async Task<IReadOnlyCollection<object>> CreateDescriptionAsync(CancellationToken cancellationToken) { var document = _span.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var taggedText = await _hint.GetDescriptionAsync(document, cancellationToken).ConfigureAwait(false); if (!taggedText.IsDefaultOrEmpty) { var context = new IntellisenseQuickInfoBuilderContext( document, _taggerProvider.ThreadingContext, _taggerProvider.OperationExecutor, _taggerProvider.AsynchronousOperationListener, _taggerProvider.StreamingFindUsagesPresenter); return Implementation.IntelliSense.Helpers.BuildInteractiveTextElements(taggedText, context); } } return Array.Empty<object>(); } private static FrameworkElement CreateElement( ImmutableArray<TaggedText> taggedTexts, IWpfTextView textView, TextFormattingRunProperties format, IClassificationFormatMap formatMap, ClassificationTypeMap typeMap, bool classify) { // Constructs the hint block which gets assigned parameter name and fontstyles according to the options // page. Calculates a inline tag that will be 3/4s the size of a normal line. This shrink size tends to work // well with VS at any zoom level or font size. var block = new TextBlock { FontFamily = format.Typeface.FontFamily, FontSize = 0.75 * format.FontRenderingEmSize, FontStyle = FontStyles.Normal, Foreground = format.ForegroundBrush, // Adds a little bit of padding to the left of the text relative to the border to make the text seem // more balanced in the border Padding = new Thickness(left: 2, top: 0, right: 2, bottom: 0) }; var (trimmedTexts, leftPadding, rightPadding) = Trim(taggedTexts); foreach (var taggedText in trimmedTexts) { var run = new Run(taggedText.ToVisibleDisplayString(includeLeftToRightMarker: true)); if (classify && taggedText.Tag != TextTags.Text) { var properties = formatMap.GetTextProperties(typeMap.GetClassificationType(taggedText.Tag.ToClassificationTypeName())); var brush = properties.ForegroundBrush.Clone(); run.Foreground = brush; } block.Inlines.Add(run); } block.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); // Encapsulates the textblock within a border. Gets foreground/background colors from the options menu. // If the tag is started or followed by a space, we trim that off but represent the space as buffer on hte // left or right side. var left = leftPadding * 5; var right = rightPadding * 5; var border = new Border { Background = format.BackgroundBrush, Child = block, CornerRadius = new CornerRadius(2), VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(left, top: 0, right, bottom: 0), }; // gets pixel distance of baseline to top of the font height var dockPanelHeight = format.Typeface.FontFamily.Baseline * format.FontRenderingEmSize; var dockPanel = new DockPanel { Height = dockPanelHeight, LastChildFill = false, // VerticalAlignment is set to Top because it will rest to the top relative to the stackpanel VerticalAlignment = VerticalAlignment.Top }; dockPanel.Children.Add(border); DockPanel.SetDock(border, Dock.Bottom); var stackPanel = new StackPanel { // Height set to align the baseline of the text within the TextBlock with the baseline of text in the editor Height = dockPanelHeight + (block.DesiredSize.Height - (block.FontFamily.Baseline * block.FontSize)), Orientation = Orientation.Vertical }; stackPanel.Children.Add(dockPanel); // Need to set these properties to avoid unnecessary reformatting because some dependancy properties // affect layout TextOptions.SetTextFormattingMode(stackPanel, TextOptions.GetTextFormattingMode(textView.VisualElement)); TextOptions.SetTextHintingMode(stackPanel, TextOptions.GetTextHintingMode(textView.VisualElement)); TextOptions.SetTextRenderingMode(stackPanel, TextOptions.GetTextRenderingMode(textView.VisualElement)); return stackPanel; } private static (ImmutableArray<TaggedText> texts, int leftPadding, int rightPadding) Trim(ImmutableArray<TaggedText> taggedTexts) { using var _ = ArrayBuilder<TaggedText>.GetInstance(out var result); var leftPadding = 0; var rightPadding = 0; if (taggedTexts.Length == 1) { var first = taggedTexts.First(); var trimStart = first.Text.TrimStart(); var trimBoth = trimStart.TrimEnd(); result.Add(new TaggedText(first.Tag, trimBoth)); leftPadding = first.Text.Length - trimStart.Length; rightPadding = trimStart.Length - trimBoth.Length; } else if (taggedTexts.Length >= 2) { var first = taggedTexts.First(); var trimStart = first.Text.TrimStart(); result.Add(new TaggedText(first.Tag, trimStart)); leftPadding = first.Text.Length - trimStart.Length; for (var i = 1; i < taggedTexts.Length - 1; i++) result.Add(taggedTexts[i]); var last = taggedTexts.Last(); var trimEnd = last.Text.TrimEnd(); result.Add(new TaggedText(last.Tag, trimEnd)); rightPadding = last.Text.Length - trimEnd.Length; } return (result.ToImmutable(), leftPadding, rightPadding); } /// <summary> /// Determines if the border is being moused over and shows the info accordingly /// </summary> private void Border_ToolTipOpening(object sender, ToolTipEventArgs e) { var hintUIElement = (FrameworkElement)sender; e.Handled = true; bool KeepOpen() { var mousePoint = Mouse.GetPosition(hintUIElement); return !(mousePoint.X > hintUIElement.ActualWidth || mousePoint.X < 0 || mousePoint.Y > hintUIElement.ActualHeight || mousePoint.Y < 0); } var toolTipPresenter = _taggerProvider.ToolTipService.CreatePresenter(_textView, new ToolTipParameters(trackMouse: true, ignoreBufferChange: false, KeepOpen)); _ = StartToolTipServiceAsync(toolTipPresenter); } /// <summary> /// Waits for the description to be created and updates the tooltip with the associated information /// </summary> private async Task StartToolTipServiceAsync(IToolTipPresenter toolTipPresenter) { var threadingContext = _taggerProvider.ThreadingContext; var uiList = await Task.Run(() => CreateDescriptionAsync(threadingContext.DisposalToken)).ConfigureAwait(false); await threadingContext.JoinableTaskFactory.SwitchToMainThreadAsync(threadingContext.DisposalToken); toolTipPresenter.StartOrUpdate(_textView.TextSnapshot.CreateTrackingSpan(_span.Start, _span.Length, SpanTrackingMode.EdgeInclusive), uiList); } private void Adornment_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (e.ClickCount == 2) { e.Handled = true; var replacementValue = _hint.ReplacementTextChange!.Value; var subjectBuffer = _span.Snapshot.TextBuffer; if (subjectBuffer.CurrentSnapshot.Length > replacementValue.Span.End) { subjectBuffer.Replace(new VisualStudio.Text.Span(replacementValue.Span.Start, replacementValue.Span.Length), replacementValue.NewText); } else { Internal.Log.Logger.Log(FunctionId.Inline_Hints_DoubleClick, $"replacement span end:{replacementValue.Span.End} is greater than or equal to current snapshot length:{subjectBuffer.CurrentSnapshot.Length}"); } } } } }
1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/EditorFeatures/Test2/InlineHints/AbstractInlineHintsTests.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.Editor.InlineHints Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.InlineHints Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Options Namespace Microsoft.CodeAnalysis.Editor.UnitTests.InlineHints <[UseExportProvider]> Public MustInherit Class AbstractInlineHintsTests Protected Async Function VerifyParamHints(test As XElement, Optional optionIsEnabled As Boolean = True) As Task Using workspace = TestWorkspace.Create(test) WpfTestRunner.RequireWpfFact($"{NameOf(AbstractInlineHintsTests)}.{NameOf(Me.VerifyParamHints)} creates asynchronous taggers") Dim options = New InlineParameterHintsOptions( EnabledForParameters:=optionIsEnabled, ForLiteralParameters:=True, ForIndexerParameters:=True, ForObjectCreationParameters:=True, ForOtherParameters:=False, SuppressForParametersThatDifferOnlyBySuffix:=True, SuppressForParametersThatMatchMethodIntent:=True, SuppressForParametersThatMatchArgumentName:=True) Dim displayOptions = New SymbolDescriptionOptions() Dim hostDocument = workspace.Documents.Single() Dim snapshot = hostDocument.GetTextBuffer().CurrentSnapshot Dim document = workspace.CurrentSolution.GetDocument(hostDocument.Id) Dim tagService = document.GetRequiredLanguageService(Of IInlineParameterNameHintsService) Dim inlineHints = Await tagService.GetInlineHintsAsync(document, New Text.TextSpan(0, snapshot.Length), options, displayOptions, CancellationToken.None) Dim producedTags = From hint In inlineHints Select hint.DisplayParts.GetFullText().TrimEnd() + hint.Span.ToString ValidateSpans(hostDocument, producedTags) End Using End Function Private Shared Sub ValidateSpans(hostDocument As TestHostDocument, producedTags As IEnumerable(Of String)) Dim expectedTags As New List(Of String) Dim nameAndSpansList = hostDocument.AnnotatedSpans.SelectMany( Function(name) name.Value, Function(name, span) New With {.Name = name.Key, span}) For Each nameAndSpan In nameAndSpansList.OrderBy(Function(x) x.span.Start) expectedTags.Add(nameAndSpan.Name + ":" + nameAndSpan.span.ToString()) Next AssertEx.Equal(expectedTags, producedTags) End Sub Protected Async Function VerifyTypeHints(test As XElement, Optional optionIsEnabled As Boolean = True, Optional ephemeral As Boolean = False) As Task Using workspace = TestWorkspace.Create(test) WpfTestRunner.RequireWpfFact($"{NameOf(AbstractInlineHintsTests)}.{NameOf(Me.VerifyTypeHints)} creates asynchronous taggers") Dim globalOptions = workspace.GetService(Of IGlobalOptionService) globalOptions.SetGlobalOption(New OptionKey(InlineHintsGlobalStateOption.DisplayAllOverride), ephemeral) Dim options = New InlineTypeHintsOptions( EnabledForTypes:=optionIsEnabled AndAlso Not ephemeral, ForImplicitVariableTypes:=True, ForLambdaParameterTypes:=True, ForImplicitObjectCreation:=True) Dim displayOptions = New SymbolDescriptionOptions() Dim hostDocument = workspace.Documents.Single() Dim snapshot = hostDocument.GetTextBuffer().CurrentSnapshot Dim document = workspace.CurrentSolution.GetDocument(hostDocument.Id) Dim tagService = document.GetRequiredLanguageService(Of IInlineTypeHintsService) Dim typeHints = Await tagService.GetInlineHintsAsync(document, New Text.TextSpan(0, snapshot.Length), options, displayOptions, CancellationToken.None) Dim producedTags = From hint In typeHints Select hint.DisplayParts.GetFullText() + ":" + hint.Span.ToString() ValidateSpans(hostDocument, producedTags) End Using 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.Editor.InlineHints Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.InlineHints Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.[Shared].Utilities Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.InlineHints <[UseExportProvider]> Public MustInherit Class AbstractInlineHintsTests Protected Async Function VerifyParamHints(test As XElement, output As XElement, Optional optionIsEnabled As Boolean = True) As Task Using workspace = TestWorkspace.Create(test) WpfTestRunner.RequireWpfFact($"{NameOf(AbstractInlineHintsTests)}.{NameOf(Me.VerifyParamHints)} creates asynchronous taggers") Dim options = New InlineParameterHintsOptions( EnabledForParameters:=optionIsEnabled, ForLiteralParameters:=True, ForIndexerParameters:=True, ForObjectCreationParameters:=True, ForOtherParameters:=False, SuppressForParametersThatDifferOnlyBySuffix:=True, SuppressForParametersThatMatchMethodIntent:=True, SuppressForParametersThatMatchArgumentName:=True) Dim displayOptions = New SymbolDescriptionOptions() Dim hostDocument = workspace.Documents.Single() Dim snapshot = hostDocument.GetTextBuffer().CurrentSnapshot Dim document = workspace.CurrentSolution.GetDocument(hostDocument.Id) Dim tagService = document.GetRequiredLanguageService(Of IInlineParameterNameHintsService) Dim inlineHints = Await tagService.GetInlineHintsAsync(document, New Text.TextSpan(0, snapshot.Length), options, displayOptions, CancellationToken.None) Dim producedTags = From hint In inlineHints Select hint.DisplayParts.GetFullText().TrimEnd() + hint.Span.ToString ValidateSpans(hostDocument, producedTags) Dim outWorkspace = TestWorkspace.Create(output) Dim expectedDocument = outWorkspace.CurrentSolution.GetDocument(outWorkspace.Documents.Single().Id) Await ValidateDoubleClick(document, expectedDocument, inlineHints) End Using End Function Private Shared Sub ValidateSpans(hostDocument As TestHostDocument, producedTags As IEnumerable(Of String)) Dim expectedTags As New List(Of String) Dim nameAndSpansList = hostDocument.AnnotatedSpans.SelectMany( Function(name) name.Value, Function(name, span) New With {.Name = name.Key, span}) For Each nameAndSpan In nameAndSpansList.OrderBy(Function(x) x.span.Start) expectedTags.Add(nameAndSpan.Name + ":" + nameAndSpan.span.ToString()) Next AssertEx.Equal(expectedTags, producedTags) End Sub Private Shared Async Function ValidateDoubleClick(document As Document, expectedDocument As Document, inlineHints As ImmutableArray(Of InlineHint)) As Task Dim textChanges = New List(Of TextChange) For Each inlineHint In inlineHints If inlineHint.ReplacementTextChange IsNot Nothing Then textChanges.Add(inlineHint.ReplacementTextChange.Value) End If Next Dim value = Await document.GetTextAsync().ConfigureAwait(False) Dim newText = value.WithChanges(textChanges).ToString() Dim expectedText = Await expectedDocument.GetTextAsync().ConfigureAwait(False) AssertEx.Equal(expectedText.ToString(), newText) End Function Protected Async Function VerifyTypeHints(test As XElement, output As XElement, Optional optionIsEnabled As Boolean = True, Optional ephemeral As Boolean = False) As Task Using workspace = TestWorkspace.Create(test) WpfTestRunner.RequireWpfFact($"{NameOf(AbstractInlineHintsTests)}.{NameOf(Me.VerifyTypeHints)} creates asynchronous taggers") Dim globalOptions = workspace.GetService(Of IGlobalOptionService) globalOptions.SetGlobalOption(New OptionKey(InlineHintsGlobalStateOption.DisplayAllOverride), ephemeral) Dim options = New InlineTypeHintsOptions( EnabledForTypes:=optionIsEnabled AndAlso Not ephemeral, ForImplicitVariableTypes:=True, ForLambdaParameterTypes:=True, ForImplicitObjectCreation:=True) Dim displayOptions = New SymbolDescriptionOptions() Dim hostDocument = workspace.Documents.Single() Dim snapshot = hostDocument.GetTextBuffer().CurrentSnapshot Dim document = workspace.CurrentSolution.GetDocument(hostDocument.Id) Dim tagService = document.GetRequiredLanguageService(Of IInlineTypeHintsService) Dim typeHints = Await tagService.GetInlineHintsAsync(document, New Text.TextSpan(0, snapshot.Length), options, displayOptions, CancellationToken.None) Dim producedTags = From hint In typeHints Select hint.DisplayParts.GetFullText() + ":" + hint.Span.ToString() ValidateSpans(hostDocument, producedTags) Dim outWorkspace = TestWorkspace.Create(output) Dim expectedDocument = outWorkspace.CurrentSolution.GetDocument(outWorkspace.Documents.Single().Id) Await ValidateDoubleClick(document, expectedDocument, typeHints) End Using End Function End Class End Namespace
1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/EditorFeatures/Test2/InlineHints/CSharpInlineParameterNameHintsTests.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.UnitTests.InlineHints Public Class CSharpInlineParameterNameHintsTests Inherits AbstractInlineHintsTests <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNoParameterSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod() { return 5; } void Main() { testMethod(); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOneParameterSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x) { return x; } void Main() { testMethod({|x:|}5); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestTwoParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, double y) { return x; } void Main() { testMethod({|x:|}5, {|y:|}2); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNegativeNumberParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, double y) { return x; } void Main() { testMethod({|x:|}-5, {|y:|}2); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestLiteralNestedCastParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, double y) { return x; } void Main() { testMethod({|x:|}(int)(double)(int)5.5, {|y:|}2); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestObjectCreationParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod({|x:|}(int)5.5, {|y:|}new object()); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestCastingANegativeSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod({|x:|}(int)-5.5, {|y:|}new object()); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNegatingACastSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod({|x:|}-(int)5.5, {|y:|}new object()); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMissingParameterNameSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int) { return 5; } void Main() { testMethod(); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestDelegateParameter() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> delegate void D(int x); class C { public static void M1(int i) { } } class Test { static void Main() { D cd1 = new D(C.M1); cd1({|x:|}-1); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestFunctionPointerNoParameter() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" AllowUnsafe="true"> <Document> unsafe class Example { void Example(delegate*&lt;int, void&gt; f) { f(42); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestParamsArgument() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { public void UseParams(params int[] list) { } public void Main(string[] args) { UseParams({|list:|}1, 2, 3, 4, 5, 6); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestAttributesArgument() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; [Obsolete({|message:|}"test")] class Foo { } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestIncompleteFunctionCall() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod({|x:|}-(int)5.5,); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestInterpolatedString() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { string testMethod(string x) { return x; } void Main() { testMethod({|x:|}$""); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(47696, "https://github.com/dotnet/roslyn/issues/47696")> Public Async Function TestRecordBaseType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> record Base(int Alice, int Bob); record Derived(int Other) : Base({|Alice:|}2, {|Bob:|}2); </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(47696, "https://github.com/dotnet/roslyn/issues/47696")> Public Async Function TestClassBaseType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Base { public Base(int paramName) {} } class Derived : Base { public Derived() : base({|paramName:|}20) {} } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotOnEnableDisableBoolean1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void EnableLogging(bool value) { } void Main() { EnableLogging(true); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotOnEnableDisableBoolean2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void DisableLogging(bool value) { } void Main() { DisableLogging(true); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnEnableDisableNonBoolean1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void EnableLogging(string value) { } void Main() { EnableLogging({|value:|}"IO"); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnEnableDisableNonBoolean2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void DisableLogging(string value) { } void Main() { DisableLogging({|value:|}"IO"); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnSetMethodWithClearContext() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void SetClassification(string classification) { } void Main() { SetClassification("IO"); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnSetMethodWithUnclearContext() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void SetClassification(string values) { } void Main() { SetClassification({|values:|}"IO"); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithAlphaSuffix1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int objA, int objB, int objC) { } void Main() { Goo(1, 2, 3); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNonAlphaSuffix1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int objA, int objB, int nonobjC) { } void Main() { Goo({|objA:|}1, {|objB:|}2, {|nonobjC:|}3); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNumericSuffix1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int obj1, int obj2, int obj3) { } void Main() { Goo(1, 2, 3); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNonNumericSuffix1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int obj1, int obj2, int nonobj3) { } void Main() { Goo({|obj1:|}1, {|obj2:|}2, {|nonobj3:|}3); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(48910, "https://github.com/dotnet/roslyn/issues/48910")> Public Async Function TestNullableSuppression() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> #nullable enable class A { void M(string x) { } void Main() { M({|x:|}null!); } } </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(46614, "https://github.com/dotnet/roslyn/issues/46614")> Public Async Function TestIndexerParameter() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class TempRecord { // Array of temperature values float[] temps = new float[10] { 56.2F, 56.7F, 56.5F, 56.9F, 58.8F, 61.3F, 65.9F, 62.1F, 59.2F, 57.5F }; // To enable client code to validate input // when accessing your indexer. public int Length => temps.Length; // Indexer declaration. // If index is out of range, the temps array will throw the exception. public float this[int index] { get => temps[index]; set => temps[index] = value; } } class Program { static void Main() { var tempRecord = new TempRecord(); // Use the indexer's set accessor var temp = tempRecord[{|index:|}3]; } } </Document> </Project> </Workspace> Await VerifyParamHints(input) 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.UnitTests.InlineHints Public Class CSharpInlineParameterNameHintsTests Inherits AbstractInlineHintsTests <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNoParameterSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod() { return 5; } void Main() { testMethod(); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOneParameterSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x) { return x; } void Main() { testMethod({|x:|}5); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x) { return x; } void Main() { testMethod(x: 5); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestTwoParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, double y) { return x; } void Main() { testMethod({|x:|}5, {|y:|}2); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, double y) { return x; } void Main() { testMethod(x: 5, y: 2); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNegativeNumberParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, double y) { return x; } void Main() { testMethod({|x:|}-5, {|y:|}2); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, double y) { return x; } void Main() { testMethod(x: -5, y: 2); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestLiteralNestedCastParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, double y) { return x; } void Main() { testMethod({|x:|}(int)(double)(int)5.5, {|y:|}2); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, double y) { return x; } void Main() { testMethod(x: (int)(double)(int)5.5, y: 2); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestObjectCreationParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod({|x:|}(int)5.5, {|y:|}new object()); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod(x: (int)5.5, y: new object()); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestCastingANegativeSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod({|x:|}(int)-5.5, {|y:|}new object()); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod(x: (int)-5.5, y: new object()); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNegatingACastSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod({|x:|}-(int)5.5, {|y:|}new object()); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod(x: -(int)5.5, y: new object()); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMissingParameterNameSimpleCase() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int) { return 5; } void Main() { testMethod(); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestDelegateParameter() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> delegate void D(int x); class C { public static void M1(int i) { } } class Test { static void Main() { D cd1 = new D(C.M1); cd1({|x:|}-1); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> delegate void D(int x); class C { public static void M1(int i) { } } class Test { static void Main() { D cd1 = new D(C.M1); cd1(x: -1); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestFunctionPointerNoParameter() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true" AllowUnsafe="true"> <Document> unsafe class Example { void Example(delegate*&lt;int, void&gt; f) { f(42); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestParamsArgument() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { public void UseParams(params int[] list) { } public void Main(string[] args) { UseParams({|list:|}1, 2, 3, 4, 5, 6); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { public void UseParams(params int[] list) { } public void Main(string[] args) { UseParams(list: 1, 2, 3, 4, 5, 6); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestAttributesArgument() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; [Obsolete({|message:|}"test")] class Foo { } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System; [Obsolete(message: "test")] class Foo { } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestIncompleteFunctionCall() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod({|x:|}-(int)5.5,); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int testMethod(int x, object y) { return x; } void Main() { testMethod(x: -(int)5.5,); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestInterpolatedString() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { string testMethod(string x) { return x; } void Main() { testMethod({|x:|}$""); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { string testMethod(string x) { return x; } void Main() { testMethod(x: $""); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(47696, "https://github.com/dotnet/roslyn/issues/47696")> Public Async Function TestRecordBaseType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> record Base(int Alice, int Bob); record Derived(int Other) : Base({|Alice:|}2, {|Bob:|}2); </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> record Base(int Alice, int Bob); record Derived(int Other) : Base(Alice: 2, Bob: 2); </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(47696, "https://github.com/dotnet/roslyn/issues/47696")> Public Async Function TestClassBaseType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Base { public Base(int paramName) {} } class Derived : Base { public Derived() : base({|paramName:|}20) {} } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Base { public Base(int paramName) {} } class Derived : Base { public Derived() : base(paramName: 20) {} } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotOnEnableDisableBoolean1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void EnableLogging(bool value) { } void Main() { EnableLogging(true); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotOnEnableDisableBoolean2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void DisableLogging(bool value) { } void Main() { DisableLogging(true); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnEnableDisableNonBoolean1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void EnableLogging(string value) { } void Main() { EnableLogging({|value:|}"IO"); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void EnableLogging(string value) { } void Main() { EnableLogging(value: "IO"); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnEnableDisableNonBoolean2() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void DisableLogging(string value) { } void Main() { DisableLogging({|value:|}"IO"); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void DisableLogging(string value) { } void Main() { DisableLogging(value: "IO"); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnSetMethodWithClearContext() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void SetClassification(string classification) { } void Main() { SetClassification("IO"); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnSetMethodWithUnclearContext() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void SetClassification(string values) { } void Main() { SetClassification({|values:|}"IO"); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void SetClassification(string values) { } void Main() { SetClassification(values: "IO"); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithAlphaSuffix1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int objA, int objB, int objC) { } void Main() { Goo(1, 2, 3); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNonAlphaSuffix1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int objA, int objB, int nonobjC) { } void Main() { Goo({|objA:|}1, {|objB:|}2, {|nonobjC:|}3); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int objA, int objB, int nonobjC) { } void Main() { Goo(objA: 1, objB: 2, nonobjC: 3); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNumericSuffix1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int obj1, int obj2, int obj3) { } void Main() { Goo(1, 2, 3); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNonNumericSuffix1() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int obj1, int obj2, int nonobj3) { } void Main() { Goo({|obj1:|}1, {|obj2:|}2, {|nonobj3:|}3); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Goo(int obj1, int obj2, int nonobj3) { } void Main() { Goo(obj1: 1, obj2: 2, nonobj3: 3); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(48910, "https://github.com/dotnet/roslyn/issues/48910")> Public Async Function TestNullableSuppression() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> #nullable enable class A { void M(string x) { } void Main() { M({|x:|}null!); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> #nullable enable class A { void M(string x) { } void Main() { M(x: null!); } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(46614, "https://github.com/dotnet/roslyn/issues/46614")> Public Async Function TestIndexerParameter() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class TempRecord { // Array of temperature values float[] temps = new float[10] { 56.2F, 56.7F, 56.5F, 56.9F, 58.8F, 61.3F, 65.9F, 62.1F, 59.2F, 57.5F }; // To enable client code to validate input // when accessing your indexer. public int Length => temps.Length; // Indexer declaration. // If index is out of range, the temps array will throw the exception. public float this[int index] { get => temps[index]; set => temps[index] = value; } } class Program { static void Main() { var tempRecord = new TempRecord(); // Use the indexer's set accessor var temp = tempRecord[{|index:|}3]; } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> public class TempRecord { // Array of temperature values float[] temps = new float[10] { 56.2F, 56.7F, 56.5F, 56.9F, 58.8F, 61.3F, 65.9F, 62.1F, 59.2F, 57.5F }; // To enable client code to validate input // when accessing your indexer. public int Length => temps.Length; // Indexer declaration. // If index is out of range, the temps array will throw the exception. public float this[int index] { get => temps[index]; set => temps[index] = value; } } class Program { static void Main() { var tempRecord = new TempRecord(); // Use the indexer's set accessor var temp = tempRecord[index: 3]; } } </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function End Class End Namespace
1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/EditorFeatures/Test2/InlineHints/CSharpInlineTypeHintsTests.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.UnitTests.InlineHints Public Class CSharpInlineTypeHintsTests Inherits AbstractInlineHintsTests <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotOnLocalVariableWithType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main() { int i = 0; } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnLocalVariableWithVarType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main() { var {|int :|}i = 0; } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnLocalVariableWithVarType_Ephemeral() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main() { {|int:var|} i = 0; } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, ephemeral:=True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnDeconstruction() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main() { var ({|int :|}i, {|string :|}j) = (0, ""); } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestWithForeachVar() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { foreach (var {|string :|}j in args) {} } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestWithForeachVar_Ephemeral() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { foreach ({|string:var|} j in args) {} } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, ephemeral:=True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotWithForeachType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { foreach (string j in args) {} } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestWithPatternVar() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { if (args is { Length: var {|int :|}goo }) { } } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestWithPatternVar_Ephemeral() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { if (args is { Length: {|int:var|} goo }) { } } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, ephemeral:=True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotWithPatternType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { if (args is { Length: int goo }) { } } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestWithSimpleLambda() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Linq; class A { void Main(string[] args) { args.Where({|string :|}a => a.Length > 0); } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestWithParenthesizedLambda() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Linq; class A { void Main(string[] args) { args.Where(({|string :|}a) => a.Length > 0); } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotWithParenthesizedLambdaWithType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Linq; class A { void Main(string[] args) { args.Where((string a) => a.Length > 0); } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestWithDeclarationExpression() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { if (int.TryParse("", out var {|int :|}x)) { } } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestWithDeclarationExpression_Ephemeral() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { if (int.TryParse("", out {|int:var|} x)) { } } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, ephemeral:=True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(48941, "https://github.com/dotnet/roslyn/issues/48941")> Public Async Function TestNotWithStronglyTypedDeclarationExpression() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { if (int.TryParse("", out int x)) { } } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(49657, "https://github.com/dotnet/roslyn/issues/49657")> Public Async Function TestWithImplicitObjectCreation_InMethodArgument() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void M(int i) { } void Main(string[] args) { M(new{| int:|}()) { } } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(49657, "https://github.com/dotnet/roslyn/issues/49657")> Public Async Function TestWithImplicitObjectCreation_FieldInitializer() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int field = new{| int:|}(); } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(49657, "https://github.com/dotnet/roslyn/issues/49657")> Public Async Function TestWithImplicitObjectCreation_LocalInitializer() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void M() { int i = new{| int:|}(); } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(49657, "https://github.com/dotnet/roslyn/issues/49657")> Public Async Function TestWithImplicitObjectCreation_ParameterInitializer() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void M(System.Threading.CancellationToken ct = new{| CancellationToken:|}()) { } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(49657, "https://github.com/dotnet/roslyn/issues/49657")> Public Async Function TestWithImplicitObjectCreation_Return() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int M() { return new{| int:|}(); } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(49657, "https://github.com/dotnet/roslyn/issues/49657")> Public Async Function TestWithImplicitObjectCreation_IfExpression() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int M() { return true ? 1 : new{| int:|}(); } } </Document> </Project> </Workspace> Await VerifyTypeHints(input) 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.UnitTests.InlineHints Public Class CSharpInlineTypeHintsTests Inherits AbstractInlineHintsTests <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotOnLocalVariableWithType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main() { int i = 0; } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnLocalVariableWithVarType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main() { var {|int :|}i = 0; } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main() { int i = 0; } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnLocalVariableWithVarType_Ephemeral() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main() { {|int:var|} i = 0; } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main() { int i = 0; } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output, ephemeral:=True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnDeconstruction() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main() { var ({|int :|}i, {|string :|}j) = (0, ""); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main() { var (i, j) = (0, ""); } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestWithForeachVar() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { foreach (var {|string :|}j in args) {} } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { foreach (string j in args) {} } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestWithForeachVar_Ephemeral() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { foreach ({|string:var|} j in args) {} } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { foreach (string j in args) {} } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output, ephemeral:=True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotWithForeachType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { foreach (string j in args) {} } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestWithPatternVar() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { if (args is { Length: var {|int :|}goo }) { } } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { if (args is { Length: int goo }) { } } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestWithPatternVar_Ephemeral() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { if (args is { Length: {|int:var|} goo }) { } } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { if (args is { Length: int goo }) { } } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output, ephemeral:=True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotWithPatternType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { if (args is { Length: int goo }) { } } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestWithSimpleLambda() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Linq; class A { void Main(string[] args) { args.Where({|string :|}a => a.Length > 0); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Linq; class A { void Main(string[] args) { args.Where(a => a.Length > 0); } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestWithParenthesizedLambda() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Linq; class A { void Main(string[] args) { args.Where(({|string :|}a) => a.Length > 0); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Linq; class A { void Main(string[] args) { args.Where((string a) => a.Length > 0); } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotWithParenthesizedLambdaWithType() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Linq; class A { void Main(string[] args) { args.Where((string a) => a.Length > 0); } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestWithDeclarationExpression() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { if (int.TryParse("", out var {|int :|}x)) { } } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { if (int.TryParse("", out int x)) { } } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestWithDeclarationExpression_Ephemeral() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { if (int.TryParse("", out {|int:var|} x)) { } } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { if (int.TryParse("", out int x)) { } } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output, ephemeral:=True) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(48941, "https://github.com/dotnet/roslyn/issues/48941")> Public Async Function TestNotWithStronglyTypedDeclarationExpression() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void Main(string[] args) { if (int.TryParse("", out int x)) { } } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(49657, "https://github.com/dotnet/roslyn/issues/49657")> Public Async Function TestWithImplicitObjectCreation_InMethodArgument() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void M(int i) { } void Main(string[] args) { M(new{| int:|}()) { } } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void M(int i) { } void Main(string[] args) { M(new int()) { } } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(49657, "https://github.com/dotnet/roslyn/issues/49657")> Public Async Function TestWithImplicitObjectCreation_FieldInitializer() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int field = new{| int:|}(); } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int field = new int(); } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(49657, "https://github.com/dotnet/roslyn/issues/49657")> Public Async Function TestWithImplicitObjectCreation_LocalInitializer() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void M() { int i = new{| int:|}(); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void M() { int i = new int(); } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(49657, "https://github.com/dotnet/roslyn/issues/49657")> Public Async Function TestWithImplicitObjectCreation_ParameterInitializer() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void M(System.Threading.CancellationToken ct = new{| CancellationToken:|}()) { } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { void M(System.Threading.CancellationToken ct = new CancellationToken()) { } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(49657, "https://github.com/dotnet/roslyn/issues/49657")> Public Async Function TestWithImplicitObjectCreation_Return() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int M() { return new{| int:|}(); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int M() { return new int(); } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> <WorkItem(49657, "https://github.com/dotnet/roslyn/issues/49657")> Public Async Function TestWithImplicitObjectCreation_IfExpression() As Task Dim input = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int M() { return true ? 1 : new{| int:|}(); } } </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class A { int M() { return true ? 1 : new int(); } } </Document> </Project> </Workspace> Await VerifyTypeHints(input, output) End Function End Class End Namespace
1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/EditorFeatures/Test2/InlineHints/VisualBasicInlineParameterNameHintsTests.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.UnitTests.InlineHints Public Class VisualBasicInlineParameterNameHintsTests Inherits AbstractInlineHintsTests <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNoParameterSimpleCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod() End Sub Sub TestMethod() End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOneParameterSimpleCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}5) End Sub Sub TestMethod(x As Integer) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestTwoParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}5, {|y:|}2.2) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNegativeNumberParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}-5, {|y:|}2.2) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestCIntCast() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}CInt(5.5), {|y:|}2.2) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestCTypeCast() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}CType(5.5, Integer), {|y:|}2.2) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestTryCastCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Test Public Sub test(x As String) End Sub Public Sub Main() test({|x:|}TryCast(New Object(), String)) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestDirectCastCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Test Public Sub test(x As String) End Sub Public Sub Main() test({|x:|}DirectCast(New Object(), String)) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestCastingANegativeSimpleCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}CInt(-5.5), {|y:|}2.2) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestObjectCreationParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}CInt(-5.5), {|y:|}2.2, {|obj:|}New Object()) End Sub Sub TestMethod(x As Integer, y As Double, obj As Object) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMissingParameterNameSimpleCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod() End Sub Sub TestMethod(As Integer) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestDelegateParameter() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Test Public Delegate Sub TestDelegate(ByVal str As String) Public Sub TestTheDelegate(ByVal test As TestDelegate) test({|str:|}"Test") End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestParamsArgument() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Test Public Sub UseParams(ParamArray args() As Integer) End Sub Public Sub Main() UseParams({|args:|}1, 2, 3, 4, 5) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestAttributesArgument() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> &lt;Obsolete({|message:|}"test")&gt; Public Class Foo Sub TestMethod() End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestIncompleteFunctionCall() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}5,) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestInterpolatedString() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}$"") End Sub Sub TestMethod(x As String) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotOnEnableDisableBoolean1() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub EnableLogging(value as boolean) end sub sub Main() EnableLogging(true) end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotOnEnableDisableBoolean2() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub DisableLogging(value as boolean) end sub sub Main() DisableLogging(true) end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnEnableDisableNonBoolean1() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub EnableLogging(value as string) end sub sub Main() EnableLogging({|value:|}"IO") end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnEnableDisableNonBoolean2() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub DisableLogging(value as string) end sub sub Main() DisableLogging({|value:|}"IO") end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnSetMethodWithClearContext() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub SetClassification(classification as string) end sub sub Main() SetClassification("IO") end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnSetMethodWithUnclearContext() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub SetClassification(values as string) end sub sub Main() SetClassification({|values:|}"IO") end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithAlphaSuffix1() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub Goo(objA as integer, objB as integer, objC as integer) end sub sub Main() Goo(1, 2, 3) end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNonAlphaSuffix1() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub Goo(objA as integer, objB as integer, nonobjC as integer) end sub sub Main() Goo({|objA:|}1, {|objB:|}2, {|nonobjC:|}3) end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNumericSuffix1() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub Goo(obj1 as integer, obj2 as integer, obj3 as integer) end sub sub Main() Goo(1, 2, 3) end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNonNumericSuffix1() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub Goo(obj1 as integer, obj2 as integer, nonobj3 as integer) end sub sub Main() Goo({|obj1:|}1, {|obj2:|}2, {|nonobj3:|}3) end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input) 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.UnitTests.InlineHints Public Class VisualBasicInlineParameterNameHintsTests Inherits AbstractInlineHintsTests <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNoParameterSimpleCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod() End Sub Sub TestMethod() End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input, input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOneParameterSimpleCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}5) End Sub Sub TestMethod(x As Integer) End Sub End Class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod(x:=5) End Sub Sub TestMethod(x As Integer) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestTwoParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}5, {|y:|}2.2) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod(x:=5, y:=2.2) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNegativeNumberParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}-5, {|y:|}2.2) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod(x:=-5, y:=2.2) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestCIntCast() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}CInt(5.5), {|y:|}2.2) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod(x:=CInt(5.5), y:=2.2) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestCTypeCast() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}CType(5.5, Integer), {|y:|}2.2) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod(x:=CType(5.5, Integer), y:=2.2) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestTryCastCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Test Public Sub test(x As String) End Sub Public Sub Main() test({|x:|}TryCast(New Object(), String)) End Sub End Class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Test Public Sub test(x As String) End Sub Public Sub Main() test(x:=TryCast(New Object(), String)) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestDirectCastCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Test Public Sub test(x As String) End Sub Public Sub Main() test({|x:|}DirectCast(New Object(), String)) End Sub End Class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Test Public Sub test(x As String) End Sub Public Sub Main() test(x:=DirectCast(New Object(), String)) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestCastingANegativeSimpleCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}CInt(-5.5), {|y:|}2.2) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod(x:=CInt(-5.5), y:=2.2) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestObjectCreationParametersSimpleCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}CInt(-5.5), {|y:|}2.2, {|obj:|}New Object()) End Sub Sub TestMethod(x As Integer, y As Double, obj As Object) End Sub End Class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod(x:=CInt(-5.5), y:=2.2, obj:=New Object()) End Sub Sub TestMethod(x As Integer, y As Double, obj As Object) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMissingParameterNameSimpleCase() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod() End Sub Sub TestMethod(As Integer) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input, input) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestDelegateParameter() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Test Public Delegate Sub TestDelegate(ByVal str As String) Public Sub TestTheDelegate(ByVal test As TestDelegate) test({|str:|}"Test") End Sub End Class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Test Public Delegate Sub TestDelegate(ByVal str As String) Public Sub TestTheDelegate(ByVal test As TestDelegate) test(str:="Test") End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestParamsArgument() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Test Public Sub UseParams(ParamArray args() As Integer) End Sub Public Sub Main() UseParams({|args:|}1, 2, 3, 4, 5) End Sub End Class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Test Public Sub UseParams(ParamArray args() As Integer) End Sub Public Sub Main() UseParams(args:=1, 2, 3, 4, 5) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestAttributesArgument() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> &lt;Obsolete({|message:|}"test")&gt; Public Class Foo Sub TestMethod() End Sub End Class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> &lt;Obsolete(message:="test")&gt; Public Class Foo Sub TestMethod() End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestIncompleteFunctionCall() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}5,) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod(x:=5,) End Sub Sub TestMethod(x As Integer, y As Double) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestInterpolatedString() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod({|x:|}$"") End Sub Sub TestMethod(x As String) End Sub End Class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class Foo Sub Main(args As String()) TestMethod(x:=$"") End Sub Sub TestMethod(x As String) End Sub End Class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotOnEnableDisableBoolean1() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub EnableLogging(value as boolean) end sub sub Main() EnableLogging(true) end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input, input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestNotOnEnableDisableBoolean2() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub DisableLogging(value as boolean) end sub sub Main() DisableLogging(true) end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input, input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnEnableDisableNonBoolean1() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub EnableLogging(value as string) end sub sub Main() EnableLogging({|value:|}"IO") end sub end class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub EnableLogging(value as string) end sub sub Main() EnableLogging(value:="IO") end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnEnableDisableNonBoolean2() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub DisableLogging(value as string) end sub sub Main() DisableLogging({|value:|}"IO") end sub end class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub DisableLogging(value as string) end sub sub Main() DisableLogging(value:="IO") end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnSetMethodWithClearContext() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub SetClassification(classification as string) end sub sub Main() SetClassification("IO") end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input, input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestOnSetMethodWithUnclearContext() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub SetClassification(values as string) end sub sub Main() SetClassification({|values:|}"IO") end sub end class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub SetClassification(values as string) end sub sub Main() SetClassification(values:="IO") end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithAlphaSuffix1() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub Goo(objA as integer, objB as integer, objC as integer) end sub sub Main() Goo(1, 2, 3) end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input, input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNonAlphaSuffix1() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub Goo(objA as integer, objB as integer, nonobjC as integer) end sub sub Main() Goo({|objA:|}1, {|objB:|}2, {|nonobjC:|}3) end sub end class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub Goo(objA as integer, objB as integer, nonobjC as integer) end sub sub Main() Goo(objA:=1, objB:=2, nonobjC:=3) end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNumericSuffix1() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub Goo(obj1 as integer, obj2 as integer, obj3 as integer) end sub sub Main() Goo(1, 2, 3) end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input, input) End Function <WorkItem(47597, "https://github.com/dotnet/roslyn/issues/47597")> <WpfFact, Trait(Traits.Feature, Traits.Features.InlineHints)> Public Async Function TestMethodWithNonNumericSuffix1() As Task Dim input = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub Goo(obj1 as integer, obj2 as integer, nonobj3 as integer) end sub sub Main() Goo({|obj1:|}1, {|obj2:|}2, {|nonobj3:|}3) end sub end class </Document> </Project> </Workspace> Dim output = <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> class A sub Goo(obj1 as integer, obj2 as integer, nonobj3 as integer) end sub sub Main() Goo(obj1:=1, obj2:=2, nonobj3:=3) end sub end class </Document> </Project> </Workspace> Await VerifyParamHints(input, output) End Function End Class End Namespace
1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/CSharp/Portable/InlineHints/CSharpInlineParameterNameHintsService.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.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.InlineHints { /// <summary> /// The service to locate the positions in which the adornments should appear /// as well as associate the adornments back to the parameter name /// </summary> [ExportLanguageService(typeof(IInlineParameterNameHintsService), LanguageNames.CSharp), Shared] internal class CSharpInlineParameterNameHintsService : AbstractInlineParameterNameHintsService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpInlineParameterNameHintsService(IGlobalOptionService globalOptions) : base(globalOptions) { } protected override void AddAllParameterNameHintLocations( SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, SyntaxNode node, ArrayBuilder<(int position, string? identifierArgument, IParameterSymbol? parameter, HintKind kind)> buffer, CancellationToken cancellationToken) { if (node is BaseArgumentListSyntax argumentList) { AddArguments(semanticModel, syntaxFacts, buffer, argumentList, cancellationToken); } else if (node is AttributeArgumentListSyntax attributeArgumentList) { AddArguments(semanticModel, syntaxFacts, buffer, attributeArgumentList, cancellationToken); } } private static void AddArguments( SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, ArrayBuilder<(int position, string? identifierArgument, IParameterSymbol? parameter, HintKind kind)> buffer, AttributeArgumentListSyntax argumentList, CancellationToken cancellationToken) { foreach (var argument in argumentList.Arguments) { if (argument.NameEquals != null || argument.NameColon != null) continue; var parameter = argument.DetermineParameter(semanticModel, cancellationToken: cancellationToken); var identifierArgument = GetIdentifierNameFromArgument(argument, syntaxFacts); buffer.Add((argument.Span.Start, identifierArgument, parameter, GetKind(argument.Expression))); } } private static void AddArguments( SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, ArrayBuilder<(int position, string? identifierArgument, IParameterSymbol? parameter, HintKind kind)> buffer, BaseArgumentListSyntax argumentList, CancellationToken cancellationToken) { foreach (var argument in argumentList.Arguments) { if (argument.NameColon != null) continue; var parameter = argument.DetermineParameter(semanticModel, cancellationToken: cancellationToken); var identifierArgument = GetIdentifierNameFromArgument(argument, syntaxFacts); buffer.Add((argument.Span.Start, identifierArgument, parameter, GetKind(argument.Expression))); } } private static HintKind GetKind(ExpressionSyntax arg) => arg switch { LiteralExpressionSyntax or InterpolatedStringExpressionSyntax => HintKind.Literal, ObjectCreationExpressionSyntax => HintKind.ObjectCreation, CastExpressionSyntax cast => GetKind(cast.Expression), PrefixUnaryExpressionSyntax prefix => GetKind(prefix.Operand), // Treat `expr!` the same as `expr` (i.e. treat `!` as if it's just trivia). PostfixUnaryExpressionSyntax(SyntaxKind.SuppressNullableWarningExpression) postfix => GetKind(postfix.Operand), _ => HintKind.Other, }; protected override bool IsIndexer(SyntaxNode node, IParameterSymbol parameter) { return node is BracketedArgumentListSyntax; } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.InlineHints { /// <summary> /// The service to locate the positions in which the adornments should appear /// as well as associate the adornments back to the parameter name /// </summary> [ExportLanguageService(typeof(IInlineParameterNameHintsService), LanguageNames.CSharp), Shared] internal class CSharpInlineParameterNameHintsService : AbstractInlineParameterNameHintsService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpInlineParameterNameHintsService(IGlobalOptionService globalOptions) : base(globalOptions) { } protected override void AddAllParameterNameHintLocations( SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, SyntaxNode node, ArrayBuilder<(int position, string? identifierArgument, IParameterSymbol? parameter, HintKind kind)> buffer, CancellationToken cancellationToken) { if (node is BaseArgumentListSyntax argumentList) { AddArguments(semanticModel, syntaxFacts, buffer, argumentList, cancellationToken); } else if (node is AttributeArgumentListSyntax attributeArgumentList) { AddArguments(semanticModel, syntaxFacts, buffer, attributeArgumentList, cancellationToken); } } private static void AddArguments( SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, ArrayBuilder<(int position, string? identifierArgument, IParameterSymbol? parameter, HintKind kind)> buffer, AttributeArgumentListSyntax argumentList, CancellationToken cancellationToken) { foreach (var argument in argumentList.Arguments) { if (argument.NameEquals != null || argument.NameColon != null) continue; var parameter = argument.DetermineParameter(semanticModel, cancellationToken: cancellationToken); var identifierArgument = GetIdentifierNameFromArgument(argument, syntaxFacts); buffer.Add((argument.Span.Start, identifierArgument, parameter, GetKind(argument.Expression))); } } private static void AddArguments( SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, ArrayBuilder<(int position, string? identifierArgument, IParameterSymbol? parameter, HintKind kind)> buffer, BaseArgumentListSyntax argumentList, CancellationToken cancellationToken) { foreach (var argument in argumentList.Arguments) { if (argument.NameColon != null) continue; var parameter = argument.DetermineParameter(semanticModel, cancellationToken: cancellationToken); var identifierArgument = GetIdentifierNameFromArgument(argument, syntaxFacts); buffer.Add((argument.Span.Start, identifierArgument, parameter, GetKind(argument.Expression))); } } private static HintKind GetKind(ExpressionSyntax arg) => arg switch { LiteralExpressionSyntax or InterpolatedStringExpressionSyntax => HintKind.Literal, ObjectCreationExpressionSyntax => HintKind.ObjectCreation, CastExpressionSyntax cast => GetKind(cast.Expression), PrefixUnaryExpressionSyntax prefix => GetKind(prefix.Operand), // Treat `expr!` the same as `expr` (i.e. treat `!` as if it's just trivia). PostfixUnaryExpressionSyntax(SyntaxKind.SuppressNullableWarningExpression) postfix => GetKind(postfix.Operand), _ => HintKind.Other, }; protected override bool IsIndexer(SyntaxNode node, IParameterSymbol parameter) { return node is BracketedArgumentListSyntax; } protected override string GetReplacementText(string parameterName) { return parameterName + ": "; } } }
1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/CSharp/Portable/InlineHints/CSharpInlineTypeHintsService.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.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.InlineHints { [ExportLanguageService(typeof(IInlineTypeHintsService), LanguageNames.CSharp), Shared] internal sealed class CSharpInlineTypeHintsService : AbstractInlineTypeHintsService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpInlineTypeHintsService(IGlobalOptionService globalOptions) : base(globalOptions) { } protected override TypeHint? TryGetTypeHint( SemanticModel semanticModel, SyntaxNode node, bool displayAllOverride, bool forImplicitVariableTypes, bool forLambdaParameterTypes, bool forImplicitObjectCreation, CancellationToken cancellationToken) { if (forImplicitVariableTypes || displayAllOverride) { if (node is VariableDeclarationSyntax { Type: { IsVar: true } } variableDeclaration && variableDeclaration.Variables.Count == 1 && !variableDeclaration.Variables[0].Identifier.IsMissing) { var type = semanticModel.GetTypeInfo(variableDeclaration.Type, cancellationToken).Type; if (IsValidType(type)) return CreateTypeHint(type, displayAllOverride, forImplicitVariableTypes, variableDeclaration.Type, variableDeclaration.Variables[0].Identifier); } if (node is DeclarationExpressionSyntax { Type: { IsVar: true } } declarationExpression) { var type = semanticModel.GetTypeInfo(declarationExpression.Type, cancellationToken).Type; if (IsValidType(type)) return CreateTypeHint(type, displayAllOverride, forImplicitVariableTypes, declarationExpression.Type, declarationExpression.Designation); } else if (node is SingleVariableDesignationSyntax { Parent: not DeclarationPatternSyntax and not DeclarationExpressionSyntax } variableDesignation) { var local = semanticModel.GetDeclaredSymbol(variableDesignation, cancellationToken) as ILocalSymbol; var type = local?.Type; if (IsValidType(type)) { return node.Parent is VarPatternSyntax varPattern ? CreateTypeHint(type, displayAllOverride, forImplicitVariableTypes, varPattern.VarKeyword, variableDesignation.Identifier) : new(type, new TextSpan(variableDesignation.Identifier.SpanStart, 0), trailingSpace: true); } } else if (node is ForEachStatementSyntax { Type: { IsVar: true } } forEachStatement) { var info = semanticModel.GetForEachStatementInfo(forEachStatement); var type = info.ElementType; if (IsValidType(type)) return CreateTypeHint(type, displayAllOverride, forImplicitVariableTypes, forEachStatement.Type, forEachStatement.Identifier); } } if (forLambdaParameterTypes || displayAllOverride) { if (node is ParameterSyntax { Type: null } parameterNode) { var parameter = semanticModel.GetDeclaredSymbol(parameterNode, cancellationToken); if (parameter?.ContainingSymbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction } && IsValidType(parameter?.Type)) { return new(parameter.Type, new TextSpan(parameterNode.Identifier.SpanStart, 0), trailingSpace: true); } } } if (forImplicitObjectCreation || displayAllOverride) { if (node is ImplicitObjectCreationExpressionSyntax implicitNew) { var type = semanticModel.GetTypeInfo(implicitNew, cancellationToken).Type; if (IsValidType(type)) { return new(type, new TextSpan(implicitNew.NewKeyword.Span.End, 0), leadingSpace: true); } } } return null; } private static TypeHint CreateTypeHint( ITypeSymbol type, bool displayAllOverride, bool normalOption, SyntaxNodeOrToken displayAllSpan, SyntaxNodeOrToken normalSpan) { var span = GetSpan(displayAllOverride, normalOption, displayAllSpan, normalSpan); // if this is a hint that is placed in-situ (i.e. it's not overwriting text like 'var'), then place // a space after it to make things feel less cramped. var trailingSpace = span.Length == 0; return new TypeHint(type, span, trailingSpace: trailingSpace); } private static TextSpan GetSpan( bool displayAllOverride, bool normalOption, SyntaxNodeOrToken displayAllSpan, SyntaxNodeOrToken normalSpan) { // If we're showing this because the normal option is on, then place the hint prior to the node being marked. if (normalOption) return new TextSpan(normalSpan.SpanStart, 0); // Otherwise, we're showing because the user explicitly asked to see all hints. In that case, overwrite the // provided span (i.e. overwrite 'var' with 'int') as this provides a cleaner view while the user is in this // mode. Contract.ThrowIfFalse(displayAllOverride); return displayAllSpan.Span; } private static bool IsValidType([NotNullWhen(true)] ITypeSymbol? type) { return type is not null or IErrorTypeSymbol && type.Name != "var"; } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.InlineHints; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.InlineHints { [ExportLanguageService(typeof(IInlineTypeHintsService), LanguageNames.CSharp), Shared] internal sealed class CSharpInlineTypeHintsService : AbstractInlineTypeHintsService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpInlineTypeHintsService(IGlobalOptionService globalOptions) : base(globalOptions) { } protected override TypeHint? TryGetTypeHint( SemanticModel semanticModel, SyntaxNode node, bool displayAllOverride, bool forImplicitVariableTypes, bool forLambdaParameterTypes, bool forImplicitObjectCreation, CancellationToken cancellationToken) { if (forImplicitVariableTypes || displayAllOverride) { if (node is VariableDeclarationSyntax { Type: { IsVar: true } } variableDeclaration && variableDeclaration.Variables.Count == 1 && !variableDeclaration.Variables[0].Identifier.IsMissing) { var type = semanticModel.GetTypeInfo(variableDeclaration.Type, cancellationToken).Type; if (IsValidType(type)) return CreateTypeHint(type, displayAllOverride, forImplicitVariableTypes, variableDeclaration.Type, variableDeclaration.Variables[0].Identifier); } if (node is DeclarationExpressionSyntax { Type: { IsVar: true } } declarationExpression) { var type = semanticModel.GetTypeInfo(declarationExpression.Type, cancellationToken).Type; if (IsValidType(type)) return CreateTypeHint(type, displayAllOverride, forImplicitVariableTypes, declarationExpression.Type, declarationExpression.Designation); } else if (node is SingleVariableDesignationSyntax { Parent: not DeclarationPatternSyntax and not DeclarationExpressionSyntax } variableDesignation) { var local = semanticModel.GetDeclaredSymbol(variableDesignation, cancellationToken) as ILocalSymbol; var type = local?.Type; if (IsValidType(type)) { return node.Parent is VarPatternSyntax varPattern ? CreateTypeHint(type, displayAllOverride, forImplicitVariableTypes, varPattern.VarKeyword, variableDesignation.Identifier) : new(type, new TextSpan(variableDesignation.Identifier.SpanStart, 0), textChange: null, trailingSpace: true); } } else if (node is ForEachStatementSyntax { Type: { IsVar: true } } forEachStatement) { var info = semanticModel.GetForEachStatementInfo(forEachStatement); var type = info.ElementType; if (IsValidType(type)) return CreateTypeHint(type, displayAllOverride, forImplicitVariableTypes, forEachStatement.Type, forEachStatement.Identifier); } } if (forLambdaParameterTypes || displayAllOverride) { if (node is ParameterSyntax { Type: null } parameterNode) { var span = new TextSpan(parameterNode.Identifier.SpanStart, 0); var parameter = semanticModel.GetDeclaredSymbol(parameterNode, cancellationToken); if (parameter?.ContainingSymbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction } && IsValidType(parameter?.Type)) { return parameterNode.Parent?.Parent?.Kind() is SyntaxKind.ParenthesizedLambdaExpression ? new TypeHint(parameter.Type, span, textChange: new TextChange(span, parameter.Type.ToDisplayString(s_minimalTypeStyle) + " "), trailingSpace: true) : new TypeHint(parameter.Type, span, textChange: null, trailingSpace: true); } } } if (forImplicitObjectCreation || displayAllOverride) { if (node is ImplicitObjectCreationExpressionSyntax implicitNew) { var type = semanticModel.GetTypeInfo(implicitNew, cancellationToken).Type; if (IsValidType(type)) { var span = new TextSpan(implicitNew.NewKeyword.Span.End, 0); return new(type, span, new TextChange(span, " " + type.ToDisplayString(s_minimalTypeStyle)), leadingSpace: true); } } } return null; } private static TypeHint CreateTypeHint( ITypeSymbol type, bool displayAllOverride, bool normalOption, SyntaxNodeOrToken displayAllSpan, SyntaxNodeOrToken normalSpan) { var span = GetSpan(displayAllOverride, normalOption, displayAllSpan, normalSpan); // if this is a hint that is placed in-situ (i.e. it's not overwriting text like 'var'), then place // a space after it to make things feel less cramped. var trailingSpace = span.Length == 0; return new TypeHint(type, span, new TextChange(displayAllSpan.Span, type.ToDisplayString(s_minimalTypeStyle)), trailingSpace: trailingSpace); } private static TextSpan GetSpan( bool displayAllOverride, bool normalOption, SyntaxNodeOrToken displayAllSpan, SyntaxNodeOrToken normalSpan) { // If we're showing this because the normal option is on, then place the hint prior to the node being marked. if (normalOption) return new TextSpan(normalSpan.SpanStart, 0); // Otherwise, we're showing because the user explicitly asked to see all hints. In that case, overwrite the // provided span (i.e. overwrite 'var' with 'int') as this provides a cleaner view while the user is in this // mode. Contract.ThrowIfFalse(displayAllOverride); return displayAllSpan.Span; } private static bool IsValidType([NotNullWhen(true)] ITypeSymbol? type) { return type is not null or IErrorTypeSymbol && type.Name != "var"; } } }
1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/Core/Portable/InlineHints/AbstractInlineParameterNameHintsService.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.InlineHints { internal abstract class AbstractInlineParameterNameHintsService : IInlineParameterNameHintsService { private readonly IGlobalOptionService _globalOptions; protected enum HintKind { Literal, ObjectCreation, Other } public AbstractInlineParameterNameHintsService(IGlobalOptionService globalOptions) { _globalOptions = globalOptions; } protected abstract void AddAllParameterNameHintLocations( SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, SyntaxNode node, ArrayBuilder<(int position, string? identifierArgument, IParameterSymbol? parameter, HintKind kind)> buffer, CancellationToken cancellationToken); protected abstract bool IsIndexer(SyntaxNode node, IParameterSymbol parameter); public async Task<ImmutableArray<InlineHint>> GetInlineHintsAsync(Document document, TextSpan textSpan, InlineParameterHintsOptions options, SymbolDescriptionOptions displayOptions, CancellationToken cancellationToken) { var displayAllOverride = _globalOptions.GetOption(InlineHintsGlobalStateOption.DisplayAllOverride); var enabledForParameters = displayAllOverride || options.EnabledForParameters; if (!enabledForParameters) return ImmutableArray<InlineHint>.Empty; var literalParameters = displayAllOverride || options.ForLiteralParameters; var objectCreationParameters = displayAllOverride || options.ForObjectCreationParameters; var otherParameters = displayAllOverride || options.ForOtherParameters; if (!literalParameters && !objectCreationParameters && !otherParameters) return ImmutableArray<InlineHint>.Empty; var indexerParameters = displayAllOverride || options.ForIndexerParameters; var suppressForParametersThatDifferOnlyBySuffix = !displayAllOverride && options.SuppressForParametersThatDifferOnlyBySuffix; var suppressForParametersThatMatchMethodIntent = !displayAllOverride && options.SuppressForParametersThatMatchMethodIntent; var suppressForParametersThatMatchArgumentName = !displayAllOverride && options.SuppressForParametersThatMatchArgumentName; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); using var _1 = ArrayBuilder<InlineHint>.GetInstance(out var result); using var _2 = ArrayBuilder<(int position, string? identifierArgument, IParameterSymbol? parameter, HintKind kind)>.GetInstance(out var buffer); foreach (var node in root.DescendantNodes(textSpan, n => n.Span.IntersectsWith(textSpan))) { cancellationToken.ThrowIfCancellationRequested(); AddAllParameterNameHintLocations(semanticModel, syntaxFacts, node, buffer, cancellationToken); if (buffer.Count > 0) { AddHintsIfAppropriate(node); buffer.Clear(); } } return result.ToImmutable(); void AddHintsIfAppropriate(SyntaxNode node) { if (suppressForParametersThatDifferOnlyBySuffix && ParametersDifferOnlyBySuffix(buffer)) return; foreach (var (position, identifierArgument, parameter, kind) in buffer) { if (string.IsNullOrEmpty(parameter?.Name)) continue; if (suppressForParametersThatMatchMethodIntent && MatchesMethodIntent(parameter)) continue; if (suppressForParametersThatMatchArgumentName && ParameterMatchesArgumentName(identifierArgument, parameter, syntaxFacts)) continue; if (!indexerParameters && IsIndexer(node, parameter)) continue; if (HintMatches(kind, literalParameters, objectCreationParameters, otherParameters)) { result.Add(new InlineHint( new TextSpan(position, 0), ImmutableArray.Create(new TaggedText(TextTags.Text, parameter.Name + ": ")), InlineHintHelpers.GetDescriptionFunction(position, parameter.GetSymbolKey(cancellationToken: cancellationToken), displayOptions))); } } } } private static bool ParametersDifferOnlyBySuffix( ArrayBuilder<(int position, string? identifierArgument, IParameterSymbol? parameter, HintKind kind)> parameterHints) { // Only relevant if we have two or more parameters. if (parameterHints.Count <= 1) return false; return ParametersDifferOnlyByAlphaSuffix(parameterHints) || ParametersDifferOnlyByNumericSuffix(parameterHints); static bool ParametersDifferOnlyByAlphaSuffix( ArrayBuilder<(int position, string? identifierArgument, IParameterSymbol? parameter, HintKind kind)> parameterHints) { if (!HasAlphaSuffix(parameterHints[0].parameter, out var firstPrefix)) return false; for (var i = 1; i < parameterHints.Count; i++) { if (!HasAlphaSuffix(parameterHints[i].parameter, out var nextPrefix)) return false; if (!firstPrefix.Span.Equals(nextPrefix.Span, StringComparison.Ordinal)) return false; } return true; } static bool ParametersDifferOnlyByNumericSuffix( ArrayBuilder<(int position, string? identifierArgument, IParameterSymbol? parameter, HintKind kind)> parameterHints) { if (!HasNumericSuffix(parameterHints[0].parameter, out var firstPrefix)) return false; for (var i = 1; i < parameterHints.Count; i++) { if (!HasNumericSuffix(parameterHints[i].parameter, out var nextPrefix)) return false; if (!firstPrefix.Span.Equals(nextPrefix.Span, StringComparison.Ordinal)) return false; } return true; } static bool HasAlphaSuffix(IParameterSymbol? parameter, out ReadOnlyMemory<char> prefix) { var name = parameter?.Name; // Has to end with A-Z // That A-Z can't be following another A-Z (that's just a capitalized word). if (name?.Length >= 2 && IsUpperAlpha(name[^1]) && !IsUpperAlpha(name[^2])) { prefix = name.AsMemory()[..^1]; return true; } prefix = default; return false; } static bool HasNumericSuffix(IParameterSymbol? parameter, out ReadOnlyMemory<char> prefix) { var name = parameter?.Name; // Has to end with 0-9. only handles single-digit numeric suffix for now for simplicity if (name?.Length >= 2 && IsNumeric(name[^1])) { prefix = name.AsMemory()[..^1]; return true; } prefix = default; return false; } static bool IsUpperAlpha(char c) => c is >= 'A' and <= 'Z'; static bool IsNumeric(char c) => c is >= '0' and <= '9'; } private static bool HintMatches(HintKind kind, bool literalParameters, bool objectCreationParameters, bool otherParameters) { return kind switch { HintKind.Literal => literalParameters, HintKind.ObjectCreation => objectCreationParameters, HintKind.Other => otherParameters, _ => throw ExceptionUtilities.UnexpectedValue(kind), }; } protected static bool MatchesMethodIntent(IParameterSymbol? parameter) { // Methods like `SetColor(color: "y")` `FromResult(result: "x")` `Enable/DisablePolling(bool)` don't need // parameter names to improve clarity. The parameter is clear from the context of the method name. // First, this only applies to methods (as we're looking at the method name itself) so filter down to those. if (parameter is not { ContainingSymbol: IMethodSymbol { MethodKind: MethodKind.Ordinary } method }) return false; // We only care when dealing with the first parameter. Note: we don't have to worry parameter reordering // due to named-parameter use. That's because this entire feature only works when we don't use // named-parameters. So, by definition, the parameter/arg must be in the right location. if (method.Parameters[0] != parameter) return false; var methodName = method.Name; // Check for something like `EnableLogging(true)` if (TryGetSuffix("Enable", methodName, out _) || TryGetSuffix("Disable", methodName, out _)) { return parameter.Type.SpecialType == SpecialType.System_Boolean; } // More names can be added here if we find other patterns like this. if (TryGetSuffix("Set", methodName, out var suffix) || TryGetSuffix("From", methodName, out suffix)) { return SuffixMatchesParameterName(suffix, parameter.Name); } return false; static bool TryGetSuffix(string prefix, string nameValue, out ReadOnlyMemory<char> suffix) { if (nameValue.Length > prefix.Length && nameValue.StartsWith(prefix) && char.IsUpper(nameValue[prefix.Length])) { suffix = nameValue.AsMemory()[prefix.Length..]; return true; } suffix = default; return false; } static bool SuffixMatchesParameterName(ReadOnlyMemory<char> suffix, string parameterName) { // Method's name will be something like 'FromResult', so 'suffix' will be 'Result' and parameterName // will be 'result'. So we check if the first letters differ on case and the rest of the method // matches. return char.ToLower(suffix.Span[0]) == parameterName[0] && suffix.Span[1..].Equals(parameterName.AsSpan()[1..], StringComparison.Ordinal); } } private static bool ParameterMatchesArgumentName(string? identifierArgument, IParameterSymbol parameter, ISyntaxFactsService syntaxFacts) => syntaxFacts.StringComparer.Compare(parameter.Name, identifierArgument) == 0; protected static string GetIdentifierNameFromArgument(SyntaxNode argument, ISyntaxFactsService syntaxFacts) { var identifierNameSyntax = syntaxFacts.IsArgument(argument) ? syntaxFacts.GetExpressionOfArgument(argument) : syntaxFacts.IsAttributeArgument(argument) ? syntaxFacts.GetExpressionOfAttributeArgument(argument) : null; if (!syntaxFacts.IsIdentifierName(identifierNameSyntax)) return string.Empty; var identifier = syntaxFacts.GetIdentifierOfIdentifierName(identifierNameSyntax); return identifier.ValueText; } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.InlineHints { internal abstract class AbstractInlineParameterNameHintsService : IInlineParameterNameHintsService { private readonly IGlobalOptionService _globalOptions; protected enum HintKind { Literal, ObjectCreation, Other } public AbstractInlineParameterNameHintsService(IGlobalOptionService globalOptions) { _globalOptions = globalOptions; } protected abstract void AddAllParameterNameHintLocations( SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, SyntaxNode node, ArrayBuilder<(int position, string? identifierArgument, IParameterSymbol? parameter, HintKind kind)> buffer, CancellationToken cancellationToken); protected abstract bool IsIndexer(SyntaxNode node, IParameterSymbol parameter); protected abstract string GetReplacementText(string parameterName); public async Task<ImmutableArray<InlineHint>> GetInlineHintsAsync(Document document, TextSpan textSpan, InlineParameterHintsOptions options, SymbolDescriptionOptions displayOptions, CancellationToken cancellationToken) { var displayAllOverride = _globalOptions.GetOption(InlineHintsGlobalStateOption.DisplayAllOverride); var enabledForParameters = displayAllOverride || options.EnabledForParameters; if (!enabledForParameters) return ImmutableArray<InlineHint>.Empty; var literalParameters = displayAllOverride || options.ForLiteralParameters; var objectCreationParameters = displayAllOverride || options.ForObjectCreationParameters; var otherParameters = displayAllOverride || options.ForOtherParameters; if (!literalParameters && !objectCreationParameters && !otherParameters) return ImmutableArray<InlineHint>.Empty; var indexerParameters = displayAllOverride || options.ForIndexerParameters; var suppressForParametersThatDifferOnlyBySuffix = !displayAllOverride && options.SuppressForParametersThatDifferOnlyBySuffix; var suppressForParametersThatMatchMethodIntent = !displayAllOverride && options.SuppressForParametersThatMatchMethodIntent; var suppressForParametersThatMatchArgumentName = !displayAllOverride && options.SuppressForParametersThatMatchArgumentName; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); using var _1 = ArrayBuilder<InlineHint>.GetInstance(out var result); using var _2 = ArrayBuilder<(int position, string? identifierArgument, IParameterSymbol? parameter, HintKind kind)>.GetInstance(out var buffer); foreach (var node in root.DescendantNodes(textSpan, n => n.Span.IntersectsWith(textSpan))) { cancellationToken.ThrowIfCancellationRequested(); AddAllParameterNameHintLocations(semanticModel, syntaxFacts, node, buffer, cancellationToken); if (buffer.Count > 0) { AddHintsIfAppropriate(node); buffer.Clear(); } } return result.ToImmutable(); void AddHintsIfAppropriate(SyntaxNode node) { if (suppressForParametersThatDifferOnlyBySuffix && ParametersDifferOnlyBySuffix(buffer)) return; foreach (var (position, identifierArgument, parameter, kind) in buffer) { if (string.IsNullOrEmpty(parameter?.Name)) continue; if (suppressForParametersThatMatchMethodIntent && MatchesMethodIntent(parameter)) continue; if (suppressForParametersThatMatchArgumentName && ParameterMatchesArgumentName(identifierArgument, parameter, syntaxFacts)) continue; if (!indexerParameters && IsIndexer(node, parameter)) continue; if (HintMatches(kind, literalParameters, objectCreationParameters, otherParameters)) { var inlineHintText = GetReplacementText(parameter.Name); var textSpan = new TextSpan(position, 0); result.Add(new InlineHint( textSpan, ImmutableArray.Create(new TaggedText(TextTags.Text, parameter.Name + ": ")), new TextChange(textSpan, inlineHintText), InlineHintHelpers.GetDescriptionFunction(position, parameter.GetSymbolKey(cancellationToken: cancellationToken), displayOptions))); } } } } private static bool ParametersDifferOnlyBySuffix( ArrayBuilder<(int position, string? identifierArgument, IParameterSymbol? parameter, HintKind kind)> parameterHints) { // Only relevant if we have two or more parameters. if (parameterHints.Count <= 1) return false; return ParametersDifferOnlyByAlphaSuffix(parameterHints) || ParametersDifferOnlyByNumericSuffix(parameterHints); static bool ParametersDifferOnlyByAlphaSuffix( ArrayBuilder<(int position, string? identifierArgument, IParameterSymbol? parameter, HintKind kind)> parameterHints) { if (!HasAlphaSuffix(parameterHints[0].parameter, out var firstPrefix)) return false; for (var i = 1; i < parameterHints.Count; i++) { if (!HasAlphaSuffix(parameterHints[i].parameter, out var nextPrefix)) return false; if (!firstPrefix.Span.Equals(nextPrefix.Span, StringComparison.Ordinal)) return false; } return true; } static bool ParametersDifferOnlyByNumericSuffix( ArrayBuilder<(int position, string? identifierArgument, IParameterSymbol? parameter, HintKind kind)> parameterHints) { if (!HasNumericSuffix(parameterHints[0].parameter, out var firstPrefix)) return false; for (var i = 1; i < parameterHints.Count; i++) { if (!HasNumericSuffix(parameterHints[i].parameter, out var nextPrefix)) return false; if (!firstPrefix.Span.Equals(nextPrefix.Span, StringComparison.Ordinal)) return false; } return true; } static bool HasAlphaSuffix(IParameterSymbol? parameter, out ReadOnlyMemory<char> prefix) { var name = parameter?.Name; // Has to end with A-Z // That A-Z can't be following another A-Z (that's just a capitalized word). if (name?.Length >= 2 && IsUpperAlpha(name[^1]) && !IsUpperAlpha(name[^2])) { prefix = name.AsMemory()[..^1]; return true; } prefix = default; return false; } static bool HasNumericSuffix(IParameterSymbol? parameter, out ReadOnlyMemory<char> prefix) { var name = parameter?.Name; // Has to end with 0-9. only handles single-digit numeric suffix for now for simplicity if (name?.Length >= 2 && IsNumeric(name[^1])) { prefix = name.AsMemory()[..^1]; return true; } prefix = default; return false; } static bool IsUpperAlpha(char c) => c is >= 'A' and <= 'Z'; static bool IsNumeric(char c) => c is >= '0' and <= '9'; } private static bool HintMatches(HintKind kind, bool literalParameters, bool objectCreationParameters, bool otherParameters) { return kind switch { HintKind.Literal => literalParameters, HintKind.ObjectCreation => objectCreationParameters, HintKind.Other => otherParameters, _ => throw ExceptionUtilities.UnexpectedValue(kind), }; } protected static bool MatchesMethodIntent(IParameterSymbol? parameter) { // Methods like `SetColor(color: "y")` `FromResult(result: "x")` `Enable/DisablePolling(bool)` don't need // parameter names to improve clarity. The parameter is clear from the context of the method name. // First, this only applies to methods (as we're looking at the method name itself) so filter down to those. if (parameter is not { ContainingSymbol: IMethodSymbol { MethodKind: MethodKind.Ordinary } method }) return false; // We only care when dealing with the first parameter. Note: we don't have to worry parameter reordering // due to named-parameter use. That's because this entire feature only works when we don't use // named-parameters. So, by definition, the parameter/arg must be in the right location. if (method.Parameters[0] != parameter) return false; var methodName = method.Name; // Check for something like `EnableLogging(true)` if (TryGetSuffix("Enable", methodName, out _) || TryGetSuffix("Disable", methodName, out _)) { return parameter.Type.SpecialType == SpecialType.System_Boolean; } // More names can be added here if we find other patterns like this. if (TryGetSuffix("Set", methodName, out var suffix) || TryGetSuffix("From", methodName, out suffix)) { return SuffixMatchesParameterName(suffix, parameter.Name); } return false; static bool TryGetSuffix(string prefix, string nameValue, out ReadOnlyMemory<char> suffix) { if (nameValue.Length > prefix.Length && nameValue.StartsWith(prefix) && char.IsUpper(nameValue[prefix.Length])) { suffix = nameValue.AsMemory()[prefix.Length..]; return true; } suffix = default; return false; } static bool SuffixMatchesParameterName(ReadOnlyMemory<char> suffix, string parameterName) { // Method's name will be something like 'FromResult', so 'suffix' will be 'Result' and parameterName // will be 'result'. So we check if the first letters differ on case and the rest of the method // matches. return char.ToLower(suffix.Span[0]) == parameterName[0] && suffix.Span[1..].Equals(parameterName.AsSpan()[1..], StringComparison.Ordinal); } } private static bool ParameterMatchesArgumentName(string? identifierArgument, IParameterSymbol parameter, ISyntaxFactsService syntaxFacts) => syntaxFacts.StringComparer.Compare(parameter.Name, identifierArgument) == 0; protected static string GetIdentifierNameFromArgument(SyntaxNode argument, ISyntaxFactsService syntaxFacts) { var identifierNameSyntax = syntaxFacts.IsArgument(argument) ? syntaxFacts.GetExpressionOfArgument(argument) : syntaxFacts.IsAttributeArgument(argument) ? syntaxFacts.GetExpressionOfAttributeArgument(argument) : null; if (!syntaxFacts.IsIdentifierName(identifierNameSyntax)) return string.Empty; var identifier = syntaxFacts.GetIdentifierOfIdentifierName(identifierNameSyntax); return identifier.ValueText; } } }
1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/Core/Portable/InlineHints/AbstractInlineTypeHintsService.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.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.InlineHints { internal abstract class AbstractInlineTypeHintsService : IInlineTypeHintsService { private static readonly SymbolDisplayFormat s_minimalTypeStyle = new SymbolDisplayFormat( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private readonly IGlobalOptionService _globalOptions; public AbstractInlineTypeHintsService(IGlobalOptionService globalOptions) { _globalOptions = globalOptions; } protected abstract TypeHint? TryGetTypeHint( SemanticModel semanticModel, SyntaxNode node, bool displayAllOverride, bool forImplicitVariableTypes, bool forLambdaParameterTypes, bool forImplicitObjectCreation, CancellationToken cancellationToken); public async Task<ImmutableArray<InlineHint>> GetInlineHintsAsync( Document document, TextSpan textSpan, InlineTypeHintsOptions options, SymbolDescriptionOptions displayOptions, CancellationToken cancellationToken) { var displayAllOverride = _globalOptions.GetOption(InlineHintsGlobalStateOption.DisplayAllOverride); var enabledForTypes = options.EnabledForTypes; if (!enabledForTypes && !displayAllOverride) return ImmutableArray<InlineHint>.Empty; var forImplicitVariableTypes = enabledForTypes && options.ForImplicitVariableTypes; var forLambdaParameterTypes = enabledForTypes && options.ForLambdaParameterTypes; var forImplicitObjectCreation = enabledForTypes && options.ForImplicitObjectCreation; if (!forImplicitVariableTypes && !forLambdaParameterTypes && !forImplicitObjectCreation && !displayAllOverride) return ImmutableArray<InlineHint>.Empty; var anonymousTypeService = document.GetRequiredLanguageService<IStructuralTypeDisplayService>(); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); using var _1 = ArrayBuilder<InlineHint>.GetInstance(out var result); foreach (var node in root.DescendantNodes(n => n.Span.IntersectsWith(textSpan))) { var hintOpt = TryGetTypeHint( semanticModel, node, displayAllOverride, forImplicitVariableTypes, forLambdaParameterTypes, forImplicitObjectCreation, cancellationToken); if (hintOpt == null) continue; var (type, span, prefix, suffix) = hintOpt.Value; using var _2 = ArrayBuilder<SymbolDisplayPart>.GetInstance(out var finalParts); finalParts.AddRange(prefix); var parts = type.ToDisplayParts(s_minimalTypeStyle); AddParts(anonymousTypeService, finalParts, parts, semanticModel, span.Start); // If we have nothing to show, then don't bother adding this hint. if (finalParts.All(p => string.IsNullOrWhiteSpace(p.ToString()))) continue; finalParts.AddRange(suffix); result.Add(new InlineHint( span, finalParts.ToTaggedText(), InlineHintHelpers.GetDescriptionFunction(span.Start, type.GetSymbolKey(cancellationToken: cancellationToken), displayOptions))); } return result.ToImmutable(); } private void AddParts( IStructuralTypeDisplayService anonymousTypeService, ArrayBuilder<SymbolDisplayPart> finalParts, ImmutableArray<SymbolDisplayPart> parts, SemanticModel semanticModel, int position, HashSet<INamedTypeSymbol>? seenSymbols = null) { seenSymbols ??= new(); foreach (var part in parts) { if (part.Symbol is INamedTypeSymbol { IsAnonymousType: true } anonymousType) { if (seenSymbols.Add(anonymousType)) { var anonymousParts = anonymousTypeService.GetAnonymousTypeParts(anonymousType, semanticModel, position); AddParts(anonymousTypeService, finalParts, anonymousParts, semanticModel, position, seenSymbols); seenSymbols.Remove(anonymousType); } else { finalParts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Text, symbol: null, "...")); } } else { finalParts.Add(part); } } } } }
// Licensed to the .NET Foundation under one or more 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.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.InlineHints { internal abstract class AbstractInlineTypeHintsService : IInlineTypeHintsService { protected static readonly SymbolDisplayFormat s_minimalTypeStyle = new SymbolDisplayFormat( genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.AllowDefaultLiteral | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private readonly IGlobalOptionService _globalOptions; public AbstractInlineTypeHintsService(IGlobalOptionService globalOptions) { _globalOptions = globalOptions; } protected abstract TypeHint? TryGetTypeHint( SemanticModel semanticModel, SyntaxNode node, bool displayAllOverride, bool forImplicitVariableTypes, bool forLambdaParameterTypes, bool forImplicitObjectCreation, CancellationToken cancellationToken); public async Task<ImmutableArray<InlineHint>> GetInlineHintsAsync( Document document, TextSpan textSpan, InlineTypeHintsOptions options, SymbolDescriptionOptions displayOptions, CancellationToken cancellationToken) { var displayAllOverride = _globalOptions.GetOption(InlineHintsGlobalStateOption.DisplayAllOverride); var enabledForTypes = options.EnabledForTypes; if (!enabledForTypes && !displayAllOverride) return ImmutableArray<InlineHint>.Empty; var forImplicitVariableTypes = enabledForTypes && options.ForImplicitVariableTypes; var forLambdaParameterTypes = enabledForTypes && options.ForLambdaParameterTypes; var forImplicitObjectCreation = enabledForTypes && options.ForImplicitObjectCreation; if (!forImplicitVariableTypes && !forLambdaParameterTypes && !forImplicitObjectCreation && !displayAllOverride) return ImmutableArray<InlineHint>.Empty; var anonymousTypeService = document.GetRequiredLanguageService<IStructuralTypeDisplayService>(); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); using var _1 = ArrayBuilder<InlineHint>.GetInstance(out var result); foreach (var node in root.DescendantNodes(n => n.Span.IntersectsWith(textSpan))) { var hintOpt = TryGetTypeHint( semanticModel, node, displayAllOverride, forImplicitVariableTypes, forLambdaParameterTypes, forImplicitObjectCreation, cancellationToken); if (hintOpt == null) continue; var (type, span, textChange, prefix, suffix) = hintOpt.Value; using var _2 = ArrayBuilder<SymbolDisplayPart>.GetInstance(out var finalParts); finalParts.AddRange(prefix); var parts = type.ToDisplayParts(s_minimalTypeStyle); AddParts(anonymousTypeService, finalParts, parts, semanticModel, span.Start); // If we have nothing to show, then don't bother adding this hint. if (finalParts.All(p => string.IsNullOrWhiteSpace(p.ToString()))) continue; finalParts.AddRange(suffix); var taggedText = finalParts.ToTaggedText(); result.Add(new InlineHint( span, taggedText, textChange, InlineHintHelpers.GetDescriptionFunction(span.Start, type.GetSymbolKey(cancellationToken: cancellationToken), displayOptions))); } return result.ToImmutable(); } private void AddParts( IStructuralTypeDisplayService anonymousTypeService, ArrayBuilder<SymbolDisplayPart> finalParts, ImmutableArray<SymbolDisplayPart> parts, SemanticModel semanticModel, int position, HashSet<INamedTypeSymbol>? seenSymbols = null) { seenSymbols ??= new(); foreach (var part in parts) { if (part.Symbol is INamedTypeSymbol { IsAnonymousType: true } anonymousType) { if (seenSymbols.Add(anonymousType)) { var anonymousParts = anonymousTypeService.GetAnonymousTypeParts(anonymousType, semanticModel, position); AddParts(anonymousTypeService, finalParts, anonymousParts, semanticModel, position, seenSymbols); seenSymbols.Remove(anonymousType); } else { finalParts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Text, symbol: null, "...")); } } else { finalParts.Add(part); } } } } }
1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/Core/Portable/InlineHints/InlineHint.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.InlineHints { internal readonly struct InlineHint { public readonly TextSpan Span; public readonly ImmutableArray<TaggedText> DisplayParts; private readonly Func<Document, CancellationToken, Task<ImmutableArray<TaggedText>>>? _getDescriptionAsync; public InlineHint( TextSpan span, ImmutableArray<TaggedText> displayParts, Func<Document, CancellationToken, Task<ImmutableArray<TaggedText>>>? getDescriptionAsync = null) { if (displayParts.Length == 0) throw new ArgumentException($"{nameof(displayParts)} must be non-empty"); Span = span; DisplayParts = displayParts; _getDescriptionAsync = getDescriptionAsync; } /// <summary> /// Gets a description for the inline hint, suitable to show when a user hovers over the editor adornment. The /// <paramref name="document"/> will represent the file at the time this hint was created. /// </summary> public Task<ImmutableArray<TaggedText>> GetDescriptionAsync(Document document, CancellationToken cancellationToken) => _getDescriptionAsync?.Invoke(document, cancellationToken) ?? SpecializedTasks.EmptyImmutableArray<TaggedText>(); } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.InlineHints { internal readonly struct InlineHint { public readonly TextSpan Span; public readonly ImmutableArray<TaggedText> DisplayParts; public readonly TextChange? ReplacementTextChange; private readonly Func<Document, CancellationToken, Task<ImmutableArray<TaggedText>>>? _getDescriptionAsync; public InlineHint( TextSpan span, ImmutableArray<TaggedText> displayParts, Func<Document, CancellationToken, Task<ImmutableArray<TaggedText>>>? getDescriptionAsync = null) : this(span, displayParts, replacementTextChange: null, getDescriptionAsync) { } public InlineHint( TextSpan span, ImmutableArray<TaggedText> displayParts, TextChange? replacementTextChange, Func<Document, CancellationToken, Task<ImmutableArray<TaggedText>>>? getDescriptionAsync = null) { if (displayParts.Length == 0) throw new ArgumentException($"{nameof(displayParts)} must be non-empty"); Span = span; DisplayParts = displayParts; _getDescriptionAsync = getDescriptionAsync; ReplacementTextChange = replacementTextChange; } /// <summary> /// Gets a description for the inline hint, suitable to show when a user hovers over the editor adornment. The /// <paramref name="document"/> will represent the file at the time this hint was created. /// </summary> public Task<ImmutableArray<TaggedText>> GetDescriptionAsync(Document document, CancellationToken cancellationToken) => _getDescriptionAsync?.Invoke(document, cancellationToken) ?? SpecializedTasks.EmptyImmutableArray<TaggedText>(); } }
1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/Core/Portable/InlineHints/TypeHint.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.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.InlineHints { internal readonly struct TypeHint { private static readonly ImmutableArray<SymbolDisplayPart> s_spaceArray = ImmutableArray.Create(new SymbolDisplayPart(SymbolDisplayPartKind.Space, symbol: null, " ")); public ITypeSymbol Type { get; } public TextSpan Span { get; } public ImmutableArray<SymbolDisplayPart> Prefix { get; } public ImmutableArray<SymbolDisplayPart> Suffix { get; } public TypeHint(ITypeSymbol type, TextSpan span, bool leadingSpace = false, bool trailingSpace = false) { Type = type; Span = span; Prefix = CreateSpaceSymbolPartArray(leadingSpace); Suffix = CreateSpaceSymbolPartArray(trailingSpace); } private static ImmutableArray<SymbolDisplayPart> CreateSpaceSymbolPartArray(bool hasSpace) => hasSpace ? s_spaceArray : ImmutableArray<SymbolDisplayPart>.Empty; public void Deconstruct(out ITypeSymbol type, out TextSpan span, out ImmutableArray<SymbolDisplayPart> prefix, out ImmutableArray<SymbolDisplayPart> suffix) { type = Type; span = Span; prefix = Prefix; suffix = Suffix; } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.InlineHints { internal readonly struct TypeHint { private static readonly ImmutableArray<SymbolDisplayPart> s_spaceArray = ImmutableArray.Create(new SymbolDisplayPart(SymbolDisplayPartKind.Space, symbol: null, " ")); public ITypeSymbol Type { get; } public TextSpan Span { get; } public TextChange? TextChange { get; } public ImmutableArray<SymbolDisplayPart> Prefix { get; } public ImmutableArray<SymbolDisplayPart> Suffix { get; } public TypeHint(ITypeSymbol type, TextSpan span, TextChange? textChange, bool leadingSpace = false, bool trailingSpace = false) { Type = type; Span = span; TextChange = textChange; Prefix = CreateSpaceSymbolPartArray(leadingSpace); Suffix = CreateSpaceSymbolPartArray(trailingSpace); } private static ImmutableArray<SymbolDisplayPart> CreateSpaceSymbolPartArray(bool hasSpace) => hasSpace ? s_spaceArray : ImmutableArray<SymbolDisplayPart>.Empty; public void Deconstruct(out ITypeSymbol type, out TextSpan span, out TextChange? textChange, out ImmutableArray<SymbolDisplayPart> prefix, out ImmutableArray<SymbolDisplayPart> suffix) { type = Type; span = Span; textChange = TextChange; prefix = Prefix; suffix = Suffix; } } }
1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/VisualBasic/Portable/InlineHints/VisualBasicInlineParameterNameHintsService.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.Threading Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.InlineHints Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.InlineHints <ExportLanguageService(GetType(IInlineParameterNameHintsService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicInlineParameterNameHintsService Inherits AbstractInlineParameterNameHintsService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(globalOptions As IGlobalOptionService) MyBase.New(globalOptions) End Sub Protected Overrides Sub AddAllParameterNameHintLocations( semanticModel As SemanticModel, syntaxFacts As ISyntaxFactsService, node As SyntaxNode, buffer As ArrayBuilder(Of (position As Integer, identifierArgument As String, parameter As IParameterSymbol, kind As HintKind)), cancellationToken As CancellationToken) Dim argumentList = TryCast(node, ArgumentListSyntax) If argumentList Is Nothing Then Return End If For Each arg In argumentList.Arguments Dim argument = TryCast(arg, SimpleArgumentSyntax) If argument Is Nothing Then Continue For End If If argument?.Expression Is Nothing Then Continue For End If If argument.IsNamed OrElse argument.NameColonEquals IsNot Nothing Then Continue For End If Dim parameter = argument.DetermineParameter(semanticModel, allowParamArray:=False, cancellationToken) If String.IsNullOrEmpty(parameter?.Name) Then Continue For End If Dim argumentIdentifier = GetIdentifierNameFromArgument(argument, syntaxFacts) buffer.Add((argument.Span.Start, argumentIdentifier, parameter, GetKind(argument.Expression))) Next End Sub Private Function GetKind(arg As ExpressionSyntax) As HintKind If TypeOf arg Is LiteralExpressionSyntax OrElse TypeOf arg Is InterpolatedStringExpressionSyntax Then Return HintKind.Literal End If If TypeOf arg Is ObjectCreationExpressionSyntax Then Return HintKind.ObjectCreation End If Dim predefinedCast = TryCast(arg, PredefinedCastExpressionSyntax) If predefinedCast IsNot Nothing Then ' Recurse until we find a literal ' If so, then we should add the adornment Return GetKind(predefinedCast.Expression) End If Dim cast = TryCast(arg, CastExpressionSyntax) If cast IsNot Nothing Then ' Recurse until we find a literal ' If so, then we should add the adornment Return GetKind(cast.Expression) End If Dim unary = TryCast(arg, UnaryExpressionSyntax) If unary IsNot Nothing Then ' Recurse until we find a literal ' If so, then we should add the adornment Return GetKind(unary.Operand) End If Return HintKind.Other End Function Protected Overrides Function IsIndexer(node As SyntaxNode, parameter As IParameterSymbol) As Boolean Dim propertySymbol = TryCast(parameter.ContainingSymbol, IPropertySymbol) Return propertySymbol IsNot Nothing AndAlso propertySymbol.IsDefault 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.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.InlineHints Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.InlineHints <ExportLanguageService(GetType(IInlineParameterNameHintsService), LanguageNames.VisualBasic), [Shared]> Friend Class VisualBasicInlineParameterNameHintsService Inherits AbstractInlineParameterNameHintsService <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New(globalOptions As IGlobalOptionService) MyBase.New(globalOptions) End Sub Protected Overrides Sub AddAllParameterNameHintLocations( semanticModel As SemanticModel, syntaxFacts As ISyntaxFactsService, node As SyntaxNode, buffer As ArrayBuilder(Of (position As Integer, identifierArgument As String, parameter As IParameterSymbol, kind As HintKind)), cancellationToken As CancellationToken) Dim argumentList = TryCast(node, ArgumentListSyntax) If argumentList Is Nothing Then Return End If For Each arg In argumentList.Arguments Dim argument = TryCast(arg, SimpleArgumentSyntax) If argument Is Nothing Then Continue For End If If argument?.Expression Is Nothing Then Continue For End If If argument.IsNamed OrElse argument.NameColonEquals IsNot Nothing Then Continue For End If Dim parameter = argument.DetermineParameter(semanticModel, allowParamArray:=False, cancellationToken) If String.IsNullOrEmpty(parameter?.Name) Then Continue For End If Dim argumentIdentifier = GetIdentifierNameFromArgument(argument, syntaxFacts) buffer.Add((argument.Span.Start, argumentIdentifier, parameter, GetKind(argument.Expression))) Next End Sub Private Function GetKind(arg As ExpressionSyntax) As HintKind If TypeOf arg Is LiteralExpressionSyntax OrElse TypeOf arg Is InterpolatedStringExpressionSyntax Then Return HintKind.Literal End If If TypeOf arg Is ObjectCreationExpressionSyntax Then Return HintKind.ObjectCreation End If Dim predefinedCast = TryCast(arg, PredefinedCastExpressionSyntax) If predefinedCast IsNot Nothing Then ' Recurse until we find a literal ' If so, then we should add the adornment Return GetKind(predefinedCast.Expression) End If Dim cast = TryCast(arg, CastExpressionSyntax) If cast IsNot Nothing Then ' Recurse until we find a literal ' If so, then we should add the adornment Return GetKind(cast.Expression) End If Dim unary = TryCast(arg, UnaryExpressionSyntax) If unary IsNot Nothing Then ' Recurse until we find a literal ' If so, then we should add the adornment Return GetKind(unary.Operand) End If Return HintKind.Other End Function Protected Overrides Function IsIndexer(node As SyntaxNode, parameter As IParameterSymbol) As Boolean Dim propertySymbol = TryCast(parameter.ContainingSymbol, IPropertySymbol) Return propertySymbol IsNot Nothing AndAlso propertySymbol.IsDefault End Function Protected Overrides Function GetReplacementText(parameterName As String) As String Return parameterName & ":=" End Function End Class End Namespace
1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Log/FunctionId.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.Internal.Log { /// <summary> /// Enum to uniquely identify each function location. /// </summary> internal enum FunctionId { // a value to use in unit tests that won't interfere with reporting // for our other scenarios. TestEvent_NotUsed = 1, WorkCoordinator_DocumentWorker_Enqueue = 2, WorkCoordinator_ProcessProjectAsync = 3, WorkCoordinator_ProcessDocumentAsync = 4, WorkCoordinator_SemanticChange_Enqueue = 5, WorkCoordinator_SemanticChange_EnqueueFromMember = 6, WorkCoordinator_SemanticChange_EnqueueFromType = 7, WorkCoordinator_SemanticChange_FullProjects = 8, WorkCoordinator_Project_Enqueue = 9, WorkCoordinator_AsyncWorkItemQueue_LastItem = 10, WorkCoordinator_AsyncWorkItemQueue_FirstItem = 11, Diagnostics_SyntaxDiagnostic = 12, Diagnostics_SemanticDiagnostic = 13, Diagnostics_ProjectDiagnostic = 14, Diagnostics_DocumentReset = 15, Diagnostics_DocumentOpen = 16, Diagnostics_RemoveDocument = 17, Diagnostics_RemoveProject = 18, Diagnostics_DocumentClose = 19, // add new values after this Run_Environment = 20, Run_Environment_Options = 21, Tagger_AdornmentManager_OnLayoutChanged = 22, Tagger_AdornmentManager_UpdateInvalidSpans = 23, Tagger_BatchChangeNotifier_NotifyEditorNow = 24, Tagger_BatchChangeNotifier_NotifyEditor = 25, Tagger_TagSource_RecomputeTags = 26, Tagger_TagSource_ProcessNewTags = 27, Tagger_SyntacticClassification_TagComputer_GetTags = 28, Tagger_SemanticClassification_TagProducer_ProduceTags = 29, Tagger_BraceHighlighting_TagProducer_ProduceTags = 30, Tagger_LineSeparator_TagProducer_ProduceTags = 31, Tagger_Outlining_TagProducer_ProduceTags = 32, Tagger_Highlighter_TagProducer_ProduceTags = 33, Tagger_ReferenceHighlighting_TagProducer_ProduceTags = 34, CaseCorrection_CaseCorrect = 35, CaseCorrection_ReplaceTokens = 36, CaseCorrection_AddReplacements = 37, CodeCleanup_CleanupAsync = 38, CodeCleanup_Cleanup = 39, CodeCleanup_IterateAllCodeCleanupProviders = 40, CodeCleanup_IterateOneCodeCleanup = 41, CommandHandler_GetCommandState = 42, CommandHandler_ExecuteHandlers = 43, CommandHandler_FormatCommand = 44, CommandHandler_CompleteStatement = 45, CommandHandler_ToggleBlockComment = 46, CommandHandler_ToggleLineComment = 47, Workspace_SourceText_GetChangeRanges = 48, Workspace_Recoverable_RecoverRootAsync = 49, Workspace_Recoverable_RecoverRoot = 50, Workspace_Recoverable_RecoverTextAsync = 51, Workspace_Recoverable_RecoverText = 52, Workspace_SkeletonAssembly_GetMetadataOnlyImage = 53, Workspace_SkeletonAssembly_EmitMetadataOnlyImage = 54, Workspace_Document_State_FullyParseSyntaxTree = 55, Workspace_Document_State_IncrementallyParseSyntaxTree = 56, Workspace_Document_GetSemanticModel = 57, Workspace_Document_GetSyntaxTree = 58, Workspace_Document_GetTextChanges = 59, Workspace_Project_GetCompilation = 60, Workspace_Project_CompilationTracker_BuildCompilationAsync = 61, Workspace_ApplyChanges = 62, Workspace_TryGetDocument = 63, Workspace_TryGetDocumentFromInProgressSolution = 64, // obsolete: Workspace_Solution_LinkedFileDiffMergingSession = 65, // obsolete: Workspace_Solution_LinkedFileDiffMergingSession_LinkedFileGroup = 66, Workspace_Solution_Info = 67, EndConstruct_DoStatement = 68, EndConstruct_XmlCData = 69, EndConstruct_XmlComment = 70, EndConstruct_XmlElement = 71, EndConstruct_XmlEmbeddedExpression = 72, EndConstruct_XmlProcessingInstruction = 73, FindReference_Rename = 74, FindReference_ChangeSignature = 75, FindReference = 76, FindReference_DetermineAllSymbolsAsync = 77, FindReference_CreateProjectMapAsync = 78, FindReference_CreateDocumentMapAsync = 79, FindReference_ProcessAsync = 80, FindReference_ProcessProjectAsync = 81, FindReference_ProcessDocumentAsync = 82, LineCommit_CommitRegion = 83, Formatting_TokenStreamConstruction = 84, Formatting_ContextInitialization = 85, Formatting_Format = 86, Formatting_ApplyResultToBuffer = 87, Formatting_IterateNodes = 88, Formatting_CollectIndentBlock = 89, Formatting_CollectSuppressOperation = 90, Formatting_CollectAlignOperation = 91, Formatting_CollectAnchorOperation = 92, Formatting_CollectTokenOperation = 93, Formatting_BuildContext = 94, Formatting_ApplySpaceAndLine = 95, Formatting_ApplyAnchorOperation = 96, Formatting_ApplyAlignOperation = 97, Formatting_AggregateCreateTextChanges = 98, Formatting_AggregateCreateFormattedRoot = 99, Formatting_CreateTextChanges = 100, Formatting_CreateFormattedRoot = 101, Formatting_Partitions = 102, SmartIndentation_Start = 103, SmartIndentation_OpenCurly = 104, SmartIndentation_CloseCurly = 105, Rename_InlineSession = 106, Rename_InlineSession_Session = 107, Rename_FindLinkedSpans = 108, Rename_GetSymbolRenameInfo = 109, Rename_OnTextBufferChanged = 110, Rename_ApplyReplacementText = 111, Rename_CommitCore = 112, Rename_CommitCoreWithPreview = 113, Rename_GetAsynchronousLocationsSource = 114, Rename_AllRenameLocations = 115, Rename_StartSearchingForSpansInAllOpenDocuments = 116, Rename_StartSearchingForSpansInOpenDocument = 117, Rename_CreateOpenTextBufferManagerForAllOpenDocs = 118, Rename_CreateOpenTextBufferManagerForAllOpenDocument = 119, Rename_ReportSpan = 120, Rename_GetNoChangeConflictResolution = 121, Rename_Tracking_BufferChanged = 122, TPLTask_TaskScheduled = 123, TPLTask_TaskStarted = 124, TPLTask_TaskCompleted = 125, Get_QuickInfo_Async = 126, Completion_ModelComputer_DoInBackground = 127, Completion_ModelComputation_FilterModelInBackground = 128, Completion_ModelComputation_WaitForModel = 129, Completion_SymbolCompletionProvider_GetItemsWorker = 130, Completion_KeywordCompletionProvider_GetItemsWorker = 131, Completion_SnippetCompletionProvider_GetItemsWorker_CSharp = 132, Completion_TypeImportCompletionProvider_GetCompletionItemsAsync = 133, Completion_ExtensionMethodImportCompletionProvider_GetCompletionItemsAsync = 134, SignatureHelp_ModelComputation_ComputeModelInBackground = 135, SignatureHelp_ModelComputation_UpdateModelInBackground = 136, Refactoring_CodeRefactoringService_GetRefactoringsAsync = 137, Refactoring_AddImport = 138, Refactoring_FullyQualify = 139, Refactoring_GenerateFromMembers_AddConstructorParametersFromMembers = 140, Refactoring_GenerateFromMembers_GenerateConstructorFromMembers = 141, Refactoring_GenerateFromMembers_GenerateEqualsAndGetHashCode = 142, Refactoring_GenerateMember_GenerateConstructor = 143, Refactoring_GenerateMember_GenerateDefaultConstructors = 144, Refactoring_GenerateMember_GenerateEnumMember = 145, Refactoring_GenerateMember_GenerateMethod = 146, Refactoring_GenerateMember_GenerateVariable = 147, Refactoring_ImplementAbstractClass = 148, Refactoring_ImplementInterface = 149, Refactoring_IntroduceVariable = 150, Refactoring_GenerateType = 151, Refactoring_RemoveUnnecessaryImports_CSharp = 152, Refactoring_RemoveUnnecessaryImports_VisualBasic = 153, Snippet_OnBeforeInsertion = 154, Snippet_OnAfterInsertion = 155, Misc_NonReentrantLock_BlockingWait = 156, Misc_SaveEventsSink_OnBeforeSave = 158, TaskList_Refresh = 159, TaskList_NavigateTo = 160, WinformDesigner_GenerateXML = 161, NavigateTo_Search = 162, NavigationService_VSDocumentNavigationService_NavigateTo = 163, NavigationBar_ComputeModelAsync = 164, NavigationBar_ItemService_GetMembersInTypes_CSharp = 165, NavigationBar_ItemService_GetTypesInFile_CSharp = 166, NavigationBar_UpdateDropDownsSynchronously_WaitForModel = 167, NavigationBar_UpdateDropDownsSynchronously_WaitForSelectedItemInfo = 168, EventHookup_Determine_If_Event_Hookup = 169, EventHookup_Generate_Handler = 170, EventHookup_Type_Char = 171, Cache_Created = 172, Cache_AddOrAccess = 173, Cache_Remove = 174, Cache_Evict = 175, Cache_EvictAll = 176, Cache_ItemRank = 177, TextStructureNavigator_GetExtentOfWord = 178, TextStructureNavigator_GetSpanOfEnclosing = 179, TextStructureNavigator_GetSpanOfFirstChild = 180, TextStructureNavigator_GetSpanOfNextSibling = 181, TextStructureNavigator_GetSpanOfPreviousSibling = 182, Debugging_LanguageDebugInfoService_GetDataTipSpanAndText = 183, Debugging_VsLanguageDebugInfo_ValidateBreakpointLocation = 184, Debugging_VsLanguageDebugInfo_GetProximityExpressions = 185, Debugging_VsLanguageDebugInfo_ResolveName = 186, Debugging_VsLanguageDebugInfo_GetNameOfLocation = 187, Debugging_VsLanguageDebugInfo_GetDataTipText = 188, Debugging_EncSession = 189, Debugging_EncSession_EditSession = 190, Debugging_EncSession_EditSession_EmitDeltaErrorId = 191, Debugging_EncSession_EditSession_RudeEdit = 192, Simplifier_ReduceAsync = 193, Simplifier_ExpandNode = 194, Simplifier_ExpandToken = 195, ForegroundNotificationService_Processed = 196, ForegroundNotificationService_NotifyOnForeground = 197, BackgroundCompiler_BuildCompilationsAsync = 198, PersistenceService_ReadAsync = 199, PersistenceService_WriteAsync = 200, PersistenceService_ReadAsyncFailed = 201, PersistenceService_WriteAsyncFailed = 202, PersistenceService_Initialization = 203, TemporaryStorageServiceFactory_ReadText = 204, TemporaryStorageServiceFactory_WriteText = 205, TemporaryStorageServiceFactory_ReadStream = 206, TemporaryStorageServiceFactory_WriteStream = 207, PullMembersUpWarning_ChangeTargetToAbstract = 208, PullMembersUpWarning_ChangeOriginToPublic = 209, PullMembersUpWarning_ChangeOriginToNonStatic = 210, PullMembersUpWarning_UserProceedToFinish = 211, PullMembersUpWarning_UserGoBack = 212, // currently no-one uses these SmartTags_RefreshSession = 213, SmartTags_SmartTagInitializeFixes = 214, SmartTags_ApplyQuickFix = 215, EditorTestApp_RefreshTask = 216, EditorTestApp_UpdateDiagnostics = 217, IncrementalAnalyzerProcessor_Analyzers = 218, IncrementalAnalyzerProcessor_Analyzer = 219, IncrementalAnalyzerProcessor_ActiveFileAnalyzers = 220, IncrementalAnalyzerProcessor_ActiveFileAnalyzer = 221, IncrementalAnalyzerProcessor_Shutdown = 222, WorkCoordinatorRegistrationService_Register = 223, WorkCoordinatorRegistrationService_Unregister = 224, WorkCoordinatorRegistrationService_Reanalyze = 225, WorkCoordinator_SolutionCrawlerOption = 226, WorkCoordinator_PersistentStorageAdded = 227, WorkCoordinator_PersistentStorageRemoved = 228, WorkCoordinator_Shutdown = 229, DiagnosticAnalyzerService_Analyzers = 230, DiagnosticAnalyzerDriver_AnalyzerCrash = 231, DiagnosticAnalyzerDriver_AnalyzerTypeCount = 232, // obsolete: PersistedSemanticVersion_Info = 233, StorageDatabase_Exceptions = 234, WorkCoordinator_ShutdownTimeout = 235, Diagnostics_HyperLink = 236, CodeFixes_FixAllOccurrencesSession = 237, CodeFixes_FixAllOccurrencesContext = 238, CodeFixes_FixAllOccurrencesComputation = 239, CodeFixes_FixAllOccurrencesComputation_Document_Diagnostics = 240, CodeFixes_FixAllOccurrencesComputation_Project_Diagnostics = 241, CodeFixes_FixAllOccurrencesComputation_Document_Fixes = 242, CodeFixes_FixAllOccurrencesComputation_Project_Fixes = 243, CodeFixes_FixAllOccurrencesComputation_Document_Merge = 244, CodeFixes_FixAllOccurrencesComputation_Project_Merge = 245, CodeFixes_FixAllOccurrencesPreviewChanges = 246, CodeFixes_ApplyChanges = 247, SolutionExplorer_AnalyzerItemSource_GetItems = 248, SolutionExplorer_DiagnosticItemSource_GetItems = 249, WorkCoordinator_ActiveFileEnqueue = 250, SymbolFinder_FindDeclarationsAsync = 251, SymbolFinder_Project_AddDeclarationsAsync = 252, SymbolFinder_Assembly_AddDeclarationsAsync = 253, SymbolFinder_Solution_Name_FindSourceDeclarationsAsync = 254, SymbolFinder_Project_Name_FindSourceDeclarationsAsync = 255, SymbolFinder_Solution_Predicate_FindSourceDeclarationsAsync = 256, SymbolFinder_Project_Predicate_FindSourceDeclarationsAsync = 257, Tagger_Diagnostics_RecomputeTags = 258, Tagger_Diagnostics_Updated = 259, SuggestedActions_HasSuggestedActionsAsync = 260, SuggestedActions_GetSuggestedActions = 261, AnalyzerDependencyCheckingService_LogConflict = 262, AnalyzerDependencyCheckingService_LogMissingDependency = 263, VirtualMemory_MemoryLow = 264, Extension_Exception = 265, WorkCoordinator_WaitForHigherPriorityOperationsAsync = 266, CSharp_Interactive_Window = 267, VisualBasic_Interactive_Window = 268, NonFatalWatson = 269, GlobalOperationRegistration = 270, CommandHandler_FindAllReference = 271, CodefixInfobar_Enable = 272, CodefixInfobar_EnableAndIgnoreFutureErrors = 273, CodefixInfobar_LeaveDisabled = 274, CodefixInfobar_ErrorIgnored = 275, Refactoring_NamingStyle = 276, // Caches SymbolTreeInfo_ExceptionInCacheRead = 277, SpellChecker_ExceptionInCacheRead = 278, BKTree_ExceptionInCacheRead = 279, IntellisenseBuild_Failed = 280, FileTextLoader_FileLengthThresholdExceeded = 281, // Generic performance measurement action IDs MeasurePerformance_StartAction = 282, MeasurePerformance_StopAction = 283, Serializer_CreateChecksum = 284, Serializer_Serialize = 285, Serializer_Deserialize = 286, CodeAnalysisService_CalculateDiagnosticsAsync = 287, CodeAnalysisService_SerializeDiagnosticResultAsync = 288, CodeAnalysisService_GetReferenceCountAsync = 289, CodeAnalysisService_FindReferenceLocationsAsync = 290, CodeAnalysisService_FindReferenceMethodsAsync = 291, CodeAnalysisService_GetFullyQualifiedName = 292, CodeAnalysisService_GetTodoCommentsAsync = 293, CodeAnalysisService_GetDesignerAttributesAsync = 294, ServiceHubRemoteHostClient_CreateAsync = 295, // obsolete: PinnedRemotableDataScope_GetRemotableData = 296, RemoteHost_Connect = 297, RemoteHost_Disconnect = 298, // obsolete: RemoteHostClientService_AddGlobalAssetsAsync = 299, // obsolete: RemoteHostClientService_RemoveGlobalAssets = 300, // obsolete: RemoteHostClientService_Enabled = 301, // obsolete: RemoteHostClientService_Restarted = 302, RemoteHostService_SynchronizePrimaryWorkspaceAsync = 303, // obsolete: RemoteHostService_SynchronizeGlobalAssetsAsync = 304, AssetStorage_CleanAssets = 305, AssetStorage_TryGetAsset = 306, AssetService_GetAssetAsync = 307, AssetService_SynchronizeAssetsAsync = 308, AssetService_SynchronizeSolutionAssetsAsync = 309, AssetService_SynchronizeProjectAssetsAsync = 310, CodeLens_GetReferenceCountAsync = 311, CodeLens_FindReferenceLocationsAsync = 312, CodeLens_FindReferenceMethodsAsync = 313, CodeLens_GetFullyQualifiedName = 314, SolutionState_ComputeChecksumsAsync = 315, ProjectState_ComputeChecksumsAsync = 316, DocumentState_ComputeChecksumsAsync = 317, // obsolete: SolutionSynchronizationService_GetRemotableData = 318, // obsolete: SolutionSynchronizationServiceFactory_CreatePinnedRemotableDataScopeAsync = 319, SolutionChecksumUpdater_SynchronizePrimaryWorkspace = 320, JsonRpcSession_RequestAssetAsync = 321, SolutionService_GetSolutionAsync = 322, SolutionService_UpdatePrimaryWorkspaceAsync = 323, RemoteHostService_GetAssetsAsync = 324, // obsolete: CompilationService_GetCompilationAsync = 325, SolutionCreator_AssetDifferences = 326, Extension_InfoBar = 327, FxCopAnalyzersInstall = 328, AssetStorage_ForceGC = 329, // obsolete: RemoteHost_Bitness = 330, Intellisense_Completion = 331, MetadataOnlyImage_EmitFailure = 332, LiveTableDataSource_OnDiagnosticsUpdated = 333, Experiment_KeybindingsReset = 334, Diagnostics_GeneratePerformaceReport = 335, Diagnostics_BadAnalyzer = 336, CodeAnalysisService_ReportAnalyzerPerformance = 337, PerformanceTrackerService_AddSnapshot = 338, // obsolete: AbstractProject_SetIntelliSenseBuild = 339, // obsolete: AbstractProject_Created = 340, // obsolete: AbstractProject_PushedToWorkspace = 341, ExternalErrorDiagnosticUpdateSource_AddError = 342, DiagnosticIncrementalAnalyzer_SynchronizeWithBuildAsync = 343, Completion_ExecuteCommand_TypeChar = 344, RemoteHostService_SynchronizeTextAsync = 345, SymbolFinder_Solution_Pattern_FindSourceDeclarationsAsync = 346, SymbolFinder_Project_Pattern_FindSourceDeclarationsAsync = 347, // obsolete: Intellisense_Completion_Commit = 348, CodeCleanupInfobar_BarDisplayed = 349, CodeCleanupInfobar_ConfigureNow = 350, CodeCleanupInfobar_NeverShowCodeCleanupInfoBarAgain = 351, FormatDocument = 352, CodeCleanup_ApplyCodeFixesAsync = 353, CodeCleanup_RemoveUnusedImports = 354, CodeCleanup_SortImports = 355, CodeCleanup_Format = 356, CodeCleanupABTest_AssignedToOnByDefault = 357, CodeCleanupABTest_AssignedToOffByDefault = 358, Workspace_Events = 359, Refactoring_ExtractMethod_UnknownMatrixItem = 360, SyntaxTreeIndex_Precalculate = 361, SyntaxTreeIndex_Precalculate_Create = 362, SymbolTreeInfo_Create = 363, SymbolTreeInfo_TryLoadOrCreate = 364, CommandHandler_GoToImplementation = 365, GraphQuery_ImplementedBy = 366, GraphQuery_Implements = 367, GraphQuery_IsCalledBy = 368, GraphQuery_IsUsedBy = 369, GraphQuery_Overrides = 370, Intellisense_AsyncCompletion_Data = 371, Intellisense_CompletionProviders_Data = 372, RemoteHostService_IsExperimentEnabledAsync = 373, PartialLoad_FullyLoaded = 374, Liveshare_UnknownCodeAction = 375, // obsolete: Liveshare_LexicalClassifications = 376, // obsolete: Liveshare_SyntacticClassifications = 377, // obsolete: Liveshare_SyntacticTagger = 378, CommandHandler_GoToBase = 379, DiagnosticAnalyzerService_GetDiagnosticsForSpanAsync = 380, CodeFixes_GetCodeFixesAsync = 381, LanguageServer_ActivateFailed = 382, LanguageServer_OnLoadedFailed = 383, CodeFixes_AddExplicitCast = 384, ToolsOptions_GenerateEditorconfig = 385, Renamer_RenameSymbolAsync = 386, Renamer_FindRenameLocationsAsync = 387, Renamer_ResolveConflictsAsync = 388, ChangeSignature_Data = 400, AbstractEncapsulateFieldService_EncapsulateFieldsAsync = 410, AbstractConvertTupleToStructCodeRefactoringProvider_ConvertToStructAsync = 420, DependentTypeFinder_FindAndCacheDerivedClassesAsync = 430, DependentTypeFinder_FindAndCacheDerivedInterfacesAsync = 431, DependentTypeFinder_FindAndCacheImplementingTypesAsync = 432, RemoteSemanticClassificationCacheService_ExceptionInCacheRead = 440, // obsolete: FeatureNotAvailable = 441, LSPCompletion_MissingLSPCompletionTriggerKind = 450, LSPCompletion_MissingLSPCompletionInvokeKind = 451, Workspace_Project_CompilationThrownAway = 460, CommandHandler_Paste_ImportsOnPaste = 470, // Superseded by LSP_FindDocumentInWorkspace // obsolete: FindDocumentInWorkspace = 480, RegisterWorkspace = 481, LSP_RequestCounter = 482, LSP_RequestDuration = 483, LSP_TimeInQueue = 484, Intellicode_UnknownIntent = 485, LSP_CompletionListCacheMiss = 486, InheritanceMargin_TargetsMenuOpen = 487, InheritanceMargin_NavigateToTarget = 488, VS_ErrorReportingService_ShowGlobalErrorInfo = 489, UnusedReferences_GetUnusedReferences = 490, ValueTracking_Command = 491, ValueTracking_TrackValueSource = 492, InheritanceMargin_GetInheritanceMemberItems = 493, LSP_FindDocumentInWorkspace = 494, SuggestedActions_GetSuggestedActionsAsync = 500, NavigateTo_CacheItemsMiss = 510, AssetService_Perf = 520, } }
// Licensed to the .NET Foundation under one or more 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.Internal.Log { /// <summary> /// Enum to uniquely identify each function location. /// </summary> internal enum FunctionId { // a value to use in unit tests that won't interfere with reporting // for our other scenarios. TestEvent_NotUsed = 1, WorkCoordinator_DocumentWorker_Enqueue = 2, WorkCoordinator_ProcessProjectAsync = 3, WorkCoordinator_ProcessDocumentAsync = 4, WorkCoordinator_SemanticChange_Enqueue = 5, WorkCoordinator_SemanticChange_EnqueueFromMember = 6, WorkCoordinator_SemanticChange_EnqueueFromType = 7, WorkCoordinator_SemanticChange_FullProjects = 8, WorkCoordinator_Project_Enqueue = 9, WorkCoordinator_AsyncWorkItemQueue_LastItem = 10, WorkCoordinator_AsyncWorkItemQueue_FirstItem = 11, Diagnostics_SyntaxDiagnostic = 12, Diagnostics_SemanticDiagnostic = 13, Diagnostics_ProjectDiagnostic = 14, Diagnostics_DocumentReset = 15, Diagnostics_DocumentOpen = 16, Diagnostics_RemoveDocument = 17, Diagnostics_RemoveProject = 18, Diagnostics_DocumentClose = 19, // add new values after this Run_Environment = 20, Run_Environment_Options = 21, Tagger_AdornmentManager_OnLayoutChanged = 22, Tagger_AdornmentManager_UpdateInvalidSpans = 23, Tagger_BatchChangeNotifier_NotifyEditorNow = 24, Tagger_BatchChangeNotifier_NotifyEditor = 25, Tagger_TagSource_RecomputeTags = 26, Tagger_TagSource_ProcessNewTags = 27, Tagger_SyntacticClassification_TagComputer_GetTags = 28, Tagger_SemanticClassification_TagProducer_ProduceTags = 29, Tagger_BraceHighlighting_TagProducer_ProduceTags = 30, Tagger_LineSeparator_TagProducer_ProduceTags = 31, Tagger_Outlining_TagProducer_ProduceTags = 32, Tagger_Highlighter_TagProducer_ProduceTags = 33, Tagger_ReferenceHighlighting_TagProducer_ProduceTags = 34, CaseCorrection_CaseCorrect = 35, CaseCorrection_ReplaceTokens = 36, CaseCorrection_AddReplacements = 37, CodeCleanup_CleanupAsync = 38, CodeCleanup_Cleanup = 39, CodeCleanup_IterateAllCodeCleanupProviders = 40, CodeCleanup_IterateOneCodeCleanup = 41, CommandHandler_GetCommandState = 42, CommandHandler_ExecuteHandlers = 43, CommandHandler_FormatCommand = 44, CommandHandler_CompleteStatement = 45, CommandHandler_ToggleBlockComment = 46, CommandHandler_ToggleLineComment = 47, Workspace_SourceText_GetChangeRanges = 48, Workspace_Recoverable_RecoverRootAsync = 49, Workspace_Recoverable_RecoverRoot = 50, Workspace_Recoverable_RecoverTextAsync = 51, Workspace_Recoverable_RecoverText = 52, Workspace_SkeletonAssembly_GetMetadataOnlyImage = 53, Workspace_SkeletonAssembly_EmitMetadataOnlyImage = 54, Workspace_Document_State_FullyParseSyntaxTree = 55, Workspace_Document_State_IncrementallyParseSyntaxTree = 56, Workspace_Document_GetSemanticModel = 57, Workspace_Document_GetSyntaxTree = 58, Workspace_Document_GetTextChanges = 59, Workspace_Project_GetCompilation = 60, Workspace_Project_CompilationTracker_BuildCompilationAsync = 61, Workspace_ApplyChanges = 62, Workspace_TryGetDocument = 63, Workspace_TryGetDocumentFromInProgressSolution = 64, // obsolete: Workspace_Solution_LinkedFileDiffMergingSession = 65, // obsolete: Workspace_Solution_LinkedFileDiffMergingSession_LinkedFileGroup = 66, Workspace_Solution_Info = 67, EndConstruct_DoStatement = 68, EndConstruct_XmlCData = 69, EndConstruct_XmlComment = 70, EndConstruct_XmlElement = 71, EndConstruct_XmlEmbeddedExpression = 72, EndConstruct_XmlProcessingInstruction = 73, FindReference_Rename = 74, FindReference_ChangeSignature = 75, FindReference = 76, FindReference_DetermineAllSymbolsAsync = 77, FindReference_CreateProjectMapAsync = 78, FindReference_CreateDocumentMapAsync = 79, FindReference_ProcessAsync = 80, FindReference_ProcessProjectAsync = 81, FindReference_ProcessDocumentAsync = 82, LineCommit_CommitRegion = 83, Formatting_TokenStreamConstruction = 84, Formatting_ContextInitialization = 85, Formatting_Format = 86, Formatting_ApplyResultToBuffer = 87, Formatting_IterateNodes = 88, Formatting_CollectIndentBlock = 89, Formatting_CollectSuppressOperation = 90, Formatting_CollectAlignOperation = 91, Formatting_CollectAnchorOperation = 92, Formatting_CollectTokenOperation = 93, Formatting_BuildContext = 94, Formatting_ApplySpaceAndLine = 95, Formatting_ApplyAnchorOperation = 96, Formatting_ApplyAlignOperation = 97, Formatting_AggregateCreateTextChanges = 98, Formatting_AggregateCreateFormattedRoot = 99, Formatting_CreateTextChanges = 100, Formatting_CreateFormattedRoot = 101, Formatting_Partitions = 102, SmartIndentation_Start = 103, SmartIndentation_OpenCurly = 104, SmartIndentation_CloseCurly = 105, Rename_InlineSession = 106, Rename_InlineSession_Session = 107, Rename_FindLinkedSpans = 108, Rename_GetSymbolRenameInfo = 109, Rename_OnTextBufferChanged = 110, Rename_ApplyReplacementText = 111, Rename_CommitCore = 112, Rename_CommitCoreWithPreview = 113, Rename_GetAsynchronousLocationsSource = 114, Rename_AllRenameLocations = 115, Rename_StartSearchingForSpansInAllOpenDocuments = 116, Rename_StartSearchingForSpansInOpenDocument = 117, Rename_CreateOpenTextBufferManagerForAllOpenDocs = 118, Rename_CreateOpenTextBufferManagerForAllOpenDocument = 119, Rename_ReportSpan = 120, Rename_GetNoChangeConflictResolution = 121, Rename_Tracking_BufferChanged = 122, TPLTask_TaskScheduled = 123, TPLTask_TaskStarted = 124, TPLTask_TaskCompleted = 125, Get_QuickInfo_Async = 126, Completion_ModelComputer_DoInBackground = 127, Completion_ModelComputation_FilterModelInBackground = 128, Completion_ModelComputation_WaitForModel = 129, Completion_SymbolCompletionProvider_GetItemsWorker = 130, Completion_KeywordCompletionProvider_GetItemsWorker = 131, Completion_SnippetCompletionProvider_GetItemsWorker_CSharp = 132, Completion_TypeImportCompletionProvider_GetCompletionItemsAsync = 133, Completion_ExtensionMethodImportCompletionProvider_GetCompletionItemsAsync = 134, SignatureHelp_ModelComputation_ComputeModelInBackground = 135, SignatureHelp_ModelComputation_UpdateModelInBackground = 136, Refactoring_CodeRefactoringService_GetRefactoringsAsync = 137, Refactoring_AddImport = 138, Refactoring_FullyQualify = 139, Refactoring_GenerateFromMembers_AddConstructorParametersFromMembers = 140, Refactoring_GenerateFromMembers_GenerateConstructorFromMembers = 141, Refactoring_GenerateFromMembers_GenerateEqualsAndGetHashCode = 142, Refactoring_GenerateMember_GenerateConstructor = 143, Refactoring_GenerateMember_GenerateDefaultConstructors = 144, Refactoring_GenerateMember_GenerateEnumMember = 145, Refactoring_GenerateMember_GenerateMethod = 146, Refactoring_GenerateMember_GenerateVariable = 147, Refactoring_ImplementAbstractClass = 148, Refactoring_ImplementInterface = 149, Refactoring_IntroduceVariable = 150, Refactoring_GenerateType = 151, Refactoring_RemoveUnnecessaryImports_CSharp = 152, Refactoring_RemoveUnnecessaryImports_VisualBasic = 153, Snippet_OnBeforeInsertion = 154, Snippet_OnAfterInsertion = 155, Misc_NonReentrantLock_BlockingWait = 156, Misc_SaveEventsSink_OnBeforeSave = 158, TaskList_Refresh = 159, TaskList_NavigateTo = 160, WinformDesigner_GenerateXML = 161, NavigateTo_Search = 162, NavigationService_VSDocumentNavigationService_NavigateTo = 163, NavigationBar_ComputeModelAsync = 164, NavigationBar_ItemService_GetMembersInTypes_CSharp = 165, NavigationBar_ItemService_GetTypesInFile_CSharp = 166, NavigationBar_UpdateDropDownsSynchronously_WaitForModel = 167, NavigationBar_UpdateDropDownsSynchronously_WaitForSelectedItemInfo = 168, EventHookup_Determine_If_Event_Hookup = 169, EventHookup_Generate_Handler = 170, EventHookup_Type_Char = 171, Cache_Created = 172, Cache_AddOrAccess = 173, Cache_Remove = 174, Cache_Evict = 175, Cache_EvictAll = 176, Cache_ItemRank = 177, TextStructureNavigator_GetExtentOfWord = 178, TextStructureNavigator_GetSpanOfEnclosing = 179, TextStructureNavigator_GetSpanOfFirstChild = 180, TextStructureNavigator_GetSpanOfNextSibling = 181, TextStructureNavigator_GetSpanOfPreviousSibling = 182, Debugging_LanguageDebugInfoService_GetDataTipSpanAndText = 183, Debugging_VsLanguageDebugInfo_ValidateBreakpointLocation = 184, Debugging_VsLanguageDebugInfo_GetProximityExpressions = 185, Debugging_VsLanguageDebugInfo_ResolveName = 186, Debugging_VsLanguageDebugInfo_GetNameOfLocation = 187, Debugging_VsLanguageDebugInfo_GetDataTipText = 188, Debugging_EncSession = 189, Debugging_EncSession_EditSession = 190, Debugging_EncSession_EditSession_EmitDeltaErrorId = 191, Debugging_EncSession_EditSession_RudeEdit = 192, Simplifier_ReduceAsync = 193, Simplifier_ExpandNode = 194, Simplifier_ExpandToken = 195, ForegroundNotificationService_Processed = 196, ForegroundNotificationService_NotifyOnForeground = 197, BackgroundCompiler_BuildCompilationsAsync = 198, PersistenceService_ReadAsync = 199, PersistenceService_WriteAsync = 200, PersistenceService_ReadAsyncFailed = 201, PersistenceService_WriteAsyncFailed = 202, PersistenceService_Initialization = 203, TemporaryStorageServiceFactory_ReadText = 204, TemporaryStorageServiceFactory_WriteText = 205, TemporaryStorageServiceFactory_ReadStream = 206, TemporaryStorageServiceFactory_WriteStream = 207, PullMembersUpWarning_ChangeTargetToAbstract = 208, PullMembersUpWarning_ChangeOriginToPublic = 209, PullMembersUpWarning_ChangeOriginToNonStatic = 210, PullMembersUpWarning_UserProceedToFinish = 211, PullMembersUpWarning_UserGoBack = 212, // currently no-one uses these SmartTags_RefreshSession = 213, SmartTags_SmartTagInitializeFixes = 214, SmartTags_ApplyQuickFix = 215, EditorTestApp_RefreshTask = 216, EditorTestApp_UpdateDiagnostics = 217, IncrementalAnalyzerProcessor_Analyzers = 218, IncrementalAnalyzerProcessor_Analyzer = 219, IncrementalAnalyzerProcessor_ActiveFileAnalyzers = 220, IncrementalAnalyzerProcessor_ActiveFileAnalyzer = 221, IncrementalAnalyzerProcessor_Shutdown = 222, WorkCoordinatorRegistrationService_Register = 223, WorkCoordinatorRegistrationService_Unregister = 224, WorkCoordinatorRegistrationService_Reanalyze = 225, WorkCoordinator_SolutionCrawlerOption = 226, WorkCoordinator_PersistentStorageAdded = 227, WorkCoordinator_PersistentStorageRemoved = 228, WorkCoordinator_Shutdown = 229, DiagnosticAnalyzerService_Analyzers = 230, DiagnosticAnalyzerDriver_AnalyzerCrash = 231, DiagnosticAnalyzerDriver_AnalyzerTypeCount = 232, // obsolete: PersistedSemanticVersion_Info = 233, StorageDatabase_Exceptions = 234, WorkCoordinator_ShutdownTimeout = 235, Diagnostics_HyperLink = 236, CodeFixes_FixAllOccurrencesSession = 237, CodeFixes_FixAllOccurrencesContext = 238, CodeFixes_FixAllOccurrencesComputation = 239, CodeFixes_FixAllOccurrencesComputation_Document_Diagnostics = 240, CodeFixes_FixAllOccurrencesComputation_Project_Diagnostics = 241, CodeFixes_FixAllOccurrencesComputation_Document_Fixes = 242, CodeFixes_FixAllOccurrencesComputation_Project_Fixes = 243, CodeFixes_FixAllOccurrencesComputation_Document_Merge = 244, CodeFixes_FixAllOccurrencesComputation_Project_Merge = 245, CodeFixes_FixAllOccurrencesPreviewChanges = 246, CodeFixes_ApplyChanges = 247, SolutionExplorer_AnalyzerItemSource_GetItems = 248, SolutionExplorer_DiagnosticItemSource_GetItems = 249, WorkCoordinator_ActiveFileEnqueue = 250, SymbolFinder_FindDeclarationsAsync = 251, SymbolFinder_Project_AddDeclarationsAsync = 252, SymbolFinder_Assembly_AddDeclarationsAsync = 253, SymbolFinder_Solution_Name_FindSourceDeclarationsAsync = 254, SymbolFinder_Project_Name_FindSourceDeclarationsAsync = 255, SymbolFinder_Solution_Predicate_FindSourceDeclarationsAsync = 256, SymbolFinder_Project_Predicate_FindSourceDeclarationsAsync = 257, Tagger_Diagnostics_RecomputeTags = 258, Tagger_Diagnostics_Updated = 259, SuggestedActions_HasSuggestedActionsAsync = 260, SuggestedActions_GetSuggestedActions = 261, AnalyzerDependencyCheckingService_LogConflict = 262, AnalyzerDependencyCheckingService_LogMissingDependency = 263, VirtualMemory_MemoryLow = 264, Extension_Exception = 265, WorkCoordinator_WaitForHigherPriorityOperationsAsync = 266, CSharp_Interactive_Window = 267, VisualBasic_Interactive_Window = 268, NonFatalWatson = 269, GlobalOperationRegistration = 270, CommandHandler_FindAllReference = 271, CodefixInfobar_Enable = 272, CodefixInfobar_EnableAndIgnoreFutureErrors = 273, CodefixInfobar_LeaveDisabled = 274, CodefixInfobar_ErrorIgnored = 275, Refactoring_NamingStyle = 276, // Caches SymbolTreeInfo_ExceptionInCacheRead = 277, SpellChecker_ExceptionInCacheRead = 278, BKTree_ExceptionInCacheRead = 279, IntellisenseBuild_Failed = 280, FileTextLoader_FileLengthThresholdExceeded = 281, // Generic performance measurement action IDs MeasurePerformance_StartAction = 282, MeasurePerformance_StopAction = 283, Serializer_CreateChecksum = 284, Serializer_Serialize = 285, Serializer_Deserialize = 286, CodeAnalysisService_CalculateDiagnosticsAsync = 287, CodeAnalysisService_SerializeDiagnosticResultAsync = 288, CodeAnalysisService_GetReferenceCountAsync = 289, CodeAnalysisService_FindReferenceLocationsAsync = 290, CodeAnalysisService_FindReferenceMethodsAsync = 291, CodeAnalysisService_GetFullyQualifiedName = 292, CodeAnalysisService_GetTodoCommentsAsync = 293, CodeAnalysisService_GetDesignerAttributesAsync = 294, ServiceHubRemoteHostClient_CreateAsync = 295, // obsolete: PinnedRemotableDataScope_GetRemotableData = 296, RemoteHost_Connect = 297, RemoteHost_Disconnect = 298, // obsolete: RemoteHostClientService_AddGlobalAssetsAsync = 299, // obsolete: RemoteHostClientService_RemoveGlobalAssets = 300, // obsolete: RemoteHostClientService_Enabled = 301, // obsolete: RemoteHostClientService_Restarted = 302, RemoteHostService_SynchronizePrimaryWorkspaceAsync = 303, // obsolete: RemoteHostService_SynchronizeGlobalAssetsAsync = 304, AssetStorage_CleanAssets = 305, AssetStorage_TryGetAsset = 306, AssetService_GetAssetAsync = 307, AssetService_SynchronizeAssetsAsync = 308, AssetService_SynchronizeSolutionAssetsAsync = 309, AssetService_SynchronizeProjectAssetsAsync = 310, CodeLens_GetReferenceCountAsync = 311, CodeLens_FindReferenceLocationsAsync = 312, CodeLens_FindReferenceMethodsAsync = 313, CodeLens_GetFullyQualifiedName = 314, SolutionState_ComputeChecksumsAsync = 315, ProjectState_ComputeChecksumsAsync = 316, DocumentState_ComputeChecksumsAsync = 317, // obsolete: SolutionSynchronizationService_GetRemotableData = 318, // obsolete: SolutionSynchronizationServiceFactory_CreatePinnedRemotableDataScopeAsync = 319, SolutionChecksumUpdater_SynchronizePrimaryWorkspace = 320, JsonRpcSession_RequestAssetAsync = 321, SolutionService_GetSolutionAsync = 322, SolutionService_UpdatePrimaryWorkspaceAsync = 323, RemoteHostService_GetAssetsAsync = 324, // obsolete: CompilationService_GetCompilationAsync = 325, SolutionCreator_AssetDifferences = 326, Extension_InfoBar = 327, FxCopAnalyzersInstall = 328, AssetStorage_ForceGC = 329, // obsolete: RemoteHost_Bitness = 330, Intellisense_Completion = 331, MetadataOnlyImage_EmitFailure = 332, LiveTableDataSource_OnDiagnosticsUpdated = 333, Experiment_KeybindingsReset = 334, Diagnostics_GeneratePerformaceReport = 335, Diagnostics_BadAnalyzer = 336, CodeAnalysisService_ReportAnalyzerPerformance = 337, PerformanceTrackerService_AddSnapshot = 338, // obsolete: AbstractProject_SetIntelliSenseBuild = 339, // obsolete: AbstractProject_Created = 340, // obsolete: AbstractProject_PushedToWorkspace = 341, ExternalErrorDiagnosticUpdateSource_AddError = 342, DiagnosticIncrementalAnalyzer_SynchronizeWithBuildAsync = 343, Completion_ExecuteCommand_TypeChar = 344, RemoteHostService_SynchronizeTextAsync = 345, SymbolFinder_Solution_Pattern_FindSourceDeclarationsAsync = 346, SymbolFinder_Project_Pattern_FindSourceDeclarationsAsync = 347, // obsolete: Intellisense_Completion_Commit = 348, CodeCleanupInfobar_BarDisplayed = 349, CodeCleanupInfobar_ConfigureNow = 350, CodeCleanupInfobar_NeverShowCodeCleanupInfoBarAgain = 351, FormatDocument = 352, CodeCleanup_ApplyCodeFixesAsync = 353, CodeCleanup_RemoveUnusedImports = 354, CodeCleanup_SortImports = 355, CodeCleanup_Format = 356, CodeCleanupABTest_AssignedToOnByDefault = 357, CodeCleanupABTest_AssignedToOffByDefault = 358, Workspace_Events = 359, Refactoring_ExtractMethod_UnknownMatrixItem = 360, SyntaxTreeIndex_Precalculate = 361, SyntaxTreeIndex_Precalculate_Create = 362, SymbolTreeInfo_Create = 363, SymbolTreeInfo_TryLoadOrCreate = 364, CommandHandler_GoToImplementation = 365, GraphQuery_ImplementedBy = 366, GraphQuery_Implements = 367, GraphQuery_IsCalledBy = 368, GraphQuery_IsUsedBy = 369, GraphQuery_Overrides = 370, Intellisense_AsyncCompletion_Data = 371, Intellisense_CompletionProviders_Data = 372, RemoteHostService_IsExperimentEnabledAsync = 373, PartialLoad_FullyLoaded = 374, Liveshare_UnknownCodeAction = 375, // obsolete: Liveshare_LexicalClassifications = 376, // obsolete: Liveshare_SyntacticClassifications = 377, // obsolete: Liveshare_SyntacticTagger = 378, CommandHandler_GoToBase = 379, DiagnosticAnalyzerService_GetDiagnosticsForSpanAsync = 380, CodeFixes_GetCodeFixesAsync = 381, LanguageServer_ActivateFailed = 382, LanguageServer_OnLoadedFailed = 383, CodeFixes_AddExplicitCast = 384, ToolsOptions_GenerateEditorconfig = 385, Renamer_RenameSymbolAsync = 386, Renamer_FindRenameLocationsAsync = 387, Renamer_ResolveConflictsAsync = 388, ChangeSignature_Data = 400, AbstractEncapsulateFieldService_EncapsulateFieldsAsync = 410, AbstractConvertTupleToStructCodeRefactoringProvider_ConvertToStructAsync = 420, DependentTypeFinder_FindAndCacheDerivedClassesAsync = 430, DependentTypeFinder_FindAndCacheDerivedInterfacesAsync = 431, DependentTypeFinder_FindAndCacheImplementingTypesAsync = 432, RemoteSemanticClassificationCacheService_ExceptionInCacheRead = 440, // obsolete: FeatureNotAvailable = 441, LSPCompletion_MissingLSPCompletionTriggerKind = 450, LSPCompletion_MissingLSPCompletionInvokeKind = 451, Workspace_Project_CompilationThrownAway = 460, CommandHandler_Paste_ImportsOnPaste = 470, // Superseded by LSP_FindDocumentInWorkspace // obsolete: FindDocumentInWorkspace = 480, RegisterWorkspace = 481, LSP_RequestCounter = 482, LSP_RequestDuration = 483, LSP_TimeInQueue = 484, Intellicode_UnknownIntent = 485, LSP_CompletionListCacheMiss = 486, InheritanceMargin_TargetsMenuOpen = 487, InheritanceMargin_NavigateToTarget = 488, VS_ErrorReportingService_ShowGlobalErrorInfo = 489, UnusedReferences_GetUnusedReferences = 490, ValueTracking_Command = 491, ValueTracking_TrackValueSource = 492, InheritanceMargin_GetInheritanceMemberItems = 493, LSP_FindDocumentInWorkspace = 494, SuggestedActions_GetSuggestedActionsAsync = 500, NavigateTo_CacheItemsMiss = 510, AssetService_Perf = 520, Inline_Hints_DoubleClick = 530, } }
1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/VisualStudio/Core/Def/EditorConfigSettings/Common/EnumPropertyView.xaml.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.Windows.Automation; using System.Windows.Controls; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common { /// <summary> /// Interaction logic for EnumPropertyView.xaml /// </summary> internal partial class EnumSettingView : UserControl { private readonly IEnumSettingViewModel _model; public EnumSettingView(IEnumSettingViewModel model) { InitializeComponent(); DataContext = model; _model = model; } private void EnumValueComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { var index = EnumValueComboBox.SelectedIndex; var descriptions = _model.EnumValues; if (index < descriptions.Length && index >= 0) { _model.ChangeProperty(descriptions[index]); } } } }
// Licensed to the .NET Foundation under one or more 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.Windows.Automation; using System.Windows.Controls; namespace Microsoft.VisualStudio.LanguageServices.EditorConfigSettings.Common { /// <summary> /// Interaction logic for EnumPropertyView.xaml /// </summary> internal partial class EnumSettingView : UserControl { private readonly IEnumSettingViewModel _model; public EnumSettingView(IEnumSettingViewModel model) { InitializeComponent(); DataContext = model; _model = model; } private void EnumValueComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { var index = EnumValueComboBox.SelectedIndex; var descriptions = _model.EnumValues; if (index < descriptions.Length && index >= 0) { _model.ChangeProperty(descriptions[index]); } } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/Core/Portable/NavigationBar/NavigationBarItems/RoslynNavigationBarItem.SymbolItem.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.Linq; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.NavigationBar { internal abstract partial class RoslynNavigationBarItem { public sealed class SymbolItem : RoslynNavigationBarItem, IEquatable<SymbolItem> { public readonly string Name; public readonly bool IsObsolete; public readonly SymbolItemLocation Location; public SymbolItem( string name, string text, Glyph glyph, bool isObsolete, SymbolItemLocation location, ImmutableArray<RoslynNavigationBarItem> childItems = default, int indent = 0, bool bolded = false) : base( RoslynNavigationBarItemKind.Symbol, text, glyph, bolded, grayed: location.OtherDocumentInfo != null, indent, childItems) { Name = name; IsObsolete = isObsolete; Location = location; } protected internal override SerializableNavigationBarItem Dehydrate() => SerializableNavigationBarItem.SymbolItem(Text, Glyph, Name, IsObsolete, Location, SerializableNavigationBarItem.Dehydrate(ChildItems), Indent, Bolded, Grayed); public override bool Equals(object? obj) => Equals(obj as SymbolItem); public bool Equals(SymbolItem? other) => base.Equals(other) && Name == other.Name && IsObsolete == other.IsObsolete && Location.Equals(other.Location); public override int GetHashCode() => throw new NotImplementedException(); } [DataContract] public readonly struct SymbolItemLocation : IEquatable<SymbolItemLocation> { /// <summary> /// The entity spans and navigation span in the originating document where this symbol was found. Any time /// the caret is within any of the entity spans, the item should be appropriately 'selected' in whatever UI /// is displaying these. The navigation span is the location in the starting document that should be /// navigated to when this item is selected If this symbol's location is in another document then this will /// be <see langword="null"/>. /// </summary> /// <remarks>Exactly one of <see cref="InDocumentInfo"/> and <see cref="OtherDocumentInfo"/> will be /// non-null.</remarks> [DataMember(Order = 0)] public readonly (ImmutableArray<TextSpan> spans, TextSpan navigationSpan)? InDocumentInfo; /// <summary> /// The document and navigation span this item should navigate to when the definition is not in the /// originating document. This is used for partial symbols where a child symbol is declared in another file, /// but should still be shown in the UI when in a part in a different file. /// </summary> /// <remarks>Exactly one of <see cref="InDocumentInfo"/> and <see cref="OtherDocumentInfo"/> will be /// non-null.</remarks> [DataMember(Order = 1)] public readonly (DocumentId documentId, TextSpan navigationSpan)? OtherDocumentInfo; public SymbolItemLocation( (ImmutableArray<TextSpan> spans, TextSpan navigationSpan)? inDocumentInfo, (DocumentId documentId, TextSpan navigationSpan)? otherDocumentInfo) { Contract.ThrowIfTrue(inDocumentInfo == null && otherDocumentInfo == null, "Both locations were null"); Contract.ThrowIfTrue(inDocumentInfo != null && otherDocumentInfo != null, "Both locations were not null"); if (inDocumentInfo != null) { Contract.ThrowIfTrue(inDocumentInfo.Value.spans.IsEmpty, "If location is in document, it must have non-empty spans"); } InDocumentInfo = inDocumentInfo; OtherDocumentInfo = otherDocumentInfo; } public override bool Equals(object? obj) => obj is SymbolItemLocation location && Equals(location); public bool Equals(SymbolItemLocation other) { if ((InDocumentInfo == null) != (other.InDocumentInfo == null)) return false; if ((OtherDocumentInfo == null) != (other.OtherDocumentInfo == null)) return false; if (InDocumentInfo != null) { if (!this.InDocumentInfo.Value.spans.SequenceEqual(other.InDocumentInfo!.Value.spans) || this.InDocumentInfo.Value.navigationSpan != other.InDocumentInfo.Value.navigationSpan) { return false; } } if (this.OtherDocumentInfo != null) { if (this.OtherDocumentInfo.Value != other.OtherDocumentInfo!.Value) return false; } return true; } public override int GetHashCode() => throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Linq; using System.Runtime.Serialization; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.NavigationBar { internal abstract partial class RoslynNavigationBarItem { public sealed class SymbolItem : RoslynNavigationBarItem, IEquatable<SymbolItem> { public readonly string Name; public readonly bool IsObsolete; public readonly SymbolItemLocation Location; public SymbolItem( string name, string text, Glyph glyph, bool isObsolete, SymbolItemLocation location, ImmutableArray<RoslynNavigationBarItem> childItems = default, int indent = 0, bool bolded = false) : base( RoslynNavigationBarItemKind.Symbol, text, glyph, bolded, grayed: location.OtherDocumentInfo != null, indent, childItems) { Name = name; IsObsolete = isObsolete; Location = location; } protected internal override SerializableNavigationBarItem Dehydrate() => SerializableNavigationBarItem.SymbolItem(Text, Glyph, Name, IsObsolete, Location, SerializableNavigationBarItem.Dehydrate(ChildItems), Indent, Bolded, Grayed); public override bool Equals(object? obj) => Equals(obj as SymbolItem); public bool Equals(SymbolItem? other) => base.Equals(other) && Name == other.Name && IsObsolete == other.IsObsolete && Location.Equals(other.Location); public override int GetHashCode() => throw new NotImplementedException(); } [DataContract] public readonly struct SymbolItemLocation : IEquatable<SymbolItemLocation> { /// <summary> /// The entity spans and navigation span in the originating document where this symbol was found. Any time /// the caret is within any of the entity spans, the item should be appropriately 'selected' in whatever UI /// is displaying these. The navigation span is the location in the starting document that should be /// navigated to when this item is selected If this symbol's location is in another document then this will /// be <see langword="null"/>. /// </summary> /// <remarks>Exactly one of <see cref="InDocumentInfo"/> and <see cref="OtherDocumentInfo"/> will be /// non-null.</remarks> [DataMember(Order = 0)] public readonly (ImmutableArray<TextSpan> spans, TextSpan navigationSpan)? InDocumentInfo; /// <summary> /// The document and navigation span this item should navigate to when the definition is not in the /// originating document. This is used for partial symbols where a child symbol is declared in another file, /// but should still be shown in the UI when in a part in a different file. /// </summary> /// <remarks>Exactly one of <see cref="InDocumentInfo"/> and <see cref="OtherDocumentInfo"/> will be /// non-null.</remarks> [DataMember(Order = 1)] public readonly (DocumentId documentId, TextSpan navigationSpan)? OtherDocumentInfo; public SymbolItemLocation( (ImmutableArray<TextSpan> spans, TextSpan navigationSpan)? inDocumentInfo, (DocumentId documentId, TextSpan navigationSpan)? otherDocumentInfo) { Contract.ThrowIfTrue(inDocumentInfo == null && otherDocumentInfo == null, "Both locations were null"); Contract.ThrowIfTrue(inDocumentInfo != null && otherDocumentInfo != null, "Both locations were not null"); if (inDocumentInfo != null) { Contract.ThrowIfTrue(inDocumentInfo.Value.spans.IsEmpty, "If location is in document, it must have non-empty spans"); } InDocumentInfo = inDocumentInfo; OtherDocumentInfo = otherDocumentInfo; } public override bool Equals(object? obj) => obj is SymbolItemLocation location && Equals(location); public bool Equals(SymbolItemLocation other) { if ((InDocumentInfo == null) != (other.InDocumentInfo == null)) return false; if ((OtherDocumentInfo == null) != (other.OtherDocumentInfo == null)) return false; if (InDocumentInfo != null) { if (!this.InDocumentInfo.Value.spans.SequenceEqual(other.InDocumentInfo!.Value.spans) || this.InDocumentInfo.Value.navigationSpan != other.InDocumentInfo.Value.navigationSpan) { return false; } } if (this.OtherDocumentInfo != null) { if (this.OtherDocumentInfo.Value != other.OtherDocumentInfo!.Value) return false; } return true; } public override int GetHashCode() => throw new NotImplementedException(); } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/EditorFeatures/Test/Emit/CompilationOutputsTests.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.IO; using System.Linq; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Emit.UnitTests { public class CompilationOutputsTests { private class TestCompilationOutputs : CompilationOutputs { private readonly Func<Stream?>? _openAssemblyStream; private readonly Func<Stream?>? _openPdbStream; public TestCompilationOutputs(Func<Stream?>? openAssemblyStream = null, Func<Stream?>? openPdbStream = null) { _openAssemblyStream = openAssemblyStream; _openPdbStream = openPdbStream; } public override string AssemblyDisplayPath => "assembly"; public override string PdbDisplayPath => "pdb"; protected override Stream? OpenAssemblyStream() => (_openAssemblyStream ?? throw new NotImplementedException()).Invoke(); protected override Stream? OpenPdbStream() => (_openPdbStream ?? throw new NotImplementedException()).Invoke(); } [Theory] [InlineData(true, false)] [InlineData(false, true)] public void OpenStream_Errors(bool canRead, bool canSeek) { var outputs = new TestCompilationOutputs( openAssemblyStream: () => new TestStream(canRead, canSeek, canWrite: true), openPdbStream: () => new TestStream(canRead, canSeek, canWrite: true)); Assert.Throws<InvalidOperationException>(() => outputs.OpenAssemblyMetadata(prefetch: false)); Assert.Throws<InvalidOperationException>(() => outputs.OpenPdb()); } [Theory] [InlineData(DebugInformationFormat.PortablePdb)] [InlineData(DebugInformationFormat.Embedded)] [InlineData(DebugInformationFormat.Pdb)] public void AssemblyAndPdb(DebugInformationFormat format) { var source = @"class C { public static void Main() { int x = 1; } }"; var compilation = CSharpTestBase.CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = (format != DebugInformationFormat.Embedded) ? new MemoryStream() : null; var peImage = compilation.EmitToArray(new EmitOptions(debugInformationFormat: format), pdbStream: pdbStream); Stream? currentPEStream = null; Stream? currentPdbStream = null; var outputs = new TestCompilationOutputs( openAssemblyStream: () => currentPEStream = new MemoryStream(peImage.ToArray()), openPdbStream: () => { if (pdbStream == null) { return null; } currentPdbStream = new MemoryStream(); pdbStream.Position = 0; pdbStream.CopyTo(currentPdbStream); currentPdbStream.Position = 0; return currentPdbStream; }); using (var pdb = outputs.OpenPdb()) { var encReader = pdb!.CreateEditAndContinueMethodDebugInfoReader(); Assert.Equal(format != DebugInformationFormat.Pdb, encReader.IsPortable); var localSig = encReader.GetLocalSignature(MetadataTokens.MethodDefinitionHandle(1)); Assert.Equal(MetadataTokens.StandaloneSignatureHandle(1), localSig); } if (format == DebugInformationFormat.Embedded) { Assert.Throws<ObjectDisposedException>(() => currentPEStream!.Length); } else { Assert.Throws<ObjectDisposedException>(() => currentPdbStream!.Length); } using (var metadata = outputs.OpenAssemblyMetadata(prefetch: false)) { Assert.NotEqual(0, currentPEStream!.Length); var mdReader = metadata!.GetMetadataReader(); Assert.Equal("lib", mdReader.GetString(mdReader.GetAssemblyDefinition().Name)); } Assert.Throws<ObjectDisposedException>(() => currentPEStream.Length); using (var metadata = outputs.OpenAssemblyMetadata(prefetch: true)) { // the stream has been closed since we prefetched the metadata: Assert.Throws<ObjectDisposedException>(() => currentPEStream.Length); var mdReader = metadata!.GetMetadataReader(); Assert.Equal("lib", mdReader.GetString(mdReader.GetAssemblyDefinition().Name)); } Assert.NotEqual(Guid.Empty, outputs.ReadAssemblyModuleVersionId()); } [Fact] public void ReadAssemblyModuleVersionId_NoAssembly() { var outputs = new TestCompilationOutputs( openAssemblyStream: () => null, openPdbStream: () => null); Assert.Equal(Guid.Empty, outputs.ReadAssemblyModuleVersionId()); } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Emit.UnitTests { public class CompilationOutputsTests { private class TestCompilationOutputs : CompilationOutputs { private readonly Func<Stream?>? _openAssemblyStream; private readonly Func<Stream?>? _openPdbStream; public TestCompilationOutputs(Func<Stream?>? openAssemblyStream = null, Func<Stream?>? openPdbStream = null) { _openAssemblyStream = openAssemblyStream; _openPdbStream = openPdbStream; } public override string AssemblyDisplayPath => "assembly"; public override string PdbDisplayPath => "pdb"; protected override Stream? OpenAssemblyStream() => (_openAssemblyStream ?? throw new NotImplementedException()).Invoke(); protected override Stream? OpenPdbStream() => (_openPdbStream ?? throw new NotImplementedException()).Invoke(); } [Theory] [InlineData(true, false)] [InlineData(false, true)] public void OpenStream_Errors(bool canRead, bool canSeek) { var outputs = new TestCompilationOutputs( openAssemblyStream: () => new TestStream(canRead, canSeek, canWrite: true), openPdbStream: () => new TestStream(canRead, canSeek, canWrite: true)); Assert.Throws<InvalidOperationException>(() => outputs.OpenAssemblyMetadata(prefetch: false)); Assert.Throws<InvalidOperationException>(() => outputs.OpenPdb()); } [Theory] [InlineData(DebugInformationFormat.PortablePdb)] [InlineData(DebugInformationFormat.Embedded)] [InlineData(DebugInformationFormat.Pdb)] public void AssemblyAndPdb(DebugInformationFormat format) { var source = @"class C { public static void Main() { int x = 1; } }"; var compilation = CSharpTestBase.CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.DebugDll, assemblyName: "lib"); var pdbStream = (format != DebugInformationFormat.Embedded) ? new MemoryStream() : null; var peImage = compilation.EmitToArray(new EmitOptions(debugInformationFormat: format), pdbStream: pdbStream); Stream? currentPEStream = null; Stream? currentPdbStream = null; var outputs = new TestCompilationOutputs( openAssemblyStream: () => currentPEStream = new MemoryStream(peImage.ToArray()), openPdbStream: () => { if (pdbStream == null) { return null; } currentPdbStream = new MemoryStream(); pdbStream.Position = 0; pdbStream.CopyTo(currentPdbStream); currentPdbStream.Position = 0; return currentPdbStream; }); using (var pdb = outputs.OpenPdb()) { var encReader = pdb!.CreateEditAndContinueMethodDebugInfoReader(); Assert.Equal(format != DebugInformationFormat.Pdb, encReader.IsPortable); var localSig = encReader.GetLocalSignature(MetadataTokens.MethodDefinitionHandle(1)); Assert.Equal(MetadataTokens.StandaloneSignatureHandle(1), localSig); } if (format == DebugInformationFormat.Embedded) { Assert.Throws<ObjectDisposedException>(() => currentPEStream!.Length); } else { Assert.Throws<ObjectDisposedException>(() => currentPdbStream!.Length); } using (var metadata = outputs.OpenAssemblyMetadata(prefetch: false)) { Assert.NotEqual(0, currentPEStream!.Length); var mdReader = metadata!.GetMetadataReader(); Assert.Equal("lib", mdReader.GetString(mdReader.GetAssemblyDefinition().Name)); } Assert.Throws<ObjectDisposedException>(() => currentPEStream.Length); using (var metadata = outputs.OpenAssemblyMetadata(prefetch: true)) { // the stream has been closed since we prefetched the metadata: Assert.Throws<ObjectDisposedException>(() => currentPEStream.Length); var mdReader = metadata!.GetMetadataReader(); Assert.Equal("lib", mdReader.GetString(mdReader.GetAssemblyDefinition().Name)); } Assert.NotEqual(Guid.Empty, outputs.ReadAssemblyModuleVersionId()); } [Fact] public void ReadAssemblyModuleVersionId_NoAssembly() { var outputs = new TestCompilationOutputs( openAssemblyStream: () => null, openPdbStream: () => null); Assert.Equal(Guid.Empty, outputs.ReadAssemblyModuleVersionId()); } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Compilers/CSharp/Test/Emit/Emit/EditAndContinue/EditAndContinuePdbTests.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.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class EditAndContinuePdbTests : EditAndContinueTestBase { [Theory] [MemberData(nameof(ExternalPdbFormats))] public void MethodExtents(DebugInformationFormat format) { var source0 = MarkedSource(WithWindowsLineBreaks(@"#pragma checksum ""C:\Enc1.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""1111111111111111111111111111111111111111"" using System; public class C { int A() => 1; void F() { #line 10 ""C:\F\A.cs"" Console.WriteLine(); #line 20 ""C:\F\B.cs"" Console.WriteLine(); #line default } int E() => 1; void G() { Func<int> <N:4>H1</N:4> = <N:0>() => 1</N:0>; Action <N:5>H2</N:5> = <N:1>() => { Func<int> <N:6>H3</N:6> = <N:2>() => 3</N:2>; }</N:1>; } } "), fileName: @"C:\Enc1.cs"); var source1 = MarkedSource(WithWindowsLineBreaks(@"#pragma checksum ""C:\Enc1.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""2222222222222222222222222222222222222222"" using System; public class C { int A() => 1; void F() { #line 10 ""C:\F\A.cs"" Console.WriteLine(); #line 10 ""C:\F\C.cs"" Console.WriteLine(); #line default } void G() { Func<int> <N:4>H1</N:4> = <N:0>() => 1</N:0>; Action <N:5>H2</N:5> = <N:1>() => { Func<int> <N:6>H3</N:6> = <N:2>() => 3</N:2>; Func<int> <N:7>H4</N:7> = <N:3>() => 4</N:3>; }</N:1>; } int E() => 1; } "), fileName: @"C:\Enc1.cs"); var source2 = MarkedSource(WithWindowsLineBreaks(@"#pragma checksum ""C:\Enc1.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""3333333333333333333333333333333333333333"" using System; public class C { int A() => 3; void F() { #line 10 ""C:\F\B.cs"" Console.WriteLine(); #line 10 ""C:\F\E.cs"" Console.WriteLine(); #line default } void G() { Action <N:5>H2</N:5> = <N:1>() => { Func<int> <N:7>H4</N:7> = <N:3>() => 4</N:3>; }</N:1>; } int E() => 1; int B() => 4; } "), fileName: @"C:\Enc1.cs"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "EncMethodExtents"); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); compilation0.VerifyDiagnostics(); compilation1.VerifyDiagnostics(); compilation2.VerifyDiagnostics(); var v0 = CompileAndVerify(compilation0, emitOptions: EmitOptions.Default.WithDebugInformationFormat(format)); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var a1 = compilation1.GetMember<MethodSymbol>("C.A"); var a2 = compilation2.GetMember<MethodSymbol>("C.A"); var b2 = compilation2.GetMember<MethodSymbol>("C.B"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var syntaxMap1 = GetSyntaxMapFromMarkers(source0, source1); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, syntaxMap1, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, g0, g1, syntaxMap1, preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__3_0, <>9__3_2, <>9__3_3#1, <>9__3_1, <G>b__3_0, <G>b__3_1, <G>b__3_2, <G>b__3_3#1}"); var reader1 = diff1.GetMetadata().Reader; CheckEncLogDefinitions(reader1, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(5, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default)); if (format == DebugInformationFormat.PortablePdb) { using var pdbProvider = MetadataReaderProvider.FromPortablePdbImage(diff1.PdbDelta); CheckEncMap(pdbProvider.GetMetadataReader(), Handle(2, TableIndex.MethodDebugInformation), Handle(4, TableIndex.MethodDebugInformation), Handle(8, TableIndex.MethodDebugInformation), Handle(9, TableIndex.MethodDebugInformation), Handle(10, TableIndex.MethodDebugInformation), Handle(11, TableIndex.MethodDebugInformation)); } diff1.VerifyPdb(Enumerable.Range(0x06000001, 20), @" <symbols> <files> <file id=""1"" name=""C:\Enc1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""0B-95-CB-78-00-AE-C7-34-45-D9-FB-31-E4-30-A4-0E-FC-EA-9E-95"" /> <file id=""2"" name=""C:\F\A.cs"" language=""C#"" /> <file id=""3"" name=""C:\F\C.cs"" language=""C#"" /> </files> <methods> <method token=""0x6000002""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""2"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""3"" /> <entry offset=""0xd"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xe""> <namespace name=""System"" /> </scope> </method> <method token=""0x6000004""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""54"" document=""1"" /> <entry offset=""0x21"" startLine=""21"" startColumn=""9"" endLine=""25"" endColumn=""17"" document=""1"" /> <entry offset=""0x41"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x42""> <local name=""H1"" il_index=""0"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" /> <local name=""H2"" il_index=""1"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" /> </scope> </method> <method token=""0x6000008""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""46"" endLine=""19"" endColumn=""47"" document=""1"" /> </sequencePoints> </method> <method token=""0x6000009""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""58"" document=""1"" /> <entry offset=""0x21"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""58"" document=""1"" /> <entry offset=""0x41"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x42""> <local name=""H3"" il_index=""0"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" /> <local name=""H4"" il_index=""1"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" /> </scope> </method> <method token=""0x600000a""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""23"" startColumn=""50"" endLine=""23"" endColumn=""51"" document=""1"" /> </sequencePoints> </method> <method token=""0x600000b""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""24"" startColumn=""50"" endLine=""24"" endColumn=""51"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); var syntaxMap2 = GetSyntaxMapFromMarkers(source1, source2); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, syntaxMap2, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, g1, g2, syntaxMap2, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, a1, a2, syntaxMap2, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Insert, null, b2))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__3_3#1, <>9__3_1, <G>b__3_1, <G>b__3_3#1, <>9__3_0, <>9__3_2, <G>b__3_0, <G>b__3_2}"); var reader2 = diff2.GetMetadata().Reader; CheckEncLogDefinitions(reader2, Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default)); if (format == DebugInformationFormat.PortablePdb) { using var pdbProvider = MetadataReaderProvider.FromPortablePdbImage(diff2.PdbDelta); CheckEncMap(pdbProvider.GetMetadataReader(), Handle(1, TableIndex.MethodDebugInformation), Handle(2, TableIndex.MethodDebugInformation), Handle(4, TableIndex.MethodDebugInformation), Handle(9, TableIndex.MethodDebugInformation), Handle(11, TableIndex.MethodDebugInformation), Handle(12, TableIndex.MethodDebugInformation)); } diff2.VerifyPdb(Enumerable.Range(0x06000001, 20), @" <symbols> <files> <file id=""1"" name=""C:\Enc1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""9C-B9-FF-18-0E-9F-A4-22-93-85-A8-5A-06-11-43-1E-64-3E-88-06"" /> <file id=""2"" name=""C:\F\B.cs"" language=""C#"" /> <file id=""3"" name=""C:\F\E.cs"" language=""C#"" /> </files> <methods> <method token=""0x6000001""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""16"" endLine=""6"" endColumn=""17"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> </scope> </method> <method token=""0x6000002""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""2"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""3"" /> <entry offset=""0xd"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method token=""0x6000004""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""21"" startColumn=""9"" endLine=""25"" endColumn=""17"" document=""1"" /> <entry offset=""0x21"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x22""> <local name=""H2"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" /> </scope> </method> <method token=""0x6000009""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""58"" document=""1"" /> <entry offset=""0x21"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x22""> <local name=""H4"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" /> </scope> </method> <method token=""0x600000b""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""24"" startColumn=""50"" endLine=""24"" endColumn=""51"" document=""1"" /> </sequencePoints> </method> <method token=""0x600000c""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""30"" startColumn=""16"" endLine=""30"" endColumn=""17"" document=""1"" /> </sequencePoints> </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.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.EditAndContinue.UnitTests { public class EditAndContinuePdbTests : EditAndContinueTestBase { [Theory] [MemberData(nameof(ExternalPdbFormats))] public void MethodExtents(DebugInformationFormat format) { var source0 = MarkedSource(WithWindowsLineBreaks(@"#pragma checksum ""C:\Enc1.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""1111111111111111111111111111111111111111"" using System; public class C { int A() => 1; void F() { #line 10 ""C:\F\A.cs"" Console.WriteLine(); #line 20 ""C:\F\B.cs"" Console.WriteLine(); #line default } int E() => 1; void G() { Func<int> <N:4>H1</N:4> = <N:0>() => 1</N:0>; Action <N:5>H2</N:5> = <N:1>() => { Func<int> <N:6>H3</N:6> = <N:2>() => 3</N:2>; }</N:1>; } } "), fileName: @"C:\Enc1.cs"); var source1 = MarkedSource(WithWindowsLineBreaks(@"#pragma checksum ""C:\Enc1.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""2222222222222222222222222222222222222222"" using System; public class C { int A() => 1; void F() { #line 10 ""C:\F\A.cs"" Console.WriteLine(); #line 10 ""C:\F\C.cs"" Console.WriteLine(); #line default } void G() { Func<int> <N:4>H1</N:4> = <N:0>() => 1</N:0>; Action <N:5>H2</N:5> = <N:1>() => { Func<int> <N:6>H3</N:6> = <N:2>() => 3</N:2>; Func<int> <N:7>H4</N:7> = <N:3>() => 4</N:3>; }</N:1>; } int E() => 1; } "), fileName: @"C:\Enc1.cs"); var source2 = MarkedSource(WithWindowsLineBreaks(@"#pragma checksum ""C:\Enc1.cs"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""3333333333333333333333333333333333333333"" using System; public class C { int A() => 3; void F() { #line 10 ""C:\F\B.cs"" Console.WriteLine(); #line 10 ""C:\F\E.cs"" Console.WriteLine(); #line default } void G() { Action <N:5>H2</N:5> = <N:1>() => { Func<int> <N:7>H4</N:7> = <N:3>() => 4</N:3>; }</N:1>; } int E() => 1; int B() => 4; } "), fileName: @"C:\Enc1.cs"); var compilation0 = CreateCompilation(source0.Tree, options: ComSafeDebugDll.WithMetadataImportOptions(MetadataImportOptions.All), assemblyName: "EncMethodExtents"); var compilation1 = compilation0.WithSource(source1.Tree); var compilation2 = compilation1.WithSource(source2.Tree); compilation0.VerifyDiagnostics(); compilation1.VerifyDiagnostics(); compilation2.VerifyDiagnostics(); var v0 = CompileAndVerify(compilation0, emitOptions: EmitOptions.Default.WithDebugInformationFormat(format)); var md0 = ModuleMetadata.CreateFromImage(v0.EmittedAssemblyData); var f0 = compilation0.GetMember<MethodSymbol>("C.F"); var f1 = compilation1.GetMember<MethodSymbol>("C.F"); var f2 = compilation2.GetMember<MethodSymbol>("C.F"); var g0 = compilation0.GetMember<MethodSymbol>("C.G"); var g1 = compilation1.GetMember<MethodSymbol>("C.G"); var g2 = compilation2.GetMember<MethodSymbol>("C.G"); var a1 = compilation1.GetMember<MethodSymbol>("C.A"); var a2 = compilation2.GetMember<MethodSymbol>("C.A"); var b2 = compilation2.GetMember<MethodSymbol>("C.B"); var generation0 = EmitBaseline.CreateInitialBaseline(md0, v0.CreateSymReader().GetEncMethodDebugInfo); var syntaxMap1 = GetSyntaxMapFromMarkers(source0, source1); var diff1 = compilation1.EmitDifference( generation0, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f0, f1, syntaxMap1, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, g0, g1, syntaxMap1, preserveLocalVariables: true))); diff1.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__3_0, <>9__3_2, <>9__3_3#1, <>9__3_1, <G>b__3_0, <G>b__3_1, <G>b__3_2, <G>b__3_3#1}"); var reader1 = diff1.GetMetadata().Reader; CheckEncLogDefinitions(reader1, Row(3, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(4, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddField), Row(5, TableIndex.Field, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(8, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(10, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(3, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default)); if (format == DebugInformationFormat.PortablePdb) { using var pdbProvider = MetadataReaderProvider.FromPortablePdbImage(diff1.PdbDelta); CheckEncMap(pdbProvider.GetMetadataReader(), Handle(2, TableIndex.MethodDebugInformation), Handle(4, TableIndex.MethodDebugInformation), Handle(8, TableIndex.MethodDebugInformation), Handle(9, TableIndex.MethodDebugInformation), Handle(10, TableIndex.MethodDebugInformation), Handle(11, TableIndex.MethodDebugInformation)); } diff1.VerifyPdb(Enumerable.Range(0x06000001, 20), @" <symbols> <files> <file id=""1"" name=""C:\Enc1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""0B-95-CB-78-00-AE-C7-34-45-D9-FB-31-E4-30-A4-0E-FC-EA-9E-95"" /> <file id=""2"" name=""C:\F\A.cs"" language=""C#"" /> <file id=""3"" name=""C:\F\C.cs"" language=""C#"" /> </files> <methods> <method token=""0x6000002""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""2"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""3"" /> <entry offset=""0xd"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0xe""> <namespace name=""System"" /> </scope> </method> <method token=""0x6000004""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""19"" startColumn=""9"" endLine=""19"" endColumn=""54"" document=""1"" /> <entry offset=""0x21"" startLine=""21"" startColumn=""9"" endLine=""25"" endColumn=""17"" document=""1"" /> <entry offset=""0x41"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x42""> <local name=""H1"" il_index=""0"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" /> <local name=""H2"" il_index=""1"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" /> </scope> </method> <method token=""0x6000008""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""19"" startColumn=""46"" endLine=""19"" endColumn=""47"" document=""1"" /> </sequencePoints> </method> <method token=""0x6000009""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""23"" startColumn=""13"" endLine=""23"" endColumn=""58"" document=""1"" /> <entry offset=""0x21"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""58"" document=""1"" /> <entry offset=""0x41"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x42""> <local name=""H3"" il_index=""0"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" /> <local name=""H4"" il_index=""1"" il_start=""0x0"" il_end=""0x42"" attributes=""0"" /> </scope> </method> <method token=""0x600000a""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""23"" startColumn=""50"" endLine=""23"" endColumn=""51"" document=""1"" /> </sequencePoints> </method> <method token=""0x600000b""> <customDebugInfo> <forward token=""0x6000002"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""24"" startColumn=""50"" endLine=""24"" endColumn=""51"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); var syntaxMap2 = GetSyntaxMapFromMarkers(source1, source2); var diff2 = compilation2.EmitDifference( diff1.NextGeneration, ImmutableArray.Create( SemanticEdit.Create(SemanticEditKind.Update, f1, f2, syntaxMap2, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, g1, g2, syntaxMap2, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Update, a1, a2, syntaxMap2, preserveLocalVariables: true), SemanticEdit.Create(SemanticEditKind.Insert, null, b2))); diff2.VerifySynthesizedMembers( "C: {<>c}", "C.<>c: {<>9__3_3#1, <>9__3_1, <G>b__3_1, <G>b__3_3#1, <>9__3_0, <>9__3_2, <G>b__3_0, <G>b__3_2}"); var reader2 = diff2.GetMetadata().Reader; CheckEncLogDefinitions(reader2, Row(5, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(6, TableIndex.StandAloneSig, EditAndContinueOperation.Default), Row(1, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(4, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(9, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(11, TableIndex.MethodDef, EditAndContinueOperation.Default), Row(2, TableIndex.TypeDef, EditAndContinueOperation.AddMethod), Row(12, TableIndex.MethodDef, EditAndContinueOperation.Default)); if (format == DebugInformationFormat.PortablePdb) { using var pdbProvider = MetadataReaderProvider.FromPortablePdbImage(diff2.PdbDelta); CheckEncMap(pdbProvider.GetMetadataReader(), Handle(1, TableIndex.MethodDebugInformation), Handle(2, TableIndex.MethodDebugInformation), Handle(4, TableIndex.MethodDebugInformation), Handle(9, TableIndex.MethodDebugInformation), Handle(11, TableIndex.MethodDebugInformation), Handle(12, TableIndex.MethodDebugInformation)); } diff2.VerifyPdb(Enumerable.Range(0x06000001, 20), @" <symbols> <files> <file id=""1"" name=""C:\Enc1.cs"" language=""C#"" checksumAlgorithm=""SHA1"" checksum=""9C-B9-FF-18-0E-9F-A4-22-93-85-A8-5A-06-11-43-1E-64-3E-88-06"" /> <file id=""2"" name=""C:\F\B.cs"" language=""C#"" /> <file id=""3"" name=""C:\F\E.cs"" language=""C#"" /> </files> <methods> <method token=""0x6000001""> <customDebugInfo> <using> <namespace usingCount=""1"" /> </using> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""6"" startColumn=""16"" endLine=""6"" endColumn=""17"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x2""> <namespace name=""System"" /> </scope> </method> <method token=""0x6000002""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""9"" startColumn=""5"" endLine=""9"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""2"" /> <entry offset=""0x7"" startLine=""10"" startColumn=""9"" endLine=""10"" endColumn=""29"" document=""3"" /> <entry offset=""0xd"" startLine=""15"" startColumn=""5"" endLine=""15"" endColumn=""6"" document=""1"" /> </sequencePoints> </method> <method token=""0x6000004""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""18"" startColumn=""5"" endLine=""18"" endColumn=""6"" document=""1"" /> <entry offset=""0x1"" startLine=""21"" startColumn=""9"" endLine=""25"" endColumn=""17"" document=""1"" /> <entry offset=""0x21"" startLine=""26"" startColumn=""5"" endLine=""26"" endColumn=""6"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x22""> <local name=""H2"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" /> </scope> </method> <method token=""0x6000009""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""22"" startColumn=""9"" endLine=""22"" endColumn=""10"" document=""1"" /> <entry offset=""0x1"" startLine=""24"" startColumn=""13"" endLine=""24"" endColumn=""58"" document=""1"" /> <entry offset=""0x21"" startLine=""25"" startColumn=""9"" endLine=""25"" endColumn=""10"" document=""1"" /> </sequencePoints> <scope startOffset=""0x0"" endOffset=""0x22""> <local name=""H4"" il_index=""1"" il_start=""0x0"" il_end=""0x22"" attributes=""0"" /> </scope> </method> <method token=""0x600000b""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""24"" startColumn=""50"" endLine=""24"" endColumn=""51"" document=""1"" /> </sequencePoints> </method> <method token=""0x600000c""> <customDebugInfo> <forward token=""0x6000001"" /> </customDebugInfo> <sequencePoints> <entry offset=""0x0"" startLine=""30"" startColumn=""16"" endLine=""30"" endColumn=""17"" document=""1"" /> </sequencePoints> </method> </methods> </symbols> "); } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/VisualBasic/Portable/Completion/CompletionProviders/PartialTypeCompletionProvider.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.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers <ExportCompletionProvider(NameOf(PartialTypeCompletionProvider), LanguageNames.VisualBasic)> <ExtensionOrder(After:=NameOf(HandlesClauseCompletionProvider))> <[Shared]> Partial Friend Class PartialTypeCompletionProvider Inherits AbstractPartialTypeCompletionProvider(Of VisualBasicSyntaxContext) Private Const InsertionTextOnOpenParen As String = NameOf(InsertionTextOnOpenParen) Private Shared ReadOnly _insertionTextFormatWithGenerics As SymbolDisplayFormat = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, miscellaneousOptions:= SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers Or SymbolDisplayMiscellaneousOptions.UseSpecialTypes, genericsOptions:= SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance Or SymbolDisplayGenericsOptions.IncludeTypeConstraints) Private Shared ReadOnly _displayTextFormat As SymbolDisplayFormat = _insertionTextFormatWithGenerics.RemoveMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Friend Overrides ReadOnly Property Language As String Get Return LanguageNames.VisualBasic End Get End Property Public Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As CompletionOptions) As Boolean Return CompletionUtilities.IsDefaultTriggerCharacter(text, characterPosition, options) End Function Public Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = CompletionUtilities.CommonTriggerChars Protected Overrides Function GetPartialTypeSyntaxNode(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As SyntaxNode Dim statement As TypeStatementSyntax = Nothing Return If(tree.IsPartialTypeDeclarationNameContext(position, cancellationToken, statement), statement, Nothing) End Function Protected Overrides Function GetDisplayAndSuffixAndInsertionText(symbol As INamedTypeSymbol, context As VisualBasicSyntaxContext) As (displayText As String, suffix As String, insertionText As String) Dim displayText = symbol.ToMinimalDisplayString(context.SemanticModel, context.Position, format:=_displayTextFormat) Dim insertionText = symbol.ToMinimalDisplayString(context.SemanticModel, context.Position, format:=_insertionTextFormatWithGenerics) Return (displayText, "", insertionText) End Function Protected Overrides Function GetProperties(symbol As INamedTypeSymbol, context As VisualBasicSyntaxContext) As ImmutableDictionary(Of String, String) Return ImmutableDictionary(Of String, String).Empty.Add( InsertionTextOnOpenParen, symbol.Name.EscapeIdentifier()) End Function Public Overrides Async Function GetTextChangeAsync(document As Document, selectedItem As CompletionItem, ch As Char?, cancellationToken As CancellationToken) As Task(Of TextChange?) If ch = "("c Then Dim insertionText As String = Nothing If selectedItem.Properties.TryGetValue(InsertionTextOnOpenParen, insertionText) Then Return New TextChange(selectedItem.Span, insertionText) End If End If Return Await MyBase.GetTextChangeAsync(document, selectedItem, ch, cancellationToken).ConfigureAwait(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.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.Completion Imports Microsoft.CodeAnalysis.Completion.Providers Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.Providers <ExportCompletionProvider(NameOf(PartialTypeCompletionProvider), LanguageNames.VisualBasic)> <ExtensionOrder(After:=NameOf(HandlesClauseCompletionProvider))> <[Shared]> Partial Friend Class PartialTypeCompletionProvider Inherits AbstractPartialTypeCompletionProvider(Of VisualBasicSyntaxContext) Private Const InsertionTextOnOpenParen As String = NameOf(InsertionTextOnOpenParen) Private Shared ReadOnly _insertionTextFormatWithGenerics As SymbolDisplayFormat = New SymbolDisplayFormat( globalNamespaceStyle:=SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle:=SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, miscellaneousOptions:= SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers Or SymbolDisplayMiscellaneousOptions.UseSpecialTypes, genericsOptions:= SymbolDisplayGenericsOptions.IncludeTypeParameters Or SymbolDisplayGenericsOptions.IncludeVariance Or SymbolDisplayGenericsOptions.IncludeTypeConstraints) Private Shared ReadOnly _displayTextFormat As SymbolDisplayFormat = _insertionTextFormatWithGenerics.RemoveMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers) <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Friend Overrides ReadOnly Property Language As String Get Return LanguageNames.VisualBasic End Get End Property Public Overrides Function IsInsertionTrigger(text As SourceText, characterPosition As Integer, options As CompletionOptions) As Boolean Return CompletionUtilities.IsDefaultTriggerCharacter(text, characterPosition, options) End Function Public Overrides ReadOnly Property TriggerCharacters As ImmutableHashSet(Of Char) = CompletionUtilities.CommonTriggerChars Protected Overrides Function GetPartialTypeSyntaxNode(tree As SyntaxTree, position As Integer, cancellationToken As CancellationToken) As SyntaxNode Dim statement As TypeStatementSyntax = Nothing Return If(tree.IsPartialTypeDeclarationNameContext(position, cancellationToken, statement), statement, Nothing) End Function Protected Overrides Function GetDisplayAndSuffixAndInsertionText(symbol As INamedTypeSymbol, context As VisualBasicSyntaxContext) As (displayText As String, suffix As String, insertionText As String) Dim displayText = symbol.ToMinimalDisplayString(context.SemanticModel, context.Position, format:=_displayTextFormat) Dim insertionText = symbol.ToMinimalDisplayString(context.SemanticModel, context.Position, format:=_insertionTextFormatWithGenerics) Return (displayText, "", insertionText) End Function Protected Overrides Function GetProperties(symbol As INamedTypeSymbol, context As VisualBasicSyntaxContext) As ImmutableDictionary(Of String, String) Return ImmutableDictionary(Of String, String).Empty.Add( InsertionTextOnOpenParen, symbol.Name.EscapeIdentifier()) End Function Public Overrides Async Function GetTextChangeAsync(document As Document, selectedItem As CompletionItem, ch As Char?, cancellationToken As CancellationToken) As Task(Of TextChange?) If ch = "("c Then Dim insertionText As String = Nothing If selectedItem.Properties.TryGetValue(InsertionTextOnOpenParen, insertionText) Then Return New TextChange(selectedItem.Span, insertionText) End If End If Return Await MyBase.GetTextChangeAsync(document, selectedItem, ch, cancellationToken).ConfigureAwait(False) End Function End Class End Namespace
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/EditorFeatures/Core/Shared/Tagging/EventSources/AbstractTaggerEventSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Editor.Tagging; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { internal abstract class AbstractTaggerEventSource : ITaggerEventSource { protected AbstractTaggerEventSource() { } public abstract void Connect(); public abstract void Disconnect(); public event EventHandler<TaggerEventArgs>? Changed; protected virtual void RaiseChanged() => this.Changed?.Invoke(this, new TaggerEventArgs()); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Editor.Tagging; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { internal abstract class AbstractTaggerEventSource : ITaggerEventSource { protected AbstractTaggerEventSource() { } public abstract void Connect(); public abstract void Disconnect(); public event EventHandler<TaggerEventArgs>? Changed; protected virtual void RaiseChanged() => this.Changed?.Invoke(this, new TaggerEventArgs()); } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/VisualBasic/Portable/Structure/Providers/ConstructorDeclarationStructureProvider.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.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class ConstructorDeclarationStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of SubNewStatementSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, constructorDeclaration As SubNewStatementSyntax, ByRef spans As TemporaryArray(Of BlockSpan), options As BlockStructureOptions, cancellationToken As CancellationToken) CollectCommentsRegions(constructorDeclaration, spans, options) Dim block = TryCast(constructorDeclaration.Parent, ConstructorBlockSyntax) If Not block?.EndBlockStatement.IsMissing Then spans.AddIfNotNull(CreateBlockSpanFromBlock( block, bannerNode:=constructorDeclaration, autoCollapse:=True, type:=BlockTypes.Member, isCollapsible:=True)) End If End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.[Shared].Collections Imports Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Structure Friend Class ConstructorDeclarationStructureProvider Inherits AbstractSyntaxNodeStructureProvider(Of SubNewStatementSyntax) Protected Overrides Sub CollectBlockSpans(previousToken As SyntaxToken, constructorDeclaration As SubNewStatementSyntax, ByRef spans As TemporaryArray(Of BlockSpan), options As BlockStructureOptions, cancellationToken As CancellationToken) CollectCommentsRegions(constructorDeclaration, spans, options) Dim block = TryCast(constructorDeclaration.Parent, ConstructorBlockSyntax) If Not block?.EndBlockStatement.IsMissing Then spans.AddIfNotNull(CreateBlockSpanFromBlock( block, bannerNode:=constructorDeclaration, autoCollapse:=True, type:=BlockTypes.Member, isCollapsible:=True)) End If End Sub End Class End Namespace
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Compilers/CSharp/Portable/Errors/LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo.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; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo : DiagnosticInfo { private DiagnosticInfo? _lazyActualUnmanagedCallersOnlyDiagnostic; private readonly MethodSymbol _method; private readonly bool _isDelegateConversion; internal LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo(MethodSymbol method, bool isDelegateConversion) : base(CSharp.MessageProvider.Instance, (int)ErrorCode.Unknown) { _method = method; _lazyActualUnmanagedCallersOnlyDiagnostic = null; _isDelegateConversion = isDelegateConversion; } internal override DiagnosticInfo GetResolvedInfo() { if (_lazyActualUnmanagedCallersOnlyDiagnostic is null) { UnmanagedCallersOnlyAttributeData? unmanagedCallersOnlyAttributeData = _method.GetUnmanagedCallersOnlyAttributeData(forceComplete: true); Debug.Assert(!ReferenceEquals(unmanagedCallersOnlyAttributeData, UnmanagedCallersOnlyAttributeData.Uninitialized)); Debug.Assert(!ReferenceEquals(unmanagedCallersOnlyAttributeData, UnmanagedCallersOnlyAttributeData.AttributePresentDataNotBound)); var info = unmanagedCallersOnlyAttributeData is null ? CSDiagnosticInfo.VoidDiagnosticInfo : new CSDiagnosticInfo(_isDelegateConversion ? ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate : ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, _method); Interlocked.CompareExchange(ref _lazyActualUnmanagedCallersOnlyDiagnostic, info, null); } return _lazyActualUnmanagedCallersOnlyDiagnostic; } } }
// Licensed to the .NET Foundation under one or more 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; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo : DiagnosticInfo { private DiagnosticInfo? _lazyActualUnmanagedCallersOnlyDiagnostic; private readonly MethodSymbol _method; private readonly bool _isDelegateConversion; internal LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo(MethodSymbol method, bool isDelegateConversion) : base(CSharp.MessageProvider.Instance, (int)ErrorCode.Unknown) { _method = method; _lazyActualUnmanagedCallersOnlyDiagnostic = null; _isDelegateConversion = isDelegateConversion; } internal override DiagnosticInfo GetResolvedInfo() { if (_lazyActualUnmanagedCallersOnlyDiagnostic is null) { UnmanagedCallersOnlyAttributeData? unmanagedCallersOnlyAttributeData = _method.GetUnmanagedCallersOnlyAttributeData(forceComplete: true); Debug.Assert(!ReferenceEquals(unmanagedCallersOnlyAttributeData, UnmanagedCallersOnlyAttributeData.Uninitialized)); Debug.Assert(!ReferenceEquals(unmanagedCallersOnlyAttributeData, UnmanagedCallersOnlyAttributeData.AttributePresentDataNotBound)); var info = unmanagedCallersOnlyAttributeData is null ? CSDiagnosticInfo.VoidDiagnosticInfo : new CSDiagnosticInfo(_isDelegateConversion ? ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate : ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, _method); Interlocked.CompareExchange(ref _lazyActualUnmanagedCallersOnlyDiagnostic, info, null); } return _lazyActualUnmanagedCallersOnlyDiagnostic; } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/Core/Portable/InvertIf/AbstractInvertIfCodeRefactoringProvider.StatementRange.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.Diagnostics; namespace Microsoft.CodeAnalysis.InvertIf { internal abstract partial class AbstractInvertIfCodeRefactoringProvider<TIfStatementSyntax, TStatementSyntax, TEmbeddedStatement> { protected readonly struct StatementRange { public readonly TStatementSyntax FirstStatement; public readonly TStatementSyntax LastStatement; public StatementRange(TStatementSyntax firstStatement, TStatementSyntax lastStatement) { Debug.Assert(firstStatement != null); Debug.Assert(lastStatement != null); Debug.Assert(firstStatement.Parent != null); Debug.Assert(firstStatement.Parent == lastStatement.Parent); Debug.Assert(firstStatement.SpanStart <= lastStatement.SpanStart); FirstStatement = firstStatement; LastStatement = lastStatement; } public bool IsEmpty => FirstStatement == null; public SyntaxNode Parent => FirstStatement.Parent; } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; namespace Microsoft.CodeAnalysis.InvertIf { internal abstract partial class AbstractInvertIfCodeRefactoringProvider<TIfStatementSyntax, TStatementSyntax, TEmbeddedStatement> { protected readonly struct StatementRange { public readonly TStatementSyntax FirstStatement; public readonly TStatementSyntax LastStatement; public StatementRange(TStatementSyntax firstStatement, TStatementSyntax lastStatement) { Debug.Assert(firstStatement != null); Debug.Assert(lastStatement != null); Debug.Assert(firstStatement.Parent != null); Debug.Assert(firstStatement.Parent == lastStatement.Parent); Debug.Assert(firstStatement.SpanStart <= lastStatement.SpanStart); FirstStatement = firstStatement; LastStatement = lastStatement; } public bool IsEmpty => FirstStatement == null; public SyntaxNode Parent => FirstStatement.Parent; } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/VisualStudio/Core/Def/Implementation/Extensions/VsTextSpanExtensions.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.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Extensions { internal static class VsTextSpanExtensions { public static bool TryMapSpanFromSecondaryBufferToPrimaryBuffer(this VsTextSpan spanInSecondaryBuffer, Microsoft.CodeAnalysis.Workspace workspace, DocumentId documentId, out VsTextSpan spanInPrimaryBuffer) { spanInPrimaryBuffer = default; if (workspace is not VisualStudioWorkspaceImpl visualStudioWorkspace) { return false; } var containedDocument = visualStudioWorkspace.TryGetContainedDocument(documentId); if (containedDocument == null) { return false; } var bufferCoordinator = containedDocument.BufferCoordinator; var primary = new VsTextSpan[1]; var hresult = bufferCoordinator.MapSecondaryToPrimarySpan(spanInSecondaryBuffer, primary); spanInPrimaryBuffer = primary[0]; return ErrorHandler.Succeeded(hresult); } } }
// Licensed to the .NET Foundation under one or more 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.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Venus; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Extensions { internal static class VsTextSpanExtensions { public static bool TryMapSpanFromSecondaryBufferToPrimaryBuffer(this VsTextSpan spanInSecondaryBuffer, Microsoft.CodeAnalysis.Workspace workspace, DocumentId documentId, out VsTextSpan spanInPrimaryBuffer) { spanInPrimaryBuffer = default; if (workspace is not VisualStudioWorkspaceImpl visualStudioWorkspace) { return false; } var containedDocument = visualStudioWorkspace.TryGetContainedDocument(documentId); if (containedDocument == null) { return false; } var bufferCoordinator = containedDocument.BufferCoordinator; var primary = new VsTextSpan[1]; var hresult = bufferCoordinator.MapSecondaryToPrimarySpan(spanInSecondaryBuffer, primary); spanInPrimaryBuffer = primary[0]; return ErrorHandler.Succeeded(hresult); } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/Core/Portable/InlineHints/InlineTypeHintsOptions.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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.InlineHints { internal readonly record struct InlineTypeHintsOptions( bool EnabledForTypes, bool ForImplicitVariableTypes, bool ForLambdaParameterTypes, bool ForImplicitObjectCreation) { public static InlineTypeHintsOptions From(Project project) => From(project.Solution.Options, project.Language); public static InlineTypeHintsOptions From(OptionSet options, string language) => new( EnabledForTypes: options.GetOption(Metadata.EnabledForTypes, language), ForImplicitVariableTypes: options.GetOption(Metadata.ForImplicitVariableTypes, language), ForLambdaParameterTypes: options.GetOption(Metadata.ForLambdaParameterTypes, language), ForImplicitObjectCreation: options.GetOption(Metadata.ForImplicitObjectCreation, language)); [ExportSolutionOptionProvider, Shared] internal sealed class Metadata : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Metadata() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( EnabledForTypes, ForImplicitVariableTypes, ForLambdaParameterTypes, ForImplicitObjectCreation); private const string FeatureName = "InlineHintsOptions"; public static readonly PerLanguageOption2<bool> EnabledForTypes = new(FeatureName, nameof(EnabledForTypes), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineTypeHints")); public static readonly PerLanguageOption2<bool> ForImplicitVariableTypes = new(FeatureName, nameof(ForImplicitVariableTypes), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineTypeHints.ForImplicitVariableTypes")); public static readonly PerLanguageOption2<bool> ForLambdaParameterTypes = new(FeatureName, nameof(ForLambdaParameterTypes), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineTypeHints.ForLambdaParameterTypes")); public static readonly PerLanguageOption2<bool> ForImplicitObjectCreation = new(FeatureName, nameof(ForImplicitObjectCreation), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineTypeHints.ForImplicitObjectCreation")); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; namespace Microsoft.CodeAnalysis.InlineHints { internal readonly record struct InlineTypeHintsOptions( bool EnabledForTypes, bool ForImplicitVariableTypes, bool ForLambdaParameterTypes, bool ForImplicitObjectCreation) { public static InlineTypeHintsOptions From(Project project) => From(project.Solution.Options, project.Language); public static InlineTypeHintsOptions From(OptionSet options, string language) => new( EnabledForTypes: options.GetOption(Metadata.EnabledForTypes, language), ForImplicitVariableTypes: options.GetOption(Metadata.ForImplicitVariableTypes, language), ForLambdaParameterTypes: options.GetOption(Metadata.ForLambdaParameterTypes, language), ForImplicitObjectCreation: options.GetOption(Metadata.ForImplicitObjectCreation, language)); [ExportSolutionOptionProvider, Shared] internal sealed class Metadata : IOptionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public Metadata() { } public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>( EnabledForTypes, ForImplicitVariableTypes, ForLambdaParameterTypes, ForImplicitObjectCreation); private const string FeatureName = "InlineHintsOptions"; public static readonly PerLanguageOption2<bool> EnabledForTypes = new(FeatureName, nameof(EnabledForTypes), defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineTypeHints")); public static readonly PerLanguageOption2<bool> ForImplicitVariableTypes = new(FeatureName, nameof(ForImplicitVariableTypes), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineTypeHints.ForImplicitVariableTypes")); public static readonly PerLanguageOption2<bool> ForLambdaParameterTypes = new(FeatureName, nameof(ForLambdaParameterTypes), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineTypeHints.ForLambdaParameterTypes")); public static readonly PerLanguageOption2<bool> ForImplicitObjectCreation = new(FeatureName, nameof(ForImplicitObjectCreation), defaultValue: true, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.InlineTypeHints.ForImplicitObjectCreation")); } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/EditorFeatures/VisualBasicTest/ConvertForToForEach/ConvertForToForEachTests.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.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertForToForEach Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertForToForEach Public Class ConvertForToForEachTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicConvertForToForEachCodeRefactoringProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestArray1() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestForSelected() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [|For|] i = 0 to array.Length - 1 Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestAtEndOfFor() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) For i = 0 to array.Length - 1[||] Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestBeforeFor() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [||] For i = 0 to array.Length - 1 Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingAfterFor() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) For [||]i = 0 to array.Length - 1 Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestArrayPlusStep1() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 step 1 Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingWithWrongStep() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 step 2 Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingIfReferencingNotDeclaringVariable() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) dim i as integer [||]For i = 0 to array.Length - 1 step 2 Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingWithIncorrectCondition1() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length { Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingWithIncorrectCondition2() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to GetLength(array) - 1 { Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingWithIncorrectCondition3() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 2 { Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestNotStartingAtZero() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 1 to array.Length - 1 { Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestList1() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 Console.WriteLine(list(i)) next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each {|Rename:v|} In list Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestChooseNameFromDeclarationStatement() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 dim val = list(i) Console.WriteLine(list(i)) next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each val In list Console.WriteLine(val) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestChooseNameAndTypeFromDeclarationStatement() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 dim val As Object = list(i) Console.WriteLine(list(i)) next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each val As Object In list Console.WriteLine(val) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestChooseNameFromDeclarationStatement_PreserveComments() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 ' loop comment dim val = list(i) Console.WriteLine(list(i)) next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each val In list ' loop comment Console.WriteLine(val) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestChooseNameFromDeclarationStatement_PreserveDirectives() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 #if true dim val = list(i) Console.WriteLine(list(i)) #end if next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each val In list #if true Console.WriteLine(val) #end if next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingIfVariableUsedNotForIndexing() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 Console.WriteLine(i) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingIfVariableUsedForIndexingNonCollection() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 Console.WriteLine(other(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestWarningIfCollectionWrittenTo() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 array(i) = 1 next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array {|Warning:v|} = 1 next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestDifferentIndexerAndEnumeratorType() As Task Await TestInRegularAndScriptAsync( "imports System class MyList default public readonly property Item(i as integer) as string public function GetEnumerator() as Enumerator end function public structure Enumerator public readonly property Current as object end structure end class class C sub Test(list as MyList) ' need to use 'string' here to preserve original index semantics. [||]For i = 0 to list.Length - 1 Console.WriteLine(list(i)) next end sub end class", "imports System class MyList default public readonly property Item(i as integer) as string public function GetEnumerator() as Enumerator end function public structure Enumerator public readonly property Current as object end structure end class class C sub Test(list as MyList) ' need to use 'string' here to preserve original index semantics. For Each {|Rename:v|} As String In list Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestSameIndexerAndEnumeratorType() As Task Await TestInRegularAndScriptAsync( "imports System class MyList default public readonly property Item(i as integer) as object public function GetEnumerator() as Enumerator end function public structure Enumerator public readonly property Current as object end structure end class class C sub Test(list as MyList) ' can omit type here since the type stayed the same. [||]For i = 0 to list.Count - 1 Console.WriteLine(list(i)) next end sub end class", "imports System class MyList default public readonly property Item(i as integer) as object public function GetEnumerator() as Enumerator end function public structure Enumerator public readonly property Current as object end structure end class class C sub Test(list as MyList) ' can omit type here since the type stayed the same. For Each {|Rename:v|} In list Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestTrivia() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) ' trivia 1 [||]For i = 0 to array.Length - 1 ' trivia 2 Console.WriteLine(array(i)) next ' trivia 3 end sub end class", "imports System class C sub Test(array as string()) ' trivia 1 For Each {|Rename:v|} In array ' trivia 2 Console.WriteLine(v) next ' trivia 3 end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> <WorkItem(32822, "https://github.com/dotnet/roslyn/issues/32822")> Public Async Function DoNotCrashOnInvalidCode() As Task Await TestMissingInRegularAndScriptAsync( " Class C Sub Test() Dim list = New List(Of Integer) [||]For newIndex = 0 To list.Count - 1 \' type the character '\' at the end of this line to invoke exception Next 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.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ConvertForToForEach Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertForToForEach Public Class ConvertForToForEachTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicConvertForToForEachCodeRefactoringProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestArray1() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestForSelected() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [|For|] i = 0 to array.Length - 1 Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestAtEndOfFor() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) For i = 0 to array.Length - 1[||] Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestBeforeFor() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [||] For i = 0 to array.Length - 1 Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingAfterFor() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) For [||]i = 0 to array.Length - 1 Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestArrayPlusStep1() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 step 1 Console.WriteLine(array(i)) next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingWithWrongStep() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 step 2 Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingIfReferencingNotDeclaringVariable() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) dim i as integer [||]For i = 0 to array.Length - 1 step 2 Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingWithIncorrectCondition1() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length { Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingWithIncorrectCondition2() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to GetLength(array) - 1 { Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingWithIncorrectCondition3() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 2 { Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestNotStartingAtZero() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 1 to array.Length - 1 { Console.WriteLine(array(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestList1() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 Console.WriteLine(list(i)) next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each {|Rename:v|} In list Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestChooseNameFromDeclarationStatement() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 dim val = list(i) Console.WriteLine(list(i)) next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each val In list Console.WriteLine(val) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestChooseNameAndTypeFromDeclarationStatement() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 dim val As Object = list(i) Console.WriteLine(list(i)) next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each val As Object In list Console.WriteLine(val) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestChooseNameFromDeclarationStatement_PreserveComments() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 ' loop comment dim val = list(i) Console.WriteLine(list(i)) next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each val In list ' loop comment Console.WriteLine(val) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestChooseNameFromDeclarationStatement_PreserveDirectives() As Task Await TestInRegularAndScript1Async( "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) [||]For i = 0 to list.Count - 1 #if true dim val = list(i) Console.WriteLine(list(i)) #end if next end sub end class", "imports System imports System.Collections.Generic class C sub Test(list as IList(of string)) For Each val In list #if true Console.WriteLine(val) #end if next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingIfVariableUsedNotForIndexing() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 Console.WriteLine(i) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestMissingIfVariableUsedForIndexingNonCollection() As Task Await TestMissingInRegularAndScriptAsync( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 Console.WriteLine(other(i)) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestWarningIfCollectionWrittenTo() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) [||]For i = 0 to array.Length - 1 array(i) = 1 next end sub end class", "imports System class C sub Test(array as string()) For Each {|Rename:v|} In array {|Warning:v|} = 1 next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestDifferentIndexerAndEnumeratorType() As Task Await TestInRegularAndScriptAsync( "imports System class MyList default public readonly property Item(i as integer) as string public function GetEnumerator() as Enumerator end function public structure Enumerator public readonly property Current as object end structure end class class C sub Test(list as MyList) ' need to use 'string' here to preserve original index semantics. [||]For i = 0 to list.Length - 1 Console.WriteLine(list(i)) next end sub end class", "imports System class MyList default public readonly property Item(i as integer) as string public function GetEnumerator() as Enumerator end function public structure Enumerator public readonly property Current as object end structure end class class C sub Test(list as MyList) ' need to use 'string' here to preserve original index semantics. For Each {|Rename:v|} As String In list Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestSameIndexerAndEnumeratorType() As Task Await TestInRegularAndScriptAsync( "imports System class MyList default public readonly property Item(i as integer) as object public function GetEnumerator() as Enumerator end function public structure Enumerator public readonly property Current as object end structure end class class C sub Test(list as MyList) ' can omit type here since the type stayed the same. [||]For i = 0 to list.Count - 1 Console.WriteLine(list(i)) next end sub end class", "imports System class MyList default public readonly property Item(i as integer) as object public function GetEnumerator() as Enumerator end function public structure Enumerator public readonly property Current as object end structure end class class C sub Test(list as MyList) ' can omit type here since the type stayed the same. For Each {|Rename:v|} In list Console.WriteLine(v) next end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> Public Async Function TestTrivia() As Task Await TestInRegularAndScript1Async( "imports System class C sub Test(array as string()) ' trivia 1 [||]For i = 0 to array.Length - 1 ' trivia 2 Console.WriteLine(array(i)) next ' trivia 3 end sub end class", "imports System class C sub Test(array as string()) ' trivia 1 For Each {|Rename:v|} In array ' trivia 2 Console.WriteLine(v) next ' trivia 3 end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForToForEach)> <WorkItem(32822, "https://github.com/dotnet/roslyn/issues/32822")> Public Async Function DoNotCrashOnInvalidCode() As Task Await TestMissingInRegularAndScriptAsync( " Class C Sub Test() Dim list = New List(Of Integer) [||]For newIndex = 0 To list.Count - 1 \' type the character '\' at the end of this line to invoke exception Next End Sub End Class") End Function End Class End Namespace
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.DocumentActiveContextChangedEventSource.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.Editor.Tagging; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { internal partial class TaggerEventSources { private class DocumentActiveContextChangedEventSource : AbstractWorkspaceTrackingTaggerEventSource { public DocumentActiveContextChangedEventSource(ITextBuffer subjectBuffer) : base(subjectBuffer) { } protected override void ConnectToWorkspace(Workspace workspace) => workspace.DocumentActiveContextChanged += OnDocumentActiveContextChanged; protected override void DisconnectFromWorkspace(Workspace workspace) => workspace.DocumentActiveContextChanged -= OnDocumentActiveContextChanged; private void OnDocumentActiveContextChanged(object? sender, DocumentActiveContextChangedEventArgs e) { var document = SubjectBuffer.AsTextContainer().GetOpenDocumentInCurrentContext(); if (document != null && document.Id == e.NewActiveContextDocumentId) { this.RaiseChanged(); } } } } }
// Licensed to the .NET Foundation under one or more 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.Editor.Tagging; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { internal partial class TaggerEventSources { private class DocumentActiveContextChangedEventSource : AbstractWorkspaceTrackingTaggerEventSource { public DocumentActiveContextChangedEventSource(ITextBuffer subjectBuffer) : base(subjectBuffer) { } protected override void ConnectToWorkspace(Workspace workspace) => workspace.DocumentActiveContextChanged += OnDocumentActiveContextChanged; protected override void DisconnectFromWorkspace(Workspace workspace) => workspace.DocumentActiveContextChanged -= OnDocumentActiveContextChanged; private void OnDocumentActiveContextChanged(object? sender, DocumentActiveContextChangedEventArgs e) { var document = SubjectBuffer.AsTextContainer().GetOpenDocumentInCurrentContext(); if (document != null && document.Id == e.NewActiveContextDocumentId) { this.RaiseChanged(); } } } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Compilers/VisualBasic/Portable/Lowering/Diagnostics/DiagnosticsPass_ExpressionLambdas.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class DiagnosticsPass Private ReadOnly _expressionTreePlaceholders As New HashSet(Of BoundNode)(ReferenceEqualityComparer.Instance) Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode If Me.IsInExpressionLambda Then Dim initializer As BoundObjectInitializerExpressionBase = node.InitializerOpt If initializer IsNot Nothing AndAlso initializer.Kind = BoundKind.ObjectInitializerExpression AndAlso node.ConstantValueOpt Is Nothing Then ' report an error for the cases where ExpressionLambdaRewriter is going to emit ' a call to a value type constructor with arguments, it would require creating ' a temp and calling the constructor on this temp If initializer.Type.IsValueType AndAlso node.ConstructorOpt IsNot Nothing AndAlso node.Arguments.Length > 0 Then GenerateExpressionTreeNotSupportedDiagnostic(initializer) End If End If End If Return MyBase.VisitObjectCreationExpression(node) End Function Public Overrides Function VisitUserDefinedUnaryOperator(node As BoundUserDefinedUnaryOperator) As BoundNode If Me.IsInExpressionLambda Then Dim opKind As UnaryOperatorKind = node.OperatorKind And UnaryOperatorKind.OpMask Dim isLifted As Boolean = (node.OperatorKind And UnaryOperatorKind.Lifted) <> 0 Select Case opKind Case UnaryOperatorKind.Minus, UnaryOperatorKind.Plus, UnaryOperatorKind.Not If isLifted Then Dim method As MethodSymbol = node.Call.Method If method.ReturnType.IsNullableType Then ' TODO: There is a bug in Dev11 when the resulting expression tree fails to build in ' case the binary operator is lifted, but the method has nullable return type. ' MORE: bug#18100 GenerateExpressionTreeNotSupportedDiagnostic(node) End If End If End Select End If Return MyBase.VisitUserDefinedUnaryOperator(node) End Function Public Overrides Function VisitAnonymousTypePropertyAccess(node As BoundAnonymousTypePropertyAccess) As BoundNode If Me.IsInExpressionLambda Then ' we do not allow anonymous objects which use one field to initialize another one GenerateDiagnostic(ERRID.ERR_BadAnonymousTypeForExprTree, node) End If Return MyBase.VisitAnonymousTypePropertyAccess(node) End Function Public Overrides Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression) As BoundNode ' Don't really care for declarations 'Me.VisitList(node.Declarations) Debug.Assert(node.Declarations.All(Function(d) d.Kind = BoundKind.AnonymousTypePropertyAccess)) Me.VisitList(node.Arguments) Return Nothing End Function Public Overrides Function VisitSequence(node As BoundSequence) As BoundNode If Not node.Locals.IsEmpty AndAlso Me.IsInExpressionLambda Then ' All such cases are not supported, note that some cases of invalid ' sequences are handled in DiagnosticsPass, but we still want to catch ' here those sequences created in lowering GenerateExpressionTreeNotSupportedDiagnostic(node) End If Return MyBase.VisitSequence(node) End Function Public Overrides Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundNode If Me.IsInExpressionLambda Then Dim opKind As BinaryOperatorKind = node.OperatorKind And BinaryOperatorKind.OpMask Select Case opKind Case BinaryOperatorKind.Like, BinaryOperatorKind.Concatenate 'Do Nothing Case Else If (node.OperatorKind And BinaryOperatorKind.Lifted) <> 0 Then Dim method As MethodSymbol = node.Call.Method If method.ReturnType.IsNullableType Then ' TODO: There is a bug in Dev11 when the resulting expression tree fails to build in ' case the binary operator is lifted, but the method has nullable return type. ' MORE: bug#18096 GenerateExpressionTreeNotSupportedDiagnostic(node) End If End If End Select End If Return MyBase.VisitUserDefinedBinaryOperator(node) End Function Public Overrides Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression) As BoundNode If Not Me.IsInExpressionLambda Then Return MyBase.VisitObjectInitializerExpression(node) End If Dim placeholder As BoundWithLValueExpressionPlaceholder = node.PlaceholderOpt Debug.Assert(placeholder IsNot Nothing) Me.Visit(placeholder) ' Initializers cannot reference placeholder Me._expressionTreePlaceholders.Add(placeholder) For Each initializer In node.Initializers ' Ignore assignments in object initializers, only reference the value Debug.Assert(initializer.Kind = BoundKind.AssignmentOperator) Dim assignment = DirectCast(initializer, BoundAssignmentOperator) Debug.Assert(assignment.LeftOnTheRightOpt Is Nothing) Dim propertyAccess = TryCast(assignment.Left, BoundPropertyAccess) If propertyAccess IsNot Nothing Then CheckRefReturningPropertyAccess(propertyAccess) End If Me.Visit(assignment.Right) Next Me._expressionTreePlaceholders.Remove(placeholder) Return Nothing End Function Public Overrides Function VisitWithLValueExpressionPlaceholder(node As BoundWithLValueExpressionPlaceholder) As BoundNode If Me._expressionTreePlaceholders.Contains(node) Then GenerateExpressionTreeNotSupportedDiagnostic(node) End If CheckMeAccessInWithExpression(node) Return MyBase.VisitWithLValueExpressionPlaceholder(node) End Function Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode 'COMPAT: old compiler used to allow assignments to properties ' we will continue allowing that too 'NOTE: native vbc also allows compound assignments like += but generates incorrect code. ' we are not going to support += assuming that it is not likely to be used in real scenarios. If Me.IsInExpressionLambda AndAlso Not (node.Left.Kind = BoundKind.PropertyAccess AndAlso node.LeftOnTheRightOpt Is Nothing) Then ' Do not support explicit assignments GenerateExpressionTreeNotSupportedDiagnostic(node) End If Return MyBase.VisitAssignmentOperator(node) End Function Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode Dim field As FieldSymbol = node.FieldSymbol If Not field.IsShared Then Me.Visit(node.ReceiverOpt) End If Return Nothing End Function Public Overrides Function VisitArrayCreation(node As BoundArrayCreation) As BoundNode If Me.IsInExpressionLambda Then If Not DirectCast(node.Type, ArrayTypeSymbol).IsSZArray Then Dim initializer As BoundArrayInitialization = node.InitializerOpt If initializer IsNot Nothing AndAlso Not initializer.Initializers.IsEmpty Then GenerateDiagnostic(ERRID.ERR_ExprTreeNoMultiDimArrayCreation, node) End If End If End If Return MyBase.VisitArrayCreation(node) End Function Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode If Me.IsInExpressionLambda Then Dim lambda As LambdaSymbol = node.LambdaSymbol If lambda.IsAsync OrElse lambda.IsIterator Then GenerateDiagnostic(ERRID.ERR_ResumableLambdaInExpressionTree, node) ElseIf Not node.WasCompilerGenerated AndAlso Not node.IsSingleLine Then GenerateDiagnostic(ERRID.ERR_StatementLambdaInExpressionTree, node) Else Select Case lambda.Syntax.Kind Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression GenerateDiagnostic(ERRID.ERR_StatementLambdaInExpressionTree, node) Case SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.SingleLineFunctionLambdaExpression Dim needDiagnostics As Boolean = True Dim block As BoundBlock = node.Body If block.Statements.Length = 1 OrElse (block.Statements.Length = 2 AndAlso block.Statements(1).Kind = BoundKind.ReturnStatement AndAlso DirectCast(block.Statements(1), BoundReturnStatement).ExpressionOpt Is Nothing) OrElse (block.Statements.Length = 3 AndAlso block.Statements(1).Kind = BoundKind.LabelStatement AndAlso block.Statements(2).Kind = BoundKind.ReturnStatement) Then Dim stmt = block.Statements(0) lSelect: Select Case stmt.Kind Case BoundKind.ReturnStatement If (DirectCast(stmt, BoundReturnStatement)).ExpressionOpt IsNot Nothing Then needDiagnostics = False End If Case BoundKind.ExpressionStatement, BoundKind.AddHandlerStatement, BoundKind.RemoveHandlerStatement needDiagnostics = False Case BoundKind.Block Dim innerBlock = DirectCast(stmt, BoundBlock) If innerBlock.Locals.IsEmpty AndAlso innerBlock.Statements.Length = 1 Then stmt = innerBlock.Statements(0) GoTo lSelect End If End Select End If If needDiagnostics Then GenerateDiagnostic(ERRID.ERR_StatementLambdaInExpressionTree, node) End If End Select End If End If Dim save_containingSymbol = Me._containingSymbol Me._containingSymbol = node.LambdaSymbol Me.Visit(node.Body) Me._containingSymbol = save_containingSymbol Return Nothing End Function Public Overrides Function VisitCall(node As BoundCall) As BoundNode Dim method As MethodSymbol = node.Method If Not method.IsShared Then Me.Visit(node.ReceiverOpt) End If If IsInExpressionLambda And method.ReturnsByRef Then GenerateDiagnostic(ERRID.ERR_RefReturningCallInExpressionTree, node) End If Me.VisitList(node.Arguments) Return Nothing End Function Public Overrides Function VisitPropertyAccess(node As BoundPropertyAccess) As BoundNode Dim [property] As PropertySymbol = node.PropertySymbol If Not [property].IsShared Then Me.Visit(node.ReceiverOpt) End If CheckRefReturningPropertyAccess(node) Me.VisitList(node.Arguments) Return Nothing End Function Private Sub CheckRefReturningPropertyAccess(node As BoundPropertyAccess) If IsInExpressionLambda AndAlso node.PropertySymbol.ReturnsByRef Then GenerateDiagnostic(ERRID.ERR_RefReturningCallInExpressionTree, node) End If End Sub Public Overrides Function VisitEventAccess(node As BoundEventAccess) As BoundNode Dim [event] As EventSymbol = node.EventSymbol If Not [event].IsShared Then Me.Visit(node.ReceiverOpt) End If Return Nothing End Function Private Sub VisitLambdaConversion(operand As BoundExpression, relaxationLambda As BoundLambda) Debug.Assert(operand IsNot Nothing AndAlso (operand.Kind = BoundKind.Lambda OrElse operand.Kind = BoundKind.QueryLambda)) If operand.Kind = BoundKind.Lambda AndAlso Not CheckLambdaForByRefParameters(DirectCast(operand, BoundLambda)) AndAlso relaxationLambda IsNot Nothing Then CheckLambdaForByRefParameters(relaxationLambda) End If Me.Visit(operand) End Sub Private Function CheckLambdaForByRefParameters(lambda As BoundLambda) As Boolean Debug.Assert(Me.IsInExpressionLambda) Debug.Assert(lambda IsNot Nothing) Dim hasByRefParameters As Boolean = False For Each p In lambda.LambdaSymbol.Parameters If p.IsByRef Then GenerateDiagnostic(ERRID.ERR_ByRefParamInExpressionTree, lambda) Return True End If Next Return False End Function Public Overrides Function VisitConversion(node As BoundConversion) As BoundNode Dim savedInExpressionLambda As Boolean = Me._inExpressionLambda If (node.ConversionKind And ConversionKind.ConvertedToExpressionTree) <> 0 Then Me._inExpressionLambda = True End If If Me.IsInExpressionLambda AndAlso (node.ConversionKind And ConversionKind.Lambda) <> 0 Then VisitLambdaConversion(node.Operand, DirectCast(node.ExtendedInfoOpt, BoundRelaxationLambda)?.Lambda) Else MyBase.VisitConversion(node) End If Me._inExpressionLambda = savedInExpressionLambda Return Nothing End Function Public Overrides Function VisitTryCast(node As BoundTryCast) As BoundNode Dim savedInExpressionLambda As Boolean = Me._inExpressionLambda If (node.ConversionKind And ConversionKind.ConvertedToExpressionTree) <> 0 Then Me._inExpressionLambda = True End If If Me.IsInExpressionLambda AndAlso (node.ConversionKind And ConversionKind.Lambda) <> 0 Then VisitLambdaConversion(node.Operand, node.RelaxationLambdaOpt) Else MyBase.VisitTryCast(node) End If Me._inExpressionLambda = savedInExpressionLambda Return Nothing End Function Public Overrides Function VisitDirectCast(node As BoundDirectCast) As BoundNode Dim savedInExpressionLambda As Boolean = Me._inExpressionLambda If (node.ConversionKind And ConversionKind.ConvertedToExpressionTree) <> 0 Then Me._inExpressionLambda = True End If If Me.IsInExpressionLambda AndAlso (node.ConversionKind And ConversionKind.Lambda) <> 0 Then VisitLambdaConversion(node.Operand, node.RelaxationLambdaOpt) Else MyBase.VisitDirectCast(node) End If Me._inExpressionLambda = savedInExpressionLambda Return Nothing End Function Public Overrides Function VisitLateInvocation(node As BoundLateInvocation) As BoundNode If Not Me.IsInExpressionLambda Then Return MyBase.VisitLateInvocation(node) End If GenerateDiagnostic(ERRID.ERR_ExprTreeNoLateBind, node) If node.Member.Kind <> BoundKind.LateMemberAccess Then Me.Visit(node.Member) End If Me.VisitList(node.ArgumentsOpt) Return Nothing End Function Public Overrides Function VisitLateMemberAccess(node As BoundLateMemberAccess) As BoundNode If Me.IsInExpressionLambda Then GenerateDiagnostic(ERRID.ERR_ExprTreeNoLateBind, node) End If Return MyBase.VisitLateMemberAccess(node) End Function Public Overrides Function VisitConditionalAccess(node As BoundConditionalAccess) As BoundNode If Me.IsInExpressionLambda Then GenerateDiagnostic(ERRID.ERR_NullPropagatingOpInExpressionTree, node) End If Return MyBase.VisitConditionalAccess(node) End Function Private Sub GenerateExpressionTreeNotSupportedDiagnostic(node As BoundNode) GenerateDiagnostic(ERRID.ERR_ExpressionTreeNotSupported, node) End Sub Private Sub GenerateDiagnostic(code As ERRID, node As BoundNode) Me._diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(code), node.Syntax.GetLocation())) 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 Imports System.Collections.Generic Imports System.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class DiagnosticsPass Private ReadOnly _expressionTreePlaceholders As New HashSet(Of BoundNode)(ReferenceEqualityComparer.Instance) Public Overrides Function VisitObjectCreationExpression(node As BoundObjectCreationExpression) As BoundNode If Me.IsInExpressionLambda Then Dim initializer As BoundObjectInitializerExpressionBase = node.InitializerOpt If initializer IsNot Nothing AndAlso initializer.Kind = BoundKind.ObjectInitializerExpression AndAlso node.ConstantValueOpt Is Nothing Then ' report an error for the cases where ExpressionLambdaRewriter is going to emit ' a call to a value type constructor with arguments, it would require creating ' a temp and calling the constructor on this temp If initializer.Type.IsValueType AndAlso node.ConstructorOpt IsNot Nothing AndAlso node.Arguments.Length > 0 Then GenerateExpressionTreeNotSupportedDiagnostic(initializer) End If End If End If Return MyBase.VisitObjectCreationExpression(node) End Function Public Overrides Function VisitUserDefinedUnaryOperator(node As BoundUserDefinedUnaryOperator) As BoundNode If Me.IsInExpressionLambda Then Dim opKind As UnaryOperatorKind = node.OperatorKind And UnaryOperatorKind.OpMask Dim isLifted As Boolean = (node.OperatorKind And UnaryOperatorKind.Lifted) <> 0 Select Case opKind Case UnaryOperatorKind.Minus, UnaryOperatorKind.Plus, UnaryOperatorKind.Not If isLifted Then Dim method As MethodSymbol = node.Call.Method If method.ReturnType.IsNullableType Then ' TODO: There is a bug in Dev11 when the resulting expression tree fails to build in ' case the binary operator is lifted, but the method has nullable return type. ' MORE: bug#18100 GenerateExpressionTreeNotSupportedDiagnostic(node) End If End If End Select End If Return MyBase.VisitUserDefinedUnaryOperator(node) End Function Public Overrides Function VisitAnonymousTypePropertyAccess(node As BoundAnonymousTypePropertyAccess) As BoundNode If Me.IsInExpressionLambda Then ' we do not allow anonymous objects which use one field to initialize another one GenerateDiagnostic(ERRID.ERR_BadAnonymousTypeForExprTree, node) End If Return MyBase.VisitAnonymousTypePropertyAccess(node) End Function Public Overrides Function VisitAnonymousTypeCreationExpression(node As BoundAnonymousTypeCreationExpression) As BoundNode ' Don't really care for declarations 'Me.VisitList(node.Declarations) Debug.Assert(node.Declarations.All(Function(d) d.Kind = BoundKind.AnonymousTypePropertyAccess)) Me.VisitList(node.Arguments) Return Nothing End Function Public Overrides Function VisitSequence(node As BoundSequence) As BoundNode If Not node.Locals.IsEmpty AndAlso Me.IsInExpressionLambda Then ' All such cases are not supported, note that some cases of invalid ' sequences are handled in DiagnosticsPass, but we still want to catch ' here those sequences created in lowering GenerateExpressionTreeNotSupportedDiagnostic(node) End If Return MyBase.VisitSequence(node) End Function Public Overrides Function VisitUserDefinedBinaryOperator(node As BoundUserDefinedBinaryOperator) As BoundNode If Me.IsInExpressionLambda Then Dim opKind As BinaryOperatorKind = node.OperatorKind And BinaryOperatorKind.OpMask Select Case opKind Case BinaryOperatorKind.Like, BinaryOperatorKind.Concatenate 'Do Nothing Case Else If (node.OperatorKind And BinaryOperatorKind.Lifted) <> 0 Then Dim method As MethodSymbol = node.Call.Method If method.ReturnType.IsNullableType Then ' TODO: There is a bug in Dev11 when the resulting expression tree fails to build in ' case the binary operator is lifted, but the method has nullable return type. ' MORE: bug#18096 GenerateExpressionTreeNotSupportedDiagnostic(node) End If End If End Select End If Return MyBase.VisitUserDefinedBinaryOperator(node) End Function Public Overrides Function VisitObjectInitializerExpression(node As BoundObjectInitializerExpression) As BoundNode If Not Me.IsInExpressionLambda Then Return MyBase.VisitObjectInitializerExpression(node) End If Dim placeholder As BoundWithLValueExpressionPlaceholder = node.PlaceholderOpt Debug.Assert(placeholder IsNot Nothing) Me.Visit(placeholder) ' Initializers cannot reference placeholder Me._expressionTreePlaceholders.Add(placeholder) For Each initializer In node.Initializers ' Ignore assignments in object initializers, only reference the value Debug.Assert(initializer.Kind = BoundKind.AssignmentOperator) Dim assignment = DirectCast(initializer, BoundAssignmentOperator) Debug.Assert(assignment.LeftOnTheRightOpt Is Nothing) Dim propertyAccess = TryCast(assignment.Left, BoundPropertyAccess) If propertyAccess IsNot Nothing Then CheckRefReturningPropertyAccess(propertyAccess) End If Me.Visit(assignment.Right) Next Me._expressionTreePlaceholders.Remove(placeholder) Return Nothing End Function Public Overrides Function VisitWithLValueExpressionPlaceholder(node As BoundWithLValueExpressionPlaceholder) As BoundNode If Me._expressionTreePlaceholders.Contains(node) Then GenerateExpressionTreeNotSupportedDiagnostic(node) End If CheckMeAccessInWithExpression(node) Return MyBase.VisitWithLValueExpressionPlaceholder(node) End Function Public Overrides Function VisitAssignmentOperator(node As BoundAssignmentOperator) As BoundNode 'COMPAT: old compiler used to allow assignments to properties ' we will continue allowing that too 'NOTE: native vbc also allows compound assignments like += but generates incorrect code. ' we are not going to support += assuming that it is not likely to be used in real scenarios. If Me.IsInExpressionLambda AndAlso Not (node.Left.Kind = BoundKind.PropertyAccess AndAlso node.LeftOnTheRightOpt Is Nothing) Then ' Do not support explicit assignments GenerateExpressionTreeNotSupportedDiagnostic(node) End If Return MyBase.VisitAssignmentOperator(node) End Function Public Overrides Function VisitFieldAccess(node As BoundFieldAccess) As BoundNode Dim field As FieldSymbol = node.FieldSymbol If Not field.IsShared Then Me.Visit(node.ReceiverOpt) End If Return Nothing End Function Public Overrides Function VisitArrayCreation(node As BoundArrayCreation) As BoundNode If Me.IsInExpressionLambda Then If Not DirectCast(node.Type, ArrayTypeSymbol).IsSZArray Then Dim initializer As BoundArrayInitialization = node.InitializerOpt If initializer IsNot Nothing AndAlso Not initializer.Initializers.IsEmpty Then GenerateDiagnostic(ERRID.ERR_ExprTreeNoMultiDimArrayCreation, node) End If End If End If Return MyBase.VisitArrayCreation(node) End Function Public Overrides Function VisitLambda(node As BoundLambda) As BoundNode If Me.IsInExpressionLambda Then Dim lambda As LambdaSymbol = node.LambdaSymbol If lambda.IsAsync OrElse lambda.IsIterator Then GenerateDiagnostic(ERRID.ERR_ResumableLambdaInExpressionTree, node) ElseIf Not node.WasCompilerGenerated AndAlso Not node.IsSingleLine Then GenerateDiagnostic(ERRID.ERR_StatementLambdaInExpressionTree, node) Else Select Case lambda.Syntax.Kind Case SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression GenerateDiagnostic(ERRID.ERR_StatementLambdaInExpressionTree, node) Case SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.SingleLineFunctionLambdaExpression Dim needDiagnostics As Boolean = True Dim block As BoundBlock = node.Body If block.Statements.Length = 1 OrElse (block.Statements.Length = 2 AndAlso block.Statements(1).Kind = BoundKind.ReturnStatement AndAlso DirectCast(block.Statements(1), BoundReturnStatement).ExpressionOpt Is Nothing) OrElse (block.Statements.Length = 3 AndAlso block.Statements(1).Kind = BoundKind.LabelStatement AndAlso block.Statements(2).Kind = BoundKind.ReturnStatement) Then Dim stmt = block.Statements(0) lSelect: Select Case stmt.Kind Case BoundKind.ReturnStatement If (DirectCast(stmt, BoundReturnStatement)).ExpressionOpt IsNot Nothing Then needDiagnostics = False End If Case BoundKind.ExpressionStatement, BoundKind.AddHandlerStatement, BoundKind.RemoveHandlerStatement needDiagnostics = False Case BoundKind.Block Dim innerBlock = DirectCast(stmt, BoundBlock) If innerBlock.Locals.IsEmpty AndAlso innerBlock.Statements.Length = 1 Then stmt = innerBlock.Statements(0) GoTo lSelect End If End Select End If If needDiagnostics Then GenerateDiagnostic(ERRID.ERR_StatementLambdaInExpressionTree, node) End If End Select End If End If Dim save_containingSymbol = Me._containingSymbol Me._containingSymbol = node.LambdaSymbol Me.Visit(node.Body) Me._containingSymbol = save_containingSymbol Return Nothing End Function Public Overrides Function VisitCall(node As BoundCall) As BoundNode Dim method As MethodSymbol = node.Method If Not method.IsShared Then Me.Visit(node.ReceiverOpt) End If If IsInExpressionLambda And method.ReturnsByRef Then GenerateDiagnostic(ERRID.ERR_RefReturningCallInExpressionTree, node) End If Me.VisitList(node.Arguments) Return Nothing End Function Public Overrides Function VisitPropertyAccess(node As BoundPropertyAccess) As BoundNode Dim [property] As PropertySymbol = node.PropertySymbol If Not [property].IsShared Then Me.Visit(node.ReceiverOpt) End If CheckRefReturningPropertyAccess(node) Me.VisitList(node.Arguments) Return Nothing End Function Private Sub CheckRefReturningPropertyAccess(node As BoundPropertyAccess) If IsInExpressionLambda AndAlso node.PropertySymbol.ReturnsByRef Then GenerateDiagnostic(ERRID.ERR_RefReturningCallInExpressionTree, node) End If End Sub Public Overrides Function VisitEventAccess(node As BoundEventAccess) As BoundNode Dim [event] As EventSymbol = node.EventSymbol If Not [event].IsShared Then Me.Visit(node.ReceiverOpt) End If Return Nothing End Function Private Sub VisitLambdaConversion(operand As BoundExpression, relaxationLambda As BoundLambda) Debug.Assert(operand IsNot Nothing AndAlso (operand.Kind = BoundKind.Lambda OrElse operand.Kind = BoundKind.QueryLambda)) If operand.Kind = BoundKind.Lambda AndAlso Not CheckLambdaForByRefParameters(DirectCast(operand, BoundLambda)) AndAlso relaxationLambda IsNot Nothing Then CheckLambdaForByRefParameters(relaxationLambda) End If Me.Visit(operand) End Sub Private Function CheckLambdaForByRefParameters(lambda As BoundLambda) As Boolean Debug.Assert(Me.IsInExpressionLambda) Debug.Assert(lambda IsNot Nothing) Dim hasByRefParameters As Boolean = False For Each p In lambda.LambdaSymbol.Parameters If p.IsByRef Then GenerateDiagnostic(ERRID.ERR_ByRefParamInExpressionTree, lambda) Return True End If Next Return False End Function Public Overrides Function VisitConversion(node As BoundConversion) As BoundNode Dim savedInExpressionLambda As Boolean = Me._inExpressionLambda If (node.ConversionKind And ConversionKind.ConvertedToExpressionTree) <> 0 Then Me._inExpressionLambda = True End If If Me.IsInExpressionLambda AndAlso (node.ConversionKind And ConversionKind.Lambda) <> 0 Then VisitLambdaConversion(node.Operand, DirectCast(node.ExtendedInfoOpt, BoundRelaxationLambda)?.Lambda) Else MyBase.VisitConversion(node) End If Me._inExpressionLambda = savedInExpressionLambda Return Nothing End Function Public Overrides Function VisitTryCast(node As BoundTryCast) As BoundNode Dim savedInExpressionLambda As Boolean = Me._inExpressionLambda If (node.ConversionKind And ConversionKind.ConvertedToExpressionTree) <> 0 Then Me._inExpressionLambda = True End If If Me.IsInExpressionLambda AndAlso (node.ConversionKind And ConversionKind.Lambda) <> 0 Then VisitLambdaConversion(node.Operand, node.RelaxationLambdaOpt) Else MyBase.VisitTryCast(node) End If Me._inExpressionLambda = savedInExpressionLambda Return Nothing End Function Public Overrides Function VisitDirectCast(node As BoundDirectCast) As BoundNode Dim savedInExpressionLambda As Boolean = Me._inExpressionLambda If (node.ConversionKind And ConversionKind.ConvertedToExpressionTree) <> 0 Then Me._inExpressionLambda = True End If If Me.IsInExpressionLambda AndAlso (node.ConversionKind And ConversionKind.Lambda) <> 0 Then VisitLambdaConversion(node.Operand, node.RelaxationLambdaOpt) Else MyBase.VisitDirectCast(node) End If Me._inExpressionLambda = savedInExpressionLambda Return Nothing End Function Public Overrides Function VisitLateInvocation(node As BoundLateInvocation) As BoundNode If Not Me.IsInExpressionLambda Then Return MyBase.VisitLateInvocation(node) End If GenerateDiagnostic(ERRID.ERR_ExprTreeNoLateBind, node) If node.Member.Kind <> BoundKind.LateMemberAccess Then Me.Visit(node.Member) End If Me.VisitList(node.ArgumentsOpt) Return Nothing End Function Public Overrides Function VisitLateMemberAccess(node As BoundLateMemberAccess) As BoundNode If Me.IsInExpressionLambda Then GenerateDiagnostic(ERRID.ERR_ExprTreeNoLateBind, node) End If Return MyBase.VisitLateMemberAccess(node) End Function Public Overrides Function VisitConditionalAccess(node As BoundConditionalAccess) As BoundNode If Me.IsInExpressionLambda Then GenerateDiagnostic(ERRID.ERR_NullPropagatingOpInExpressionTree, node) End If Return MyBase.VisitConditionalAccess(node) End Function Private Sub GenerateExpressionTreeNotSupportedDiagnostic(node As BoundNode) GenerateDiagnostic(ERRID.ERR_ExpressionTreeNotSupported, node) End Sub Private Sub GenerateDiagnostic(code As ERRID, node As BoundNode) Me._diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(code), node.Syntax.GetLocation())) End Sub End Class End Namespace
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/LazyInitialization.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; namespace Roslyn.Utilities { internal static class LazyInitialization { internal static T InterlockedStore<T>([NotNull] ref T? target, T value) where T : class => Interlocked.CompareExchange(ref target, value, null) ?? value; /// <summary> /// Ensure that the given target value is initialized (not null) in a thread-safe manner. /// </summary> /// <typeparam name="T">The type of the target value. Must be a reference type.</typeparam> /// <param name="target">The target to initialize.</param> /// <param name="valueFactory">A factory delegate to create a new instance of the target value. Note that this delegate may be called /// more than once by multiple threads, but only one of those values will successfully be written to the target.</param> /// <returns>The target value.</returns> public static T EnsureInitialized<T>([NotNull] ref T? target, Func<T> valueFactory) where T : class => Volatile.Read(ref target!) ?? InterlockedStore(ref target, valueFactory()); /// <summary> /// Ensure that the given target value is initialized (not null) in a thread-safe manner. /// </summary> /// <typeparam name="T">The type of the target value. Must be a reference type.</typeparam> /// <param name="target">The target to initialize.</param> /// <typeparam name="U">The type of the <paramref name="state"/> argument passed to the value factory.</typeparam> /// <param name="valueFactory">A factory delegate to create a new instance of the target value. Note that this delegate may be called /// more than once by multiple threads, but only one of those values will successfully be written to the target.</param> /// <param name="state">An argument passed to the value factory.</param> /// <returns>The target value.</returns> public static T EnsureInitialized<T, U>([NotNull] ref T? target, Func<U, T> valueFactory, U state) where T : class { return Volatile.Read(ref target!) ?? InterlockedStore(ref target, valueFactory(state)); } /// <summary> /// Ensure that the given target value is initialized in a thread-safe manner. This overload supports the /// initialization of value types, and reference type fields where <see langword="null"/> is considered an /// initialized value. /// </summary> /// <typeparam name="T">The type of the target value.</typeparam> /// <param name="target">A target value box to initialize.</param> /// <param name="valueFactory">A factory delegate to create a new instance of the target value. Note that this delegate may be called /// more than once by multiple threads, but only one of those values will successfully be written to the target.</param> /// <returns>The target value.</returns> public static T? EnsureInitialized<T>([NotNull] ref StrongBox<T?>? target, Func<T?> valueFactory) { var box = Volatile.Read(ref target!) ?? InterlockedStore(ref target, new StrongBox<T?>(valueFactory())); return box.Value; } /// <summary> /// Ensure that the given target value is initialized in a thread-safe manner. This overload supports the /// initialization of value types, and reference type fields where <see langword="null"/> is considered an /// initialized value. /// </summary> /// <typeparam name="T">The type of the target value.</typeparam> /// <param name="target">A target value box to initialize.</param> /// <typeparam name="U">The type of the <paramref name="state"/> argument passed to the value factory.</typeparam> /// <param name="valueFactory">A factory delegate to create a new instance of the target value. Note that this delegate may be called /// more than once by multiple threads, but only one of those values will successfully be written to the target.</param> /// <param name="state">An argument passed to the value factory.</param> /// <returns>The target value.</returns> public static T? EnsureInitialized<T, U>([NotNull] ref StrongBox<T?>? target, Func<U, T?> valueFactory, U state) { var box = Volatile.Read(ref target!) ?? InterlockedStore(ref target, new StrongBox<T?>(valueFactory(state))); return box.Value; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; namespace Roslyn.Utilities { internal static class LazyInitialization { internal static T InterlockedStore<T>([NotNull] ref T? target, T value) where T : class => Interlocked.CompareExchange(ref target, value, null) ?? value; /// <summary> /// Ensure that the given target value is initialized (not null) in a thread-safe manner. /// </summary> /// <typeparam name="T">The type of the target value. Must be a reference type.</typeparam> /// <param name="target">The target to initialize.</param> /// <param name="valueFactory">A factory delegate to create a new instance of the target value. Note that this delegate may be called /// more than once by multiple threads, but only one of those values will successfully be written to the target.</param> /// <returns>The target value.</returns> public static T EnsureInitialized<T>([NotNull] ref T? target, Func<T> valueFactory) where T : class => Volatile.Read(ref target!) ?? InterlockedStore(ref target, valueFactory()); /// <summary> /// Ensure that the given target value is initialized (not null) in a thread-safe manner. /// </summary> /// <typeparam name="T">The type of the target value. Must be a reference type.</typeparam> /// <param name="target">The target to initialize.</param> /// <typeparam name="U">The type of the <paramref name="state"/> argument passed to the value factory.</typeparam> /// <param name="valueFactory">A factory delegate to create a new instance of the target value. Note that this delegate may be called /// more than once by multiple threads, but only one of those values will successfully be written to the target.</param> /// <param name="state">An argument passed to the value factory.</param> /// <returns>The target value.</returns> public static T EnsureInitialized<T, U>([NotNull] ref T? target, Func<U, T> valueFactory, U state) where T : class { return Volatile.Read(ref target!) ?? InterlockedStore(ref target, valueFactory(state)); } /// <summary> /// Ensure that the given target value is initialized in a thread-safe manner. This overload supports the /// initialization of value types, and reference type fields where <see langword="null"/> is considered an /// initialized value. /// </summary> /// <typeparam name="T">The type of the target value.</typeparam> /// <param name="target">A target value box to initialize.</param> /// <param name="valueFactory">A factory delegate to create a new instance of the target value. Note that this delegate may be called /// more than once by multiple threads, but only one of those values will successfully be written to the target.</param> /// <returns>The target value.</returns> public static T? EnsureInitialized<T>([NotNull] ref StrongBox<T?>? target, Func<T?> valueFactory) { var box = Volatile.Read(ref target!) ?? InterlockedStore(ref target, new StrongBox<T?>(valueFactory())); return box.Value; } /// <summary> /// Ensure that the given target value is initialized in a thread-safe manner. This overload supports the /// initialization of value types, and reference type fields where <see langword="null"/> is considered an /// initialized value. /// </summary> /// <typeparam name="T">The type of the target value.</typeparam> /// <param name="target">A target value box to initialize.</param> /// <typeparam name="U">The type of the <paramref name="state"/> argument passed to the value factory.</typeparam> /// <param name="valueFactory">A factory delegate to create a new instance of the target value. Note that this delegate may be called /// more than once by multiple threads, but only one of those values will successfully be written to the target.</param> /// <param name="state">An argument passed to the value factory.</param> /// <returns>The target value.</returns> public static T? EnsureInitialized<T, U>([NotNull] ref StrongBox<T?>? target, Func<U, T?> valueFactory, U state) { var box = Volatile.Read(ref target!) ?? InterlockedStore(ref target, new StrongBox<T?>(valueFactory(state))); return box.Value; } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Compilers/Core/Portable/InternalUtilities/ReadOnlyUnmanagedMemoryStream.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.IO; using System.Runtime.InteropServices; namespace Microsoft.CodeAnalysis { internal sealed class ReadOnlyUnmanagedMemoryStream : Stream { private readonly object _memoryOwner; private readonly IntPtr _data; private readonly int _length; private int _position; public ReadOnlyUnmanagedMemoryStream(object memoryOwner, IntPtr data, int length) { _memoryOwner = memoryOwner; _data = data; _length = length; } public override unsafe int ReadByte() { if (_position == _length) { return -1; } return ((byte*)_data)[_position++]; } public override int Read(byte[] buffer, int offset, int count) { int bytesRead = Math.Min(count, _length - _position); Marshal.Copy(_data + _position, buffer, offset, bytesRead); _position += bytesRead; return bytesRead; } public override void Flush() { } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return false; } } public override long Length { get { return _length; } } public override long Position { get { return _position; } set { Seek(value, SeekOrigin.Begin); } } public override long Seek(long offset, SeekOrigin origin) { long target; try { switch (origin) { case SeekOrigin.Begin: target = offset; break; case SeekOrigin.Current: target = checked(offset + _position); break; case SeekOrigin.End: target = checked(offset + _length); break; default: throw new ArgumentOutOfRangeException(nameof(origin)); } } catch (OverflowException) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (target < 0 || target >= _length) { throw new ArgumentOutOfRangeException(nameof(offset)); } _position = (int)target; return target; } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Runtime.InteropServices; namespace Microsoft.CodeAnalysis { internal sealed class ReadOnlyUnmanagedMemoryStream : Stream { private readonly object _memoryOwner; private readonly IntPtr _data; private readonly int _length; private int _position; public ReadOnlyUnmanagedMemoryStream(object memoryOwner, IntPtr data, int length) { _memoryOwner = memoryOwner; _data = data; _length = length; } public override unsafe int ReadByte() { if (_position == _length) { return -1; } return ((byte*)_data)[_position++]; } public override int Read(byte[] buffer, int offset, int count) { int bytesRead = Math.Min(count, _length - _position); Marshal.Copy(_data + _position, buffer, offset, bytesRead); _position += bytesRead; return bytesRead; } public override void Flush() { } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return false; } } public override long Length { get { return _length; } } public override long Position { get { return _position; } set { Seek(value, SeekOrigin.Begin); } } public override long Seek(long offset, SeekOrigin origin) { long target; try { switch (origin) { case SeekOrigin.Begin: target = offset; break; case SeekOrigin.Current: target = checked(offset + _position); break; case SeekOrigin.End: target = checked(offset + _length); break; default: throw new ArgumentOutOfRangeException(nameof(origin)); } } catch (OverflowException) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (target < 0 || target >= _length) { throw new ArgumentOutOfRangeException(nameof(offset)); } _position = (int)target; return target; } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerManager.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Manages properties of analyzers (such as registered actions, supported diagnostics) for analyzer host's lifetime /// and executes the callbacks into the analyzers. /// /// It ensures the following for the lifetime of analyzer host: /// 1) <see cref="DiagnosticAnalyzer.Initialize(AnalysisContext)"/> is invoked only once per-analyzer. /// 2) <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> is invoked only once per-analyzer. /// 3) <see cref="CompilationStartAnalyzerAction"/> registered during Initialize are invoked only once per-compilation per-analyzer and analyzer options. /// </summary> internal partial class AnalyzerManager { // This cache stores the analyzer execution context per-analyzer (i.e. registered actions, supported descriptors, etc.). private readonly ImmutableDictionary<DiagnosticAnalyzer, AnalyzerExecutionContext> _analyzerExecutionContextMap; public AnalyzerManager(ImmutableArray<DiagnosticAnalyzer> analyzers) { _analyzerExecutionContextMap = CreateAnalyzerExecutionContextMap(analyzers); } public AnalyzerManager(DiagnosticAnalyzer analyzer) { _analyzerExecutionContextMap = CreateAnalyzerExecutionContextMap(SpecializedCollections.SingletonEnumerable(analyzer)); } private ImmutableDictionary<DiagnosticAnalyzer, AnalyzerExecutionContext> CreateAnalyzerExecutionContextMap(IEnumerable<DiagnosticAnalyzer> analyzers) { var builder = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, AnalyzerExecutionContext>(); foreach (var analyzer in analyzers) { builder.Add(analyzer, new AnalyzerExecutionContext(analyzer)); } return builder.ToImmutable(); } private AnalyzerExecutionContext GetAnalyzerExecutionContext(DiagnosticAnalyzer analyzer) => _analyzerExecutionContextMap[analyzer]; [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/26778", OftenCompletesSynchronously = true)] private async ValueTask<HostCompilationStartAnalysisScope> GetCompilationAnalysisScopeAsync( DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope sessionScope, AnalyzerExecutor analyzerExecutor) { var analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer); return await GetCompilationAnalysisScopeCoreAsync(sessionScope, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false); } [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/26778", OftenCompletesSynchronously = true)] private async ValueTask<HostCompilationStartAnalysisScope> GetCompilationAnalysisScopeCoreAsync( HostSessionStartAnalysisScope sessionScope, AnalyzerExecutor analyzerExecutor, AnalyzerExecutionContext analyzerExecutionContext) { try { return await analyzerExecutionContext.GetCompilationAnalysisScopeAsync(sessionScope, analyzerExecutor).ConfigureAwait(false); } catch (OperationCanceledException) { // Task to compute the scope was cancelled. // Clear the compilation scope for analyzer, so we can attempt a retry. analyzerExecutionContext.ClearCompilationScopeTask(); analyzerExecutor.CancellationToken.ThrowIfCancellationRequested(); return await GetCompilationAnalysisScopeCoreAsync(sessionScope, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false); } } private async Task<HostSymbolStartAnalysisScope> GetSymbolAnalysisScopeAsync( ISymbol symbol, DiagnosticAnalyzer analyzer, ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions, AnalyzerExecutor analyzerExecutor) { var analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer); return await GetSymbolAnalysisScopeCoreAsync(symbol, symbolStartActions, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false); } private async Task<HostSymbolStartAnalysisScope> GetSymbolAnalysisScopeCoreAsync( ISymbol symbol, ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions, AnalyzerExecutor analyzerExecutor, AnalyzerExecutionContext analyzerExecutionContext) { try { return await analyzerExecutionContext.GetSymbolAnalysisScopeAsync(symbol, symbolStartActions, analyzerExecutor).ConfigureAwait(false); } catch (OperationCanceledException) { // Task to compute the scope was cancelled. // Clear the symbol scope for analyzer, so we can attempt a retry. analyzerExecutionContext.ClearSymbolScopeTask(symbol); analyzerExecutor.CancellationToken.ThrowIfCancellationRequested(); return await GetSymbolAnalysisScopeCoreAsync(symbol, symbolStartActions, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false); } } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)] private async ValueTask<HostSessionStartAnalysisScope> GetSessionAnalysisScopeAsync( DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { var analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer); return await GetSessionAnalysisScopeCoreAsync(analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)] private async ValueTask<HostSessionStartAnalysisScope> GetSessionAnalysisScopeCoreAsync( AnalyzerExecutor analyzerExecutor, AnalyzerExecutionContext analyzerExecutionContext) { try { var task = analyzerExecutionContext.GetSessionAnalysisScopeAsync(analyzerExecutor); return await task.ConfigureAwait(false); } catch (OperationCanceledException) { // Task to compute the scope was cancelled. // Clear the entry in scope map for analyzer, so we can attempt a retry. analyzerExecutionContext.ClearSessionScopeTask(); analyzerExecutor.CancellationToken.ThrowIfCancellationRequested(); return await GetSessionAnalysisScopeCoreAsync(analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false); } } /// <summary> /// Get all the analyzer actions to execute for the given analyzer against a given compilation. /// The returned actions include the actions registered during <see cref="DiagnosticAnalyzer.Initialize(AnalysisContext)"/> method as well as /// the actions registered during <see cref="CompilationStartAnalyzerAction"/> for the given compilation. /// </summary> [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)] public async ValueTask<AnalyzerActions> GetAnalyzerActionsAsync(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { var sessionScope = await GetSessionAnalysisScopeAsync(analyzer, analyzerExecutor).ConfigureAwait(false); if (sessionScope.GetAnalyzerActions(analyzer).CompilationStartActionsCount > 0 && analyzerExecutor.Compilation != null) { var compilationScope = await GetCompilationAnalysisScopeAsync(analyzer, sessionScope, analyzerExecutor).ConfigureAwait(false); return compilationScope.GetAnalyzerActions(analyzer); } return sessionScope.GetAnalyzerActions(analyzer); } /// <summary> /// Get the per-symbol analyzer actions to be executed by the given analyzer. /// These are the actions registered during the various RegisterSymbolStartAction method invocations for the given symbol on different analysis contexts. /// </summary> [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)] public async ValueTask<AnalyzerActions> GetPerSymbolAnalyzerActionsAsync(ISymbol symbol, DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { var analyzerActions = await GetAnalyzerActionsAsync(analyzer, analyzerExecutor).ConfigureAwait(false); if (analyzerActions.SymbolStartActionsCount > 0) { var filteredSymbolStartActions = getFilteredActionsByKind(analyzerActions.SymbolStartActions); if (filteredSymbolStartActions.Length > 0) { var symbolScope = await GetSymbolAnalysisScopeAsync(symbol, analyzer, filteredSymbolStartActions, analyzerExecutor).ConfigureAwait(false); return symbolScope.GetAnalyzerActions(analyzer); } } return AnalyzerActions.Empty; ImmutableArray<SymbolStartAnalyzerAction> getFilteredActionsByKind(ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions) { ArrayBuilder<SymbolStartAnalyzerAction>? filteredActionsBuilderOpt = null; for (int i = 0; i < symbolStartActions.Length; i++) { var symbolStartAction = symbolStartActions[i]; if (symbolStartAction.Kind != symbol.Kind) { if (filteredActionsBuilderOpt == null) { filteredActionsBuilderOpt = ArrayBuilder<SymbolStartAnalyzerAction>.GetInstance(); filteredActionsBuilderOpt.AddRange(symbolStartActions, i); } } else if (filteredActionsBuilderOpt != null) { filteredActionsBuilderOpt.Add(symbolStartAction); } } return filteredActionsBuilderOpt != null ? filteredActionsBuilderOpt.ToImmutableAndFree() : symbolStartActions; } } /// <summary> /// Returns true if the given analyzer has enabled concurrent execution by invoking <see cref="AnalysisContext.EnableConcurrentExecution"/>. /// </summary> public async Task<bool> IsConcurrentAnalyzerAsync(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { var sessionScope = await GetSessionAnalysisScopeAsync(analyzer, analyzerExecutor).ConfigureAwait(false); return sessionScope.IsConcurrentAnalyzer(analyzer); } /// <summary> /// Returns <see cref="GeneratedCodeAnalysisFlags"/> for the given analyzer. /// If an analyzer hasn't configured generated code analysis, returns <see cref="AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags"/>. /// </summary> public async Task<GeneratedCodeAnalysisFlags> GetGeneratedCodeAnalysisFlagsAsync(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { var sessionScope = await GetSessionAnalysisScopeAsync(analyzer, analyzerExecutor).ConfigureAwait(false); return sessionScope.GetGeneratedCodeAnalysisFlags(analyzer); } private static void ForceLocalizableStringExceptions(LocalizableString localizableString, EventHandler<Exception> handler) { if (localizableString.CanThrowExceptions) { localizableString.OnException += handler; localizableString.ToString(); localizableString.OnException -= handler; } } /// <summary> /// Return <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> of given <paramref name="analyzer"/>. /// </summary> public ImmutableArray<DiagnosticDescriptor> GetSupportedDiagnosticDescriptors( DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { var analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer); return analyzerExecutionContext.GetOrComputeDiagnosticDescriptors(analyzer, analyzerExecutor); } /// <summary> /// Return <see cref="DiagnosticSuppressor.SupportedSuppressions"/> of given <paramref name="suppressor"/>. /// </summary> public ImmutableArray<SuppressionDescriptor> GetSupportedSuppressionDescriptors( DiagnosticSuppressor suppressor, AnalyzerExecutor analyzerExecutor) { var analyzerExecutionContext = GetAnalyzerExecutionContext(suppressor); return analyzerExecutionContext.GetOrComputeSuppressionDescriptors(suppressor, analyzerExecutor); } internal bool IsSupportedDiagnostic(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Func<DiagnosticAnalyzer, bool> isCompilerAnalyzer, AnalyzerExecutor analyzerExecutor) { // Avoid realizing all the descriptors for all compiler diagnostics by assuming that compiler analyzer doesn't report unsupported diagnostics. if (isCompilerAnalyzer(analyzer)) { return true; } // Get all the supported diagnostics and scan them linearly to see if the reported diagnostic is supported by the analyzer. // The linear scan is okay, given that this runs only if a diagnostic is being reported and a given analyzer is quite unlikely to have hundreds of thousands of supported diagnostics. var supportedDescriptors = GetSupportedDiagnosticDescriptors(analyzer, analyzerExecutor); foreach (var descriptor in supportedDescriptors) { if (descriptor.Id.Equals(diagnostic.Id, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } /// <summary> /// Returns true if all the diagnostics that can be produced by this analyzer are suppressed through options. /// </summary> internal bool IsDiagnosticAnalyzerSuppressed( DiagnosticAnalyzer analyzer, CompilationOptions options, Func<DiagnosticAnalyzer, bool> isCompilerAnalyzer, AnalyzerExecutor analyzerExecutor, SeverityFilter severityFilter) { if (isCompilerAnalyzer(analyzer)) { // Compiler analyzer must always be executed for compiler errors, which cannot be suppressed or filtered. return false; } var supportedDiagnostics = GetSupportedDiagnosticDescriptors(analyzer, analyzerExecutor); var diagnosticOptions = options.SpecificDiagnosticOptions; analyzerExecutor.TryGetCompilationAndAnalyzerOptions(out var compilation, out var analyzerOptions); foreach (var diag in supportedDiagnostics) { if (diag.IsNotConfigurable()) { if (diag.IsEnabledByDefault) { // Diagnostic descriptor is not configurable, so the diagnostics created through it cannot be suppressed. return false; } else { // NotConfigurable disabled diagnostic can be ignored as it is never reported. continue; } } // Is this diagnostic suppressed by default (as written by the rule author) var isSuppressed = !diag.IsEnabledByDefault; // Global editorconfig settings overrides the analyzer author // Compilation wide user settings (diagnosticOptions) from ruleset/nowarn/warnaserror overrides the analyzer author and global editorconfig settings. // Note that "/warnaserror-:DiagnosticId" adds a diagnostic option with value 'ReportDiagnostic.Default', // which should not alter 'isSuppressed'. if ((diagnosticOptions.TryGetValue(diag.Id, out var severity) || options.SyntaxTreeOptionsProvider is object && options.SyntaxTreeOptionsProvider.TryGetGlobalDiagnosticValue(diag.Id, analyzerExecutor.CancellationToken, out severity)) && severity != ReportDiagnostic.Default) { isSuppressed = severity == ReportDiagnostic.Suppress; } else { severity = isSuppressed ? ReportDiagnostic.Suppress : DiagnosticDescriptor.MapSeverityToReport(diag.DefaultSeverity); } // Is this diagnostic suppressed due to its severity if (severityFilter.Contains(severity)) { isSuppressed = true; } // Editorconfig user settings override compilation wide settings. if (isSuppressed && isEnabledWithAnalyzerConfigOptions(diag, severityFilter, compilation, analyzerOptions, analyzerExecutor.CancellationToken)) { isSuppressed = false; } if (!isSuppressed) { return false; } } if (analyzer is DiagnosticSuppressor suppressor) { foreach (var suppressionDescriptor in GetSupportedSuppressionDescriptors(suppressor, analyzerExecutor)) { if (!suppressionDescriptor.IsDisabled(options)) { return false; } } } return true; static bool isEnabledWithAnalyzerConfigOptions( DiagnosticDescriptor descriptor, SeverityFilter severityFilter, Compilation? compilation, AnalyzerOptions? analyzerOptions, CancellationToken cancellationToken) { if (compilation != null && compilation.Options.SyntaxTreeOptionsProvider is { } treeOptions) { foreach (var tree in compilation.SyntaxTrees) { // Check if diagnostic is enabled by SyntaxTree.DiagnosticOptions or Bulk configuration from AnalyzerConfigOptions. if (treeOptions.TryGetDiagnosticValue(tree, descriptor.Id, cancellationToken, out var configuredValue) || analyzerOptions.TryGetSeverityFromBulkConfiguration(tree, compilation, descriptor, cancellationToken, out configuredValue)) { if (configuredValue != ReportDiagnostic.Suppress && !severityFilter.Contains(configuredValue)) { return true; } } } } return false; } } internal static bool HasCompilerOrNotConfigurableTag(ImmutableArray<string> customTags) { foreach (var customTag in customTags) { if (customTag is WellKnownDiagnosticTags.Compiler or WellKnownDiagnosticTags.NotConfigurable) { return true; } } return false; } internal static bool HasNotConfigurableTag(ImmutableArray<string> customTags) { foreach (var customTag in customTags) { if (customTag == WellKnownDiagnosticTags.NotConfigurable) { return true; } } return false; } public bool TryProcessCompletedMemberAndGetPendingSymbolEndActionsForContainer( ISymbol containingSymbol, ISymbol processedMemberSymbol, DiagnosticAnalyzer analyzer, out (ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) containerEndActionsAndEvent) { return GetAnalyzerExecutionContext(analyzer).TryProcessCompletedMemberAndGetPendingSymbolEndActionsForContainer(containingSymbol, processedMemberSymbol, out containerEndActionsAndEvent); } public bool TryStartExecuteSymbolEndActions(ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, DiagnosticAnalyzer analyzer, SymbolDeclaredCompilationEvent symbolDeclaredEvent) { return GetAnalyzerExecutionContext(analyzer).TryStartExecuteSymbolEndActions(symbolEndActions, symbolDeclaredEvent); } public void MarkSymbolEndAnalysisPending( ISymbol symbol, DiagnosticAnalyzer analyzer, ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) { GetAnalyzerExecutionContext(analyzer).MarkSymbolEndAnalysisPending(symbol, symbolEndActions, symbolDeclaredEvent); } public void MarkSymbolEndAnalysisComplete(ISymbol symbol, DiagnosticAnalyzer analyzer) { GetAnalyzerExecutionContext(analyzer).MarkSymbolEndAnalysisComplete(symbol); } [Conditional("DEBUG")] public void VerifyAllSymbolEndActionsExecuted() { foreach (var analyzerExecutionContext in _analyzerExecutionContextMap.Values) { analyzerExecutionContext.VerifyAllSymbolEndActionsExecuted(); } } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Manages properties of analyzers (such as registered actions, supported diagnostics) for analyzer host's lifetime /// and executes the callbacks into the analyzers. /// /// It ensures the following for the lifetime of analyzer host: /// 1) <see cref="DiagnosticAnalyzer.Initialize(AnalysisContext)"/> is invoked only once per-analyzer. /// 2) <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> is invoked only once per-analyzer. /// 3) <see cref="CompilationStartAnalyzerAction"/> registered during Initialize are invoked only once per-compilation per-analyzer and analyzer options. /// </summary> internal partial class AnalyzerManager { // This cache stores the analyzer execution context per-analyzer (i.e. registered actions, supported descriptors, etc.). private readonly ImmutableDictionary<DiagnosticAnalyzer, AnalyzerExecutionContext> _analyzerExecutionContextMap; public AnalyzerManager(ImmutableArray<DiagnosticAnalyzer> analyzers) { _analyzerExecutionContextMap = CreateAnalyzerExecutionContextMap(analyzers); } public AnalyzerManager(DiagnosticAnalyzer analyzer) { _analyzerExecutionContextMap = CreateAnalyzerExecutionContextMap(SpecializedCollections.SingletonEnumerable(analyzer)); } private ImmutableDictionary<DiagnosticAnalyzer, AnalyzerExecutionContext> CreateAnalyzerExecutionContextMap(IEnumerable<DiagnosticAnalyzer> analyzers) { var builder = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, AnalyzerExecutionContext>(); foreach (var analyzer in analyzers) { builder.Add(analyzer, new AnalyzerExecutionContext(analyzer)); } return builder.ToImmutable(); } private AnalyzerExecutionContext GetAnalyzerExecutionContext(DiagnosticAnalyzer analyzer) => _analyzerExecutionContextMap[analyzer]; [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/26778", OftenCompletesSynchronously = true)] private async ValueTask<HostCompilationStartAnalysisScope> GetCompilationAnalysisScopeAsync( DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope sessionScope, AnalyzerExecutor analyzerExecutor) { var analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer); return await GetCompilationAnalysisScopeCoreAsync(sessionScope, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false); } [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/26778", OftenCompletesSynchronously = true)] private async ValueTask<HostCompilationStartAnalysisScope> GetCompilationAnalysisScopeCoreAsync( HostSessionStartAnalysisScope sessionScope, AnalyzerExecutor analyzerExecutor, AnalyzerExecutionContext analyzerExecutionContext) { try { return await analyzerExecutionContext.GetCompilationAnalysisScopeAsync(sessionScope, analyzerExecutor).ConfigureAwait(false); } catch (OperationCanceledException) { // Task to compute the scope was cancelled. // Clear the compilation scope for analyzer, so we can attempt a retry. analyzerExecutionContext.ClearCompilationScopeTask(); analyzerExecutor.CancellationToken.ThrowIfCancellationRequested(); return await GetCompilationAnalysisScopeCoreAsync(sessionScope, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false); } } private async Task<HostSymbolStartAnalysisScope> GetSymbolAnalysisScopeAsync( ISymbol symbol, DiagnosticAnalyzer analyzer, ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions, AnalyzerExecutor analyzerExecutor) { var analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer); return await GetSymbolAnalysisScopeCoreAsync(symbol, symbolStartActions, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false); } private async Task<HostSymbolStartAnalysisScope> GetSymbolAnalysisScopeCoreAsync( ISymbol symbol, ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions, AnalyzerExecutor analyzerExecutor, AnalyzerExecutionContext analyzerExecutionContext) { try { return await analyzerExecutionContext.GetSymbolAnalysisScopeAsync(symbol, symbolStartActions, analyzerExecutor).ConfigureAwait(false); } catch (OperationCanceledException) { // Task to compute the scope was cancelled. // Clear the symbol scope for analyzer, so we can attempt a retry. analyzerExecutionContext.ClearSymbolScopeTask(symbol); analyzerExecutor.CancellationToken.ThrowIfCancellationRequested(); return await GetSymbolAnalysisScopeCoreAsync(symbol, symbolStartActions, analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false); } } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)] private async ValueTask<HostSessionStartAnalysisScope> GetSessionAnalysisScopeAsync( DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { var analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer); return await GetSessionAnalysisScopeCoreAsync(analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)] private async ValueTask<HostSessionStartAnalysisScope> GetSessionAnalysisScopeCoreAsync( AnalyzerExecutor analyzerExecutor, AnalyzerExecutionContext analyzerExecutionContext) { try { var task = analyzerExecutionContext.GetSessionAnalysisScopeAsync(analyzerExecutor); return await task.ConfigureAwait(false); } catch (OperationCanceledException) { // Task to compute the scope was cancelled. // Clear the entry in scope map for analyzer, so we can attempt a retry. analyzerExecutionContext.ClearSessionScopeTask(); analyzerExecutor.CancellationToken.ThrowIfCancellationRequested(); return await GetSessionAnalysisScopeCoreAsync(analyzerExecutor, analyzerExecutionContext).ConfigureAwait(false); } } /// <summary> /// Get all the analyzer actions to execute for the given analyzer against a given compilation. /// The returned actions include the actions registered during <see cref="DiagnosticAnalyzer.Initialize(AnalysisContext)"/> method as well as /// the actions registered during <see cref="CompilationStartAnalyzerAction"/> for the given compilation. /// </summary> [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)] public async ValueTask<AnalyzerActions> GetAnalyzerActionsAsync(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { var sessionScope = await GetSessionAnalysisScopeAsync(analyzer, analyzerExecutor).ConfigureAwait(false); if (sessionScope.GetAnalyzerActions(analyzer).CompilationStartActionsCount > 0 && analyzerExecutor.Compilation != null) { var compilationScope = await GetCompilationAnalysisScopeAsync(analyzer, sessionScope, analyzerExecutor).ConfigureAwait(false); return compilationScope.GetAnalyzerActions(analyzer); } return sessionScope.GetAnalyzerActions(analyzer); } /// <summary> /// Get the per-symbol analyzer actions to be executed by the given analyzer. /// These are the actions registered during the various RegisterSymbolStartAction method invocations for the given symbol on different analysis contexts. /// </summary> [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/23582", OftenCompletesSynchronously = true)] public async ValueTask<AnalyzerActions> GetPerSymbolAnalyzerActionsAsync(ISymbol symbol, DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { var analyzerActions = await GetAnalyzerActionsAsync(analyzer, analyzerExecutor).ConfigureAwait(false); if (analyzerActions.SymbolStartActionsCount > 0) { var filteredSymbolStartActions = getFilteredActionsByKind(analyzerActions.SymbolStartActions); if (filteredSymbolStartActions.Length > 0) { var symbolScope = await GetSymbolAnalysisScopeAsync(symbol, analyzer, filteredSymbolStartActions, analyzerExecutor).ConfigureAwait(false); return symbolScope.GetAnalyzerActions(analyzer); } } return AnalyzerActions.Empty; ImmutableArray<SymbolStartAnalyzerAction> getFilteredActionsByKind(ImmutableArray<SymbolStartAnalyzerAction> symbolStartActions) { ArrayBuilder<SymbolStartAnalyzerAction>? filteredActionsBuilderOpt = null; for (int i = 0; i < symbolStartActions.Length; i++) { var symbolStartAction = symbolStartActions[i]; if (symbolStartAction.Kind != symbol.Kind) { if (filteredActionsBuilderOpt == null) { filteredActionsBuilderOpt = ArrayBuilder<SymbolStartAnalyzerAction>.GetInstance(); filteredActionsBuilderOpt.AddRange(symbolStartActions, i); } } else if (filteredActionsBuilderOpt != null) { filteredActionsBuilderOpt.Add(symbolStartAction); } } return filteredActionsBuilderOpt != null ? filteredActionsBuilderOpt.ToImmutableAndFree() : symbolStartActions; } } /// <summary> /// Returns true if the given analyzer has enabled concurrent execution by invoking <see cref="AnalysisContext.EnableConcurrentExecution"/>. /// </summary> public async Task<bool> IsConcurrentAnalyzerAsync(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { var sessionScope = await GetSessionAnalysisScopeAsync(analyzer, analyzerExecutor).ConfigureAwait(false); return sessionScope.IsConcurrentAnalyzer(analyzer); } /// <summary> /// Returns <see cref="GeneratedCodeAnalysisFlags"/> for the given analyzer. /// If an analyzer hasn't configured generated code analysis, returns <see cref="AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags"/>. /// </summary> public async Task<GeneratedCodeAnalysisFlags> GetGeneratedCodeAnalysisFlagsAsync(DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { var sessionScope = await GetSessionAnalysisScopeAsync(analyzer, analyzerExecutor).ConfigureAwait(false); return sessionScope.GetGeneratedCodeAnalysisFlags(analyzer); } private static void ForceLocalizableStringExceptions(LocalizableString localizableString, EventHandler<Exception> handler) { if (localizableString.CanThrowExceptions) { localizableString.OnException += handler; localizableString.ToString(); localizableString.OnException -= handler; } } /// <summary> /// Return <see cref="DiagnosticAnalyzer.SupportedDiagnostics"/> of given <paramref name="analyzer"/>. /// </summary> public ImmutableArray<DiagnosticDescriptor> GetSupportedDiagnosticDescriptors( DiagnosticAnalyzer analyzer, AnalyzerExecutor analyzerExecutor) { var analyzerExecutionContext = GetAnalyzerExecutionContext(analyzer); return analyzerExecutionContext.GetOrComputeDiagnosticDescriptors(analyzer, analyzerExecutor); } /// <summary> /// Return <see cref="DiagnosticSuppressor.SupportedSuppressions"/> of given <paramref name="suppressor"/>. /// </summary> public ImmutableArray<SuppressionDescriptor> GetSupportedSuppressionDescriptors( DiagnosticSuppressor suppressor, AnalyzerExecutor analyzerExecutor) { var analyzerExecutionContext = GetAnalyzerExecutionContext(suppressor); return analyzerExecutionContext.GetOrComputeSuppressionDescriptors(suppressor, analyzerExecutor); } internal bool IsSupportedDiagnostic(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Func<DiagnosticAnalyzer, bool> isCompilerAnalyzer, AnalyzerExecutor analyzerExecutor) { // Avoid realizing all the descriptors for all compiler diagnostics by assuming that compiler analyzer doesn't report unsupported diagnostics. if (isCompilerAnalyzer(analyzer)) { return true; } // Get all the supported diagnostics and scan them linearly to see if the reported diagnostic is supported by the analyzer. // The linear scan is okay, given that this runs only if a diagnostic is being reported and a given analyzer is quite unlikely to have hundreds of thousands of supported diagnostics. var supportedDescriptors = GetSupportedDiagnosticDescriptors(analyzer, analyzerExecutor); foreach (var descriptor in supportedDescriptors) { if (descriptor.Id.Equals(diagnostic.Id, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } /// <summary> /// Returns true if all the diagnostics that can be produced by this analyzer are suppressed through options. /// </summary> internal bool IsDiagnosticAnalyzerSuppressed( DiagnosticAnalyzer analyzer, CompilationOptions options, Func<DiagnosticAnalyzer, bool> isCompilerAnalyzer, AnalyzerExecutor analyzerExecutor, SeverityFilter severityFilter) { if (isCompilerAnalyzer(analyzer)) { // Compiler analyzer must always be executed for compiler errors, which cannot be suppressed or filtered. return false; } var supportedDiagnostics = GetSupportedDiagnosticDescriptors(analyzer, analyzerExecutor); var diagnosticOptions = options.SpecificDiagnosticOptions; analyzerExecutor.TryGetCompilationAndAnalyzerOptions(out var compilation, out var analyzerOptions); foreach (var diag in supportedDiagnostics) { if (diag.IsNotConfigurable()) { if (diag.IsEnabledByDefault) { // Diagnostic descriptor is not configurable, so the diagnostics created through it cannot be suppressed. return false; } else { // NotConfigurable disabled diagnostic can be ignored as it is never reported. continue; } } // Is this diagnostic suppressed by default (as written by the rule author) var isSuppressed = !diag.IsEnabledByDefault; // Global editorconfig settings overrides the analyzer author // Compilation wide user settings (diagnosticOptions) from ruleset/nowarn/warnaserror overrides the analyzer author and global editorconfig settings. // Note that "/warnaserror-:DiagnosticId" adds a diagnostic option with value 'ReportDiagnostic.Default', // which should not alter 'isSuppressed'. if ((diagnosticOptions.TryGetValue(diag.Id, out var severity) || options.SyntaxTreeOptionsProvider is object && options.SyntaxTreeOptionsProvider.TryGetGlobalDiagnosticValue(diag.Id, analyzerExecutor.CancellationToken, out severity)) && severity != ReportDiagnostic.Default) { isSuppressed = severity == ReportDiagnostic.Suppress; } else { severity = isSuppressed ? ReportDiagnostic.Suppress : DiagnosticDescriptor.MapSeverityToReport(diag.DefaultSeverity); } // Is this diagnostic suppressed due to its severity if (severityFilter.Contains(severity)) { isSuppressed = true; } // Editorconfig user settings override compilation wide settings. if (isSuppressed && isEnabledWithAnalyzerConfigOptions(diag, severityFilter, compilation, analyzerOptions, analyzerExecutor.CancellationToken)) { isSuppressed = false; } if (!isSuppressed) { return false; } } if (analyzer is DiagnosticSuppressor suppressor) { foreach (var suppressionDescriptor in GetSupportedSuppressionDescriptors(suppressor, analyzerExecutor)) { if (!suppressionDescriptor.IsDisabled(options)) { return false; } } } return true; static bool isEnabledWithAnalyzerConfigOptions( DiagnosticDescriptor descriptor, SeverityFilter severityFilter, Compilation? compilation, AnalyzerOptions? analyzerOptions, CancellationToken cancellationToken) { if (compilation != null && compilation.Options.SyntaxTreeOptionsProvider is { } treeOptions) { foreach (var tree in compilation.SyntaxTrees) { // Check if diagnostic is enabled by SyntaxTree.DiagnosticOptions or Bulk configuration from AnalyzerConfigOptions. if (treeOptions.TryGetDiagnosticValue(tree, descriptor.Id, cancellationToken, out var configuredValue) || analyzerOptions.TryGetSeverityFromBulkConfiguration(tree, compilation, descriptor, cancellationToken, out configuredValue)) { if (configuredValue != ReportDiagnostic.Suppress && !severityFilter.Contains(configuredValue)) { return true; } } } } return false; } } internal static bool HasCompilerOrNotConfigurableTag(ImmutableArray<string> customTags) { foreach (var customTag in customTags) { if (customTag is WellKnownDiagnosticTags.Compiler or WellKnownDiagnosticTags.NotConfigurable) { return true; } } return false; } internal static bool HasNotConfigurableTag(ImmutableArray<string> customTags) { foreach (var customTag in customTags) { if (customTag == WellKnownDiagnosticTags.NotConfigurable) { return true; } } return false; } public bool TryProcessCompletedMemberAndGetPendingSymbolEndActionsForContainer( ISymbol containingSymbol, ISymbol processedMemberSymbol, DiagnosticAnalyzer analyzer, out (ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) containerEndActionsAndEvent) { return GetAnalyzerExecutionContext(analyzer).TryProcessCompletedMemberAndGetPendingSymbolEndActionsForContainer(containingSymbol, processedMemberSymbol, out containerEndActionsAndEvent); } public bool TryStartExecuteSymbolEndActions(ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, DiagnosticAnalyzer analyzer, SymbolDeclaredCompilationEvent symbolDeclaredEvent) { return GetAnalyzerExecutionContext(analyzer).TryStartExecuteSymbolEndActions(symbolEndActions, symbolDeclaredEvent); } public void MarkSymbolEndAnalysisPending( ISymbol symbol, DiagnosticAnalyzer analyzer, ImmutableArray<SymbolEndAnalyzerAction> symbolEndActions, SymbolDeclaredCompilationEvent symbolDeclaredEvent) { GetAnalyzerExecutionContext(analyzer).MarkSymbolEndAnalysisPending(symbol, symbolEndActions, symbolDeclaredEvent); } public void MarkSymbolEndAnalysisComplete(ISymbol symbol, DiagnosticAnalyzer analyzer) { GetAnalyzerExecutionContext(analyzer).MarkSymbolEndAnalysisComplete(symbol); } [Conditional("DEBUG")] public void VerifyAllSymbolEndActionsExecuted() { foreach (var analyzerExecutionContext in _analyzerExecutionContextMap.Values) { analyzerExecutionContext.VerifyAllSymbolEndActionsExecuted(); } } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Compilers/Core/Portable/Symbols/IParameterSymbolInternal.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.Symbols { internal interface IParameterSymbolInternal : ISymbolInternal { } }
// Licensed to the .NET Foundation under one or more 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.Symbols { internal interface IParameterSymbolInternal : ISymbolInternal { } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/AsKeywordRecommenderTests.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.Declarations Public Class AsKeywordRecommenderTests Inherits RecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInAggregateClause1Test() VerifyRecommendationsContain(<MethodBody>Dim x = From x In {1, 2, 3} Aggregate x |</MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInAggregateClause2Test() VerifyRecommendationsContain(<MethodBody>Dim x = From x In {1, 2, 3} Aggregate x | As Type1 In collection, element2 |</MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInConst1Test() VerifyRecommendationsContain(<ClassDeclaration>Const goo |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInConst2Test() VerifyRecommendationsContain(<ClassDeclaration>Const goo As Integer = 42, bar |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInExternalMethodSub1Test() VerifyRecommendationsContain(<ClassDeclaration>Declare Sub goo Lib "goo.dll" (x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInExternalMethodSub2Test() VerifyRecommendationsContain(<ClassDeclaration>Declare Sub goo Lib "goo.dll" (x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsNotInExternalMethodSubReturnTypeTest() VerifyRecommendationsMissing(<ClassDeclaration>Declare Sub goo Lib "goo.dll" (x As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInExternalMethodFunction1Test() VerifyRecommendationsContain(<ClassDeclaration>Declare Function goo Lib "goo.dll" (x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInExternalMethodFunction2Test() VerifyRecommendationsContain(<ClassDeclaration>Declare Function goo Lib "goo.dll" (x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInExternalMethodFunctionReturnTypeTest() VerifyRecommendationsContain(<ClassDeclaration>Declare Function goo Lib "goo.dll" (x As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInDelegateSub1Test() VerifyRecommendationsContain(<ClassDeclaration>Delegate Sub goo (x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInDelegateSub2Test() VerifyRecommendationsContain(<ClassDeclaration>Delegate Sub goo (x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsNotInDelegateSubReturnTypeTest() VerifyRecommendationsMissing(<ClassDeclaration>Delegate Sub goo (x As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInDelegateFunction1Test() VerifyRecommendationsContain(<ClassDeclaration>Delegate Function goo (x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInDelegateFunction2Test() VerifyRecommendationsContain(<ClassDeclaration>Delegate Function goo (x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInDelegateFunctionReturnTypeTest() VerifyRecommendationsContain(<ClassDeclaration>Delegate Function goo (x As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInDim1Test() VerifyRecommendationsContain(<ClassDeclaration>Dim x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInDim2Test() VerifyRecommendationsContain(<ClassDeclaration>Dim x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInEnumTest() VerifyRecommendationsContain(<ClassDeclaration>Enum Goo |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInAddHandlerTest() VerifyRecommendationsContain(<ClassDeclaration> Custom Event Goo As Action AddHandler(value |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInRemoveHandlerTest() VerifyRecommendationsContain(<ClassDeclaration> Custom Event Goo As Action RemoveHandler(value |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInForLoopTest() VerifyRecommendationsContain(<MethodBody>For x |</MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInForLoopWithTypeCharacterTest() VerifyRecommendationsMissing(<MethodBody>For x% |</MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInForEachLoopTest() VerifyRecommendationsContain(<MethodBody>For Each x |</MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInFromClause1Test() VerifyRecommendationsContain(<MethodBody>Dim x = From x |</MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInFromClause2Test() VerifyRecommendationsContain(<MethodBody>Dim x = From x As Integer in collection1, y |</MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInFunctionArguments1Test() VerifyRecommendationsContain(<ClassDeclaration>Function Goo(x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInFunctionArguments2Test() VerifyRecommendationsContain(<ClassDeclaration>Function Goo(x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsNotInFunctionArgumentsWithTypeCharacterTest() VerifyRecommendationsMissing(<ClassDeclaration>Function Goo(x% |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInFunctionReturnValueTest() VerifyRecommendationsContain(<ClassDeclaration>Function Goo(x As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInFunctionLambdaArguments1Test() VerifyRecommendationsContain(<ClassDeclaration>Dim x = Function(x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInFunctionLambdaArguments2Test() VerifyRecommendationsContain(<ClassDeclaration>Dim x = Function(x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInFunctionLambdaReturnValueTest() VerifyRecommendationsContain(<ClassDeclaration>Dim x = Function(x As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInGroupJoinTest() VerifyRecommendationsContain(<ClassDeclaration>Dim x = From i In {1, 2, 3} Group Join x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInOperatorArguments1Test() VerifyRecommendationsContain(<ClassDeclaration>Public Shared Operator +(x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInOperatorArguments2Test() VerifyRecommendationsContain(<ClassDeclaration>Public Shared Operator +(x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInOperatorReturnValueTest() VerifyRecommendationsContain(<ClassDeclaration>Public Shared Operator +(x As Integer, y As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInPropertyArguments1Test() VerifyRecommendationsContain(<ClassDeclaration>Public Property Goo(x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInPropertyArguments2Test() VerifyRecommendationsContain(<ClassDeclaration>Public Property Goo(x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInPropertyTypeTest() VerifyRecommendationsContain(<ClassDeclaration>Public Property Goo(x As Integer, y As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInPropertySetArgumentTest() VerifyRecommendationsContain(<ClassDeclaration> Public Property Goo(x As Integer, y As Integer) Set(value |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInSubArguments1Test() VerifyRecommendationsContain(<ClassDeclaration>Sub Goo(x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInSubArguments2Test() VerifyRecommendationsContain(<ClassDeclaration>Sub Goo(x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsNotInSubReturnValueTest() VerifyRecommendationsMissing(<ClassDeclaration>Sub Goo(x As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInSubLambdaArguments1Test() VerifyRecommendationsContain(<ClassDeclaration>Dim x = Sub(x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInSubLambdaArguments2Test() VerifyRecommendationsContain(<ClassDeclaration>Dim x = Sub(x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsNotInSubLambdaReturnValueTest() VerifyRecommendationsMissing(<ClassDeclaration>Dim x = Sub(x As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInCatchBlockTest() VerifyRecommendationsContain(<MethodBody> Try Catch goo |</MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInEventDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>Event Goo |</ClassDeclaration>, "As") End Sub <WorkItem(543118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543118")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsAfterLetIdentifierTest() VerifyRecommendationsContain(<MethodBody>From i1 In New Integer() {4, 5} Let i2 |</MethodBody>, "As") End Sub <WorkItem(543637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543637")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInGenericTypeParameterListTest() Dim code = <File> Module Module1 Sub Goo(Of T | End Sub End Module </File> VerifyRecommendationsContain(code, "As") End Sub <WorkItem(543637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543637")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAsInGenericTypeArgumentListTest() Dim code = <File> Module Module1 Sub Goo(Of T) Goo(Of T | End Sub End Module </File> VerifyRecommendationsMissing(code, "As") End Sub <WorkItem(544192, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544192")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsAfterPropertyNameTest() Dim code = <File> Class C Public Property P | End Class </File> VerifyRecommendationsContain(code, "As") End Sub <WorkItem(544192, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544192")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAsAfterPropertyOpenParenTest() Dim code = <File> Class C Public Property P( | End Class </File> VerifyRecommendationsMissing(code, "As") End Sub <WorkItem(544192, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544192")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsAfterPropertyCloseParenTest() Dim code = <File> Class C Public Property P() | End Class </File> VerifyRecommendationsContain(code, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsAfterFunctionNameTest() VerifyRecommendationsContain(<ClassDeclaration>Function Goo |</ClassDeclaration>, "As") End Sub <WorkItem(530387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530387")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAsAfterSubNameTest() VerifyRecommendationsMissing(<ClassDeclaration>Sub Goo |</ClassDeclaration>, "As") End Sub <WorkItem(530387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530387")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAsAfterSubNameWithParensTest() VerifyRecommendationsMissing(<ClassDeclaration>Sub Goo() |</ClassDeclaration>, "As") End Sub <WorkItem(530387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530387")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAsAfterSubNameWithBodyTest() Dim code = <File> Class C Sub Goo | End Sub End Class </File> VerifyRecommendationsMissing(code, "As") End Sub <WorkItem(530387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530387")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAsAfterSubNameWithBodyAndParametersTest() Dim code = <File> Class C Sub Goo(x As String) | End Sub End Class </File> VerifyRecommendationsMissing(code, "As") End Sub <WorkItem(546659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546659")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInUsingBlockTest() VerifyRecommendationsContain(<MethodBody>Using Goo |</MethodBody>, "As") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAsAfterEolTest() VerifyRecommendationsMissing( <MethodBody> Dim Goo | </MethodBody>, "As") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAsAfterColonTest() VerifyRecommendationsMissing( <MethodBody> Dim Goo : | </MethodBody>, "As") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsAfterExplicitLineContinuationTest() VerifyRecommendationsContain( <MethodBody> Dim Goo _ | </MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsAfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <MethodBody> Dim Goo _ ' Test | </MethodBody>, "As") End Sub <WorkItem(547254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547254")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterPublicAsyncTest() VerifyRecommendationsContain(<ClassDeclaration>Public Async |</ClassDeclaration>, "As") 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.Declarations Public Class AsKeywordRecommenderTests Inherits RecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInAggregateClause1Test() VerifyRecommendationsContain(<MethodBody>Dim x = From x In {1, 2, 3} Aggregate x |</MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInAggregateClause2Test() VerifyRecommendationsContain(<MethodBody>Dim x = From x In {1, 2, 3} Aggregate x | As Type1 In collection, element2 |</MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInConst1Test() VerifyRecommendationsContain(<ClassDeclaration>Const goo |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInConst2Test() VerifyRecommendationsContain(<ClassDeclaration>Const goo As Integer = 42, bar |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInExternalMethodSub1Test() VerifyRecommendationsContain(<ClassDeclaration>Declare Sub goo Lib "goo.dll" (x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInExternalMethodSub2Test() VerifyRecommendationsContain(<ClassDeclaration>Declare Sub goo Lib "goo.dll" (x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsNotInExternalMethodSubReturnTypeTest() VerifyRecommendationsMissing(<ClassDeclaration>Declare Sub goo Lib "goo.dll" (x As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInExternalMethodFunction1Test() VerifyRecommendationsContain(<ClassDeclaration>Declare Function goo Lib "goo.dll" (x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInExternalMethodFunction2Test() VerifyRecommendationsContain(<ClassDeclaration>Declare Function goo Lib "goo.dll" (x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInExternalMethodFunctionReturnTypeTest() VerifyRecommendationsContain(<ClassDeclaration>Declare Function goo Lib "goo.dll" (x As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInDelegateSub1Test() VerifyRecommendationsContain(<ClassDeclaration>Delegate Sub goo (x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInDelegateSub2Test() VerifyRecommendationsContain(<ClassDeclaration>Delegate Sub goo (x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsNotInDelegateSubReturnTypeTest() VerifyRecommendationsMissing(<ClassDeclaration>Delegate Sub goo (x As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInDelegateFunction1Test() VerifyRecommendationsContain(<ClassDeclaration>Delegate Function goo (x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInDelegateFunction2Test() VerifyRecommendationsContain(<ClassDeclaration>Delegate Function goo (x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInDelegateFunctionReturnTypeTest() VerifyRecommendationsContain(<ClassDeclaration>Delegate Function goo (x As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInDim1Test() VerifyRecommendationsContain(<ClassDeclaration>Dim x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInDim2Test() VerifyRecommendationsContain(<ClassDeclaration>Dim x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInEnumTest() VerifyRecommendationsContain(<ClassDeclaration>Enum Goo |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInAddHandlerTest() VerifyRecommendationsContain(<ClassDeclaration> Custom Event Goo As Action AddHandler(value |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInRemoveHandlerTest() VerifyRecommendationsContain(<ClassDeclaration> Custom Event Goo As Action RemoveHandler(value |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInForLoopTest() VerifyRecommendationsContain(<MethodBody>For x |</MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInForLoopWithTypeCharacterTest() VerifyRecommendationsMissing(<MethodBody>For x% |</MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInForEachLoopTest() VerifyRecommendationsContain(<MethodBody>For Each x |</MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInFromClause1Test() VerifyRecommendationsContain(<MethodBody>Dim x = From x |</MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInFromClause2Test() VerifyRecommendationsContain(<MethodBody>Dim x = From x As Integer in collection1, y |</MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInFunctionArguments1Test() VerifyRecommendationsContain(<ClassDeclaration>Function Goo(x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInFunctionArguments2Test() VerifyRecommendationsContain(<ClassDeclaration>Function Goo(x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsNotInFunctionArgumentsWithTypeCharacterTest() VerifyRecommendationsMissing(<ClassDeclaration>Function Goo(x% |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInFunctionReturnValueTest() VerifyRecommendationsContain(<ClassDeclaration>Function Goo(x As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInFunctionLambdaArguments1Test() VerifyRecommendationsContain(<ClassDeclaration>Dim x = Function(x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInFunctionLambdaArguments2Test() VerifyRecommendationsContain(<ClassDeclaration>Dim x = Function(x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInFunctionLambdaReturnValueTest() VerifyRecommendationsContain(<ClassDeclaration>Dim x = Function(x As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInGroupJoinTest() VerifyRecommendationsContain(<ClassDeclaration>Dim x = From i In {1, 2, 3} Group Join x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInOperatorArguments1Test() VerifyRecommendationsContain(<ClassDeclaration>Public Shared Operator +(x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInOperatorArguments2Test() VerifyRecommendationsContain(<ClassDeclaration>Public Shared Operator +(x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInOperatorReturnValueTest() VerifyRecommendationsContain(<ClassDeclaration>Public Shared Operator +(x As Integer, y As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInPropertyArguments1Test() VerifyRecommendationsContain(<ClassDeclaration>Public Property Goo(x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInPropertyArguments2Test() VerifyRecommendationsContain(<ClassDeclaration>Public Property Goo(x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInPropertyTypeTest() VerifyRecommendationsContain(<ClassDeclaration>Public Property Goo(x As Integer, y As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInPropertySetArgumentTest() VerifyRecommendationsContain(<ClassDeclaration> Public Property Goo(x As Integer, y As Integer) Set(value |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInSubArguments1Test() VerifyRecommendationsContain(<ClassDeclaration>Sub Goo(x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInSubArguments2Test() VerifyRecommendationsContain(<ClassDeclaration>Sub Goo(x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsNotInSubReturnValueTest() VerifyRecommendationsMissing(<ClassDeclaration>Sub Goo(x As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInSubLambdaArguments1Test() VerifyRecommendationsContain(<ClassDeclaration>Dim x = Sub(x |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInSubLambdaArguments2Test() VerifyRecommendationsContain(<ClassDeclaration>Dim x = Sub(x As Integer, y |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsNotInSubLambdaReturnValueTest() VerifyRecommendationsMissing(<ClassDeclaration>Dim x = Sub(x As Integer) |</ClassDeclaration>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInCatchBlockTest() VerifyRecommendationsContain(<MethodBody> Try Catch goo |</MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInEventDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>Event Goo |</ClassDeclaration>, "As") End Sub <WorkItem(543118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543118")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsAfterLetIdentifierTest() VerifyRecommendationsContain(<MethodBody>From i1 In New Integer() {4, 5} Let i2 |</MethodBody>, "As") End Sub <WorkItem(543637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543637")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInGenericTypeParameterListTest() Dim code = <File> Module Module1 Sub Goo(Of T | End Sub End Module </File> VerifyRecommendationsContain(code, "As") End Sub <WorkItem(543637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543637")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAsInGenericTypeArgumentListTest() Dim code = <File> Module Module1 Sub Goo(Of T) Goo(Of T | End Sub End Module </File> VerifyRecommendationsMissing(code, "As") End Sub <WorkItem(544192, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544192")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsAfterPropertyNameTest() Dim code = <File> Class C Public Property P | End Class </File> VerifyRecommendationsContain(code, "As") End Sub <WorkItem(544192, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544192")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAsAfterPropertyOpenParenTest() Dim code = <File> Class C Public Property P( | End Class </File> VerifyRecommendationsMissing(code, "As") End Sub <WorkItem(544192, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544192")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsAfterPropertyCloseParenTest() Dim code = <File> Class C Public Property P() | End Class </File> VerifyRecommendationsContain(code, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsAfterFunctionNameTest() VerifyRecommendationsContain(<ClassDeclaration>Function Goo |</ClassDeclaration>, "As") End Sub <WorkItem(530387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530387")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAsAfterSubNameTest() VerifyRecommendationsMissing(<ClassDeclaration>Sub Goo |</ClassDeclaration>, "As") End Sub <WorkItem(530387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530387")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAsAfterSubNameWithParensTest() VerifyRecommendationsMissing(<ClassDeclaration>Sub Goo() |</ClassDeclaration>, "As") End Sub <WorkItem(530387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530387")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAsAfterSubNameWithBodyTest() Dim code = <File> Class C Sub Goo | End Sub End Class </File> VerifyRecommendationsMissing(code, "As") End Sub <WorkItem(530387, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530387")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAsAfterSubNameWithBodyAndParametersTest() Dim code = <File> Class C Sub Goo(x As String) | End Sub End Class </File> VerifyRecommendationsMissing(code, "As") End Sub <WorkItem(546659, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546659")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsInUsingBlockTest() VerifyRecommendationsContain(<MethodBody>Using Goo |</MethodBody>, "As") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAsAfterEolTest() VerifyRecommendationsMissing( <MethodBody> Dim Goo | </MethodBody>, "As") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoAsAfterColonTest() VerifyRecommendationsMissing( <MethodBody> Dim Goo : | </MethodBody>, "As") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsAfterExplicitLineContinuationTest() VerifyRecommendationsContain( <MethodBody> Dim Goo _ | </MethodBody>, "As") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AsAfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <MethodBody> Dim Goo _ ' Test | </MethodBody>, "As") End Sub <WorkItem(547254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547254")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterPublicAsyncTest() VerifyRecommendationsContain(<ClassDeclaration>Public Async |</ClassDeclaration>, "As") End Sub End Class End Namespace
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Workspaces/Core/Portable/Shared/Utilities/StreamingProgressTracker.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.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// Utility class that can be used to track the progress of an operation in a threadsafe manner. /// </summary> internal sealed class StreamingProgressTracker : IStreamingProgressTracker { private int _completedItems; private int _totalItems; private readonly Func<int, int, CancellationToken, ValueTask>? _updateAction; public StreamingProgressTracker(Func<int, int, CancellationToken, ValueTask>? updateAction = null) => _updateAction = updateAction; public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) { Interlocked.Add(ref _totalItems, count); return UpdateAsync(cancellationToken); } public ValueTask ItemsCompletedAsync(int count, CancellationToken cancellationToken) { Interlocked.Add(ref _completedItems, count); return UpdateAsync(cancellationToken); } private ValueTask UpdateAsync(CancellationToken cancellationToken) => _updateAction?.Invoke(Volatile.Read(ref _completedItems), Volatile.Read(ref _totalItems), cancellationToken) ?? default; } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Shared.Utilities { /// <summary> /// Utility class that can be used to track the progress of an operation in a threadsafe manner. /// </summary> internal sealed class StreamingProgressTracker : IStreamingProgressTracker { private int _completedItems; private int _totalItems; private readonly Func<int, int, CancellationToken, ValueTask>? _updateAction; public StreamingProgressTracker(Func<int, int, CancellationToken, ValueTask>? updateAction = null) => _updateAction = updateAction; public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken) { Interlocked.Add(ref _totalItems, count); return UpdateAsync(cancellationToken); } public ValueTask ItemsCompletedAsync(int count, CancellationToken cancellationToken) { Interlocked.Add(ref _completedItems, count); return UpdateAsync(cancellationToken); } private ValueTask UpdateAsync(CancellationToken cancellationToken) => _updateAction?.Invoke(Volatile.Read(ref _completedItems), Volatile.Read(ref _totalItems), cancellationToken) ?? default; } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Analyzers/CSharp/CodeFixes/UseIndexOrRangeOperator/CSharpUseRangeOperatorCodeFixProvider.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.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator { using static CodeFixHelpers; using static CSharpUseRangeOperatorDiagnosticAnalyzer; using static Helpers; using static SyntaxFactory; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseRangeOperator), Shared] internal class CSharpUseRangeOperatorCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseRangeOperatorCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.UseRangeOperatorDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var invocationNodes = diagnostics.Select(d => GetInvocationExpression(d, cancellationToken)) .OrderByDescending(i => i.SpanStart) .ToImmutableArray(); var syntaxGenerator = SyntaxGenerator.GetGenerator(document); await editor.ApplyExpressionLevelSemanticEditsAsync( document, invocationNodes, canReplace: (_1, _2) => true, (semanticModel, currentRoot, currentInvocation) => UpdateInvocation(semanticModel, currentRoot, currentInvocation, syntaxGenerator, cancellationToken), cancellationToken).ConfigureAwait(false); } private static SyntaxNode UpdateInvocation( SemanticModel semanticModel, SyntaxNode currentRoot, InvocationExpressionSyntax currentInvocation, SyntaxGenerator generator, CancellationToken cancellationToken) { if (semanticModel.GetOperation(currentInvocation, cancellationToken) is IInvocationOperation invocation && InfoCache.TryCreate(semanticModel.Compilation, out var infoCache) && AnalyzeInvocation(invocation, infoCache) is { } result) { var updatedNode = FixOne(result, generator); if (updatedNode != null) return currentRoot.ReplaceNode(result.Invocation, updatedNode); } return currentRoot; } private static InvocationExpressionSyntax GetInvocationExpression(Diagnostic d, CancellationToken cancellationToken) => (InvocationExpressionSyntax)d.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken); private static ExpressionSyntax FixOne(Result result, SyntaxGenerator generator) { var invocation = result.Invocation; var rangeExpression = CreateRangeExpression(result, generator); var argument = Argument(rangeExpression).WithAdditionalAnnotations(Formatter.Annotation); var arguments = SingletonSeparatedList(argument); if (result.MemberInfo.OverloadedMethodOpt == null) { var argList = invocation.ArgumentList; var argumentList = BracketedArgumentList( Token(SyntaxKind.OpenBracketToken).WithTriviaFrom(argList.OpenParenToken), arguments, Token(SyntaxKind.CloseBracketToken).WithTriviaFrom(argList.CloseParenToken)); if (invocation.Expression is MemberBindingExpressionSyntax) { // x?.Substring(...) -> x?[...] return ElementBindingExpression(argumentList); } if (invocation.Expression is IdentifierNameSyntax) { // Substring(...) -> this[...] return ElementAccessExpression(ThisExpression(), argumentList); } var expression = invocation.Expression is MemberAccessExpressionSyntax memberAccess ? memberAccess.Expression // x.Substring(...) -> x[...] : invocation.Expression; return ElementAccessExpression(expression, argumentList); } else { return invocation.ReplaceNode( invocation.ArgumentList, invocation.ArgumentList.WithArguments(arguments)); } } private static RangeExpressionSyntax CreateRangeExpression(Result result, SyntaxGenerator generator) => result.Kind switch { ResultKind.Computed => CreateComputedRange(result), ResultKind.Constant => CreateConstantRange(result, generator), _ => throw ExceptionUtilities.Unreachable, }; private static RangeExpressionSyntax CreateComputedRange(Result result) { // We have enough information now to generate `start..end`. However, this will often // not be what the user wants. For example, generating `start..expr.Length` is not as // desirable as `start..`. Similarly, `start..(expr.Length - 1)` is not as desirable as // `start..^1`. var startOperation = result.Op1; var endOperation = result.Op2; var lengthLikeProperty = result.MemberInfo.LengthLikeProperty; var instance = result.InvocationOperation.Instance; Contract.ThrowIfNull(instance); // If our start-op is actually equivalent to `expr.Length - val`, then just change our // start-op to be `val` and record that we should emit it as `^val`. var startFromEnd = IsFromEnd(lengthLikeProperty, instance, ref startOperation); var startExpr = (ExpressionSyntax)startOperation.Syntax; var endFromEnd = false; ExpressionSyntax? endExpr = null; if (endOperation is not null) { // We need to do the same for the second argument, since it's present. // Similarly, if our end-op is actually equivalent to `expr.Length - val`, then just // change our end-op to be `val` and record that we should emit it as `^val`. endFromEnd = IsFromEnd(lengthLikeProperty, instance, ref endOperation); // Check if the range goes to 'expr.Length'; if it does, we leave off // the end part of the range, i.e. `start..`. if (!IsInstanceLengthCheck(lengthLikeProperty, instance, endOperation)) endExpr = (ExpressionSyntax)endOperation.Syntax; } // If we're starting the range operation from 0, then we can just leave off the start of // the range. i.e. `..end` if (startOperation.ConstantValue.HasValue && startOperation.ConstantValue.Value is 0) { startExpr = null; } return RangeExpression( startExpr != null && startFromEnd ? IndexExpression(startExpr) : startExpr?.Parenthesize(), endExpr != null && endFromEnd ? IndexExpression(endExpr) : endExpr?.Parenthesize()); } private static RangeExpressionSyntax CreateConstantRange(Result result, SyntaxGenerator generator) { var constant1Syntax = (ExpressionSyntax)result.Op1.Syntax; // the form is s.Slice(constant1, s.Length - constant2). Want to generate // s[constant1..(constant2-constant1)] var constant1 = GetInt32Value(result.Op1); Contract.ThrowIfNull(result.Op2); var constant2 = GetInt32Value(result.Op2); var endExpr = (ExpressionSyntax)generator.LiteralExpression(constant2 - constant1); return RangeExpression( constant1Syntax, IndexExpression(endExpr)); } private static int GetInt32Value(IOperation operation) => (int)operation.ConstantValue.Value!; // Safe as we already confirmed this was an int when making the result. /// <summary> /// check if its the form: `expr.Length - value`. If so, update rangeOperation to then /// point to 'value' so that we can generate '^value'. /// </summary> private static bool IsFromEnd( IPropertySymbol lengthLikeProperty, IOperation instance, ref IOperation rangeOperation) { if (IsSubtraction(rangeOperation, out var subtraction) && IsInstanceLengthCheck(lengthLikeProperty, instance, subtraction.LeftOperand)) { rangeOperation = subtraction.RightOperand; return true; } return false; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Use_range_operator, createChangedDocument, CSharpAnalyzersResources.Use_range_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. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UseIndexOrRangeOperator { using static CodeFixHelpers; using static CSharpUseRangeOperatorDiagnosticAnalyzer; using static Helpers; using static SyntaxFactory; [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseRangeOperator), Shared] internal class CSharpUseRangeOperatorCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseRangeOperatorCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.UseRangeOperatorDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override async Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var invocationNodes = diagnostics.Select(d => GetInvocationExpression(d, cancellationToken)) .OrderByDescending(i => i.SpanStart) .ToImmutableArray(); var syntaxGenerator = SyntaxGenerator.GetGenerator(document); await editor.ApplyExpressionLevelSemanticEditsAsync( document, invocationNodes, canReplace: (_1, _2) => true, (semanticModel, currentRoot, currentInvocation) => UpdateInvocation(semanticModel, currentRoot, currentInvocation, syntaxGenerator, cancellationToken), cancellationToken).ConfigureAwait(false); } private static SyntaxNode UpdateInvocation( SemanticModel semanticModel, SyntaxNode currentRoot, InvocationExpressionSyntax currentInvocation, SyntaxGenerator generator, CancellationToken cancellationToken) { if (semanticModel.GetOperation(currentInvocation, cancellationToken) is IInvocationOperation invocation && InfoCache.TryCreate(semanticModel.Compilation, out var infoCache) && AnalyzeInvocation(invocation, infoCache) is { } result) { var updatedNode = FixOne(result, generator); if (updatedNode != null) return currentRoot.ReplaceNode(result.Invocation, updatedNode); } return currentRoot; } private static InvocationExpressionSyntax GetInvocationExpression(Diagnostic d, CancellationToken cancellationToken) => (InvocationExpressionSyntax)d.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken); private static ExpressionSyntax FixOne(Result result, SyntaxGenerator generator) { var invocation = result.Invocation; var rangeExpression = CreateRangeExpression(result, generator); var argument = Argument(rangeExpression).WithAdditionalAnnotations(Formatter.Annotation); var arguments = SingletonSeparatedList(argument); if (result.MemberInfo.OverloadedMethodOpt == null) { var argList = invocation.ArgumentList; var argumentList = BracketedArgumentList( Token(SyntaxKind.OpenBracketToken).WithTriviaFrom(argList.OpenParenToken), arguments, Token(SyntaxKind.CloseBracketToken).WithTriviaFrom(argList.CloseParenToken)); if (invocation.Expression is MemberBindingExpressionSyntax) { // x?.Substring(...) -> x?[...] return ElementBindingExpression(argumentList); } if (invocation.Expression is IdentifierNameSyntax) { // Substring(...) -> this[...] return ElementAccessExpression(ThisExpression(), argumentList); } var expression = invocation.Expression is MemberAccessExpressionSyntax memberAccess ? memberAccess.Expression // x.Substring(...) -> x[...] : invocation.Expression; return ElementAccessExpression(expression, argumentList); } else { return invocation.ReplaceNode( invocation.ArgumentList, invocation.ArgumentList.WithArguments(arguments)); } } private static RangeExpressionSyntax CreateRangeExpression(Result result, SyntaxGenerator generator) => result.Kind switch { ResultKind.Computed => CreateComputedRange(result), ResultKind.Constant => CreateConstantRange(result, generator), _ => throw ExceptionUtilities.Unreachable, }; private static RangeExpressionSyntax CreateComputedRange(Result result) { // We have enough information now to generate `start..end`. However, this will often // not be what the user wants. For example, generating `start..expr.Length` is not as // desirable as `start..`. Similarly, `start..(expr.Length - 1)` is not as desirable as // `start..^1`. var startOperation = result.Op1; var endOperation = result.Op2; var lengthLikeProperty = result.MemberInfo.LengthLikeProperty; var instance = result.InvocationOperation.Instance; Contract.ThrowIfNull(instance); // If our start-op is actually equivalent to `expr.Length - val`, then just change our // start-op to be `val` and record that we should emit it as `^val`. var startFromEnd = IsFromEnd(lengthLikeProperty, instance, ref startOperation); var startExpr = (ExpressionSyntax)startOperation.Syntax; var endFromEnd = false; ExpressionSyntax? endExpr = null; if (endOperation is not null) { // We need to do the same for the second argument, since it's present. // Similarly, if our end-op is actually equivalent to `expr.Length - val`, then just // change our end-op to be `val` and record that we should emit it as `^val`. endFromEnd = IsFromEnd(lengthLikeProperty, instance, ref endOperation); // Check if the range goes to 'expr.Length'; if it does, we leave off // the end part of the range, i.e. `start..`. if (!IsInstanceLengthCheck(lengthLikeProperty, instance, endOperation)) endExpr = (ExpressionSyntax)endOperation.Syntax; } // If we're starting the range operation from 0, then we can just leave off the start of // the range. i.e. `..end` if (startOperation.ConstantValue.HasValue && startOperation.ConstantValue.Value is 0) { startExpr = null; } return RangeExpression( startExpr != null && startFromEnd ? IndexExpression(startExpr) : startExpr?.Parenthesize(), endExpr != null && endFromEnd ? IndexExpression(endExpr) : endExpr?.Parenthesize()); } private static RangeExpressionSyntax CreateConstantRange(Result result, SyntaxGenerator generator) { var constant1Syntax = (ExpressionSyntax)result.Op1.Syntax; // the form is s.Slice(constant1, s.Length - constant2). Want to generate // s[constant1..(constant2-constant1)] var constant1 = GetInt32Value(result.Op1); Contract.ThrowIfNull(result.Op2); var constant2 = GetInt32Value(result.Op2); var endExpr = (ExpressionSyntax)generator.LiteralExpression(constant2 - constant1); return RangeExpression( constant1Syntax, IndexExpression(endExpr)); } private static int GetInt32Value(IOperation operation) => (int)operation.ConstantValue.Value!; // Safe as we already confirmed this was an int when making the result. /// <summary> /// check if its the form: `expr.Length - value`. If so, update rangeOperation to then /// point to 'value' so that we can generate '^value'. /// </summary> private static bool IsFromEnd( IPropertySymbol lengthLikeProperty, IOperation instance, ref IOperation rangeOperation) { if (IsSubtraction(rangeOperation, out var subtraction) && IsInstanceLengthCheck(lengthLikeProperty, instance, subtraction.LeftOperand)) { rangeOperation = subtraction.RightOperand; return true; } return false; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Use_range_operator, createChangedDocument, CSharpAnalyzersResources.Use_range_operator) { } } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/EditorFeatures/Core/Shared/Extensions/TextChangeExtensions.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.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class TextChangeExtensions { public static TextChangeRange ToTextChangeRange(this ITextChange textChange) => new(textChange.OldSpan.ToTextSpan(), textChange.NewLength); } }
// Licensed to the .NET Foundation under one or more 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.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class TextChangeExtensions { public static TextChangeRange ToTextChangeRange(this ITextChange textChange) => new(textChange.OldSpan.ToTextSpan(), textChange.NewLength); } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Scripting/Core/Hosting/CommandLine/ConsoleIO.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.Diagnostics; using System.IO; namespace Microsoft.CodeAnalysis.Scripting.Hosting { internal class ConsoleIO { public static readonly ConsoleIO Default = new ConsoleIO(Console.Out, Console.Error, Console.In); public TextWriter Error { get; } public TextWriter Out { get; } public TextReader In { get; } public ConsoleIO(TextWriter output, TextWriter error, TextReader input) { Debug.Assert(output != null); Debug.Assert(input != null); Out = output; Error = error; In = input; } public virtual void SetForegroundColor(ConsoleColor consoleColor) => Console.ForegroundColor = consoleColor; public virtual void ResetColor() => Console.ResetColor(); } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using System.IO; namespace Microsoft.CodeAnalysis.Scripting.Hosting { internal class ConsoleIO { public static readonly ConsoleIO Default = new ConsoleIO(Console.Out, Console.Error, Console.In); public TextWriter Error { get; } public TextWriter Out { get; } public TextReader In { get; } public ConsoleIO(TextWriter output, TextWriter error, TextReader input) { Debug.Assert(output != null); Debug.Assert(input != null); Out = output; Error = error; In = input; } public virtual void SetForegroundColor(ConsoleColor consoleColor) => Console.ForegroundColor = consoleColor; public virtual void ResetColor() => Console.ResetColor(); } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/Core/Portable/NavigationBar/NavigationBarItems/RoslynNavigationBarItem.GenerateEventHandlerItem.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; namespace Microsoft.CodeAnalysis.NavigationBar { internal abstract partial class RoslynNavigationBarItem { public class GenerateEventHandler : AbstractGenerateCodeItem, IEquatable<GenerateEventHandler> { public readonly string ContainerName; public readonly SymbolKey EventSymbolKey; public GenerateEventHandler(string text, Glyph glyph, string containerName, SymbolKey eventSymbolKey, SymbolKey destinationTypeSymbolKey) : base(RoslynNavigationBarItemKind.GenerateEventHandler, text, glyph, destinationTypeSymbolKey) { ContainerName = containerName; EventSymbolKey = eventSymbolKey; } protected internal override SerializableNavigationBarItem Dehydrate() => SerializableNavigationBarItem.GenerateEventHandler(Text, Glyph, ContainerName, EventSymbolKey, DestinationTypeSymbolKey); public override bool Equals(object? obj) => Equals(obj as GenerateEventHandler); public bool Equals(GenerateEventHandler? other) => base.Equals(other) && ContainerName == other.ContainerName && EventSymbolKey.Equals(other.EventSymbolKey); public override int GetHashCode() => throw new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.NavigationBar { internal abstract partial class RoslynNavigationBarItem { public class GenerateEventHandler : AbstractGenerateCodeItem, IEquatable<GenerateEventHandler> { public readonly string ContainerName; public readonly SymbolKey EventSymbolKey; public GenerateEventHandler(string text, Glyph glyph, string containerName, SymbolKey eventSymbolKey, SymbolKey destinationTypeSymbolKey) : base(RoslynNavigationBarItemKind.GenerateEventHandler, text, glyph, destinationTypeSymbolKey) { ContainerName = containerName; EventSymbolKey = eventSymbolKey; } protected internal override SerializableNavigationBarItem Dehydrate() => SerializableNavigationBarItem.GenerateEventHandler(Text, Glyph, ContainerName, EventSymbolKey, DestinationTypeSymbolKey); public override bool Equals(object? obj) => Equals(obj as GenerateEventHandler); public bool Equals(GenerateEventHandler? other) => base.Equals(other) && ContainerName == other.ContainerName && EventSymbolKey.Equals(other.EventSymbolKey); public override int GetHashCode() => throw new NotImplementedException(); } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/SByteKeywordRecommender.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; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class SByteKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public SByteKeywordRecommender() : base(SyntaxKind.SByteKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsNonAttributeExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsEnumBaseListContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsLocalFunctionDeclarationContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsPrimaryFunctionExpressionContext || context.IsCrefContext || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsPossibleTupleContext || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } protected override SpecialType SpecialType => SpecialType.System_SByte; } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class SByteKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public SByteKeywordRecommender() : base(SyntaxKind.SByteKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsNonAttributeExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsEnumBaseListContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsLocalFunctionDeclarationContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsPrimaryFunctionExpressionContext || context.IsCrefContext || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsPossibleTupleContext || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } protected override SpecialType SpecialType => SpecialType.System_SByte; } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Compilers/Core/CommandLine/BuildProtocol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using static Microsoft.CodeAnalysis.CommandLine.BuildProtocolConstants; using static Microsoft.CodeAnalysis.CommandLine.CompilerServerLogger; // This file describes data structures about the protocol from client program to server that is // used. The basic protocol is this. // // After the server pipe is connected, it forks off a thread to handle the connection, and creates // a new instance of the pipe to listen for new clients. When it gets a request, it validates // the security and elevation level of the client. If that fails, it disconnects the client. Otherwise, // it handles the request, sends a response (described by Response class) back to the client, then // disconnects the pipe and ends the thread. namespace Microsoft.CodeAnalysis.CommandLine { /// <summary> /// Represents a request from the client. A request is as follows. /// /// Field Name Type Size (bytes) /// ---------------------------------------------------- /// Length Integer 4 /// RequestId Guid 16 /// Language RequestLanguage 4 /// CompilerHash String Variable /// Argument Count UInteger 4 /// Arguments Argument[] Variable /// /// See <see cref="Argument"/> for the format of an /// Argument. /// /// </summary> internal sealed class BuildRequest { /// <summary> /// The maximum size of a request supported by the compiler server. /// </summary> /// <remarks> /// Currently this limit is 5MB. /// </remarks> private const int MaximumRequestSize = 0x500000; public readonly Guid RequestId; public readonly RequestLanguage Language; public readonly ReadOnlyCollection<Argument> Arguments; public readonly string CompilerHash; public BuildRequest(RequestLanguage language, string compilerHash, IEnumerable<Argument> arguments, Guid? requestId = null) { RequestId = requestId ?? Guid.Empty; Language = language; Arguments = new ReadOnlyCollection<Argument>(arguments.ToList()); CompilerHash = compilerHash; Debug.Assert(!string.IsNullOrWhiteSpace(CompilerHash), "A hash value is required to communicate with the server"); } public static BuildRequest Create(RequestLanguage language, IList<string> args, string workingDirectory, string tempDirectory, string compilerHash, Guid? requestId = null, string? keepAlive = null, string? libDirectory = null) { Debug.Assert(!string.IsNullOrWhiteSpace(compilerHash), "CompilerHash is required to send request to the build server"); var requestLength = args.Count + 1 + (libDirectory == null ? 0 : 1); var requestArgs = new List<Argument>(requestLength); requestArgs.Add(new Argument(ArgumentId.CurrentDirectory, 0, workingDirectory)); requestArgs.Add(new Argument(ArgumentId.TempDirectory, 0, tempDirectory)); if (keepAlive != null) { requestArgs.Add(new Argument(ArgumentId.KeepAlive, 0, keepAlive)); } if (libDirectory != null) { requestArgs.Add(new Argument(ArgumentId.LibEnvVariable, 0, libDirectory)); } for (int i = 0; i < args.Count; ++i) { var arg = args[i]; requestArgs.Add(new Argument(ArgumentId.CommandLineArgument, i, arg)); } return new BuildRequest(language, compilerHash, requestArgs, requestId); } public static BuildRequest CreateShutdown() { var requestArgs = new[] { new Argument(ArgumentId.Shutdown, argumentIndex: 0, value: "") }; return new BuildRequest(RequestLanguage.CSharpCompile, GetCommitHash() ?? "", requestArgs); } /// <summary> /// Read a Request from the given stream. /// /// The total request size must be less than <see cref="MaximumRequestSize"/>. /// </summary> /// <returns>null if the Request was too large, the Request otherwise.</returns> public static async Task<BuildRequest> ReadAsync(Stream inStream, CancellationToken cancellationToken) { // Read the length of the request var lengthBuffer = new byte[4]; await ReadAllAsync(inStream, lengthBuffer, 4, cancellationToken).ConfigureAwait(false); var length = BitConverter.ToInt32(lengthBuffer, 0); // Back out if the request is too large if (length > MaximumRequestSize) { throw new ArgumentException($"Request is over {MaximumRequestSize >> 20}MB in length"); } cancellationToken.ThrowIfCancellationRequested(); // Read the full request var requestBuffer = new byte[length]; await ReadAllAsync(inStream, requestBuffer, length, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); // Parse the request into the Request data structure. using var reader = new BinaryReader(new MemoryStream(requestBuffer), Encoding.Unicode); var requestId = readGuid(reader); var language = (RequestLanguage)reader.ReadUInt32(); var compilerHash = reader.ReadString(); uint argumentCount = reader.ReadUInt32(); var argumentsBuilder = new List<Argument>((int)argumentCount); for (int i = 0; i < argumentCount; i++) { cancellationToken.ThrowIfCancellationRequested(); argumentsBuilder.Add(BuildRequest.Argument.ReadFromBinaryReader(reader)); } return new BuildRequest(language, compilerHash, argumentsBuilder, requestId); static Guid readGuid(BinaryReader reader) { const int size = 16; var bytes = new byte[size]; if (size != reader.Read(bytes, 0, size)) { throw new InvalidOperationException(); } return new Guid(bytes); } } /// <summary> /// Write a Request to the stream. /// </summary> public async Task WriteAsync(Stream outStream, CancellationToken cancellationToken = default(CancellationToken)) { using var memoryStream = new MemoryStream(); using var writer = new BinaryWriter(memoryStream, Encoding.Unicode); writer.Write(RequestId.ToByteArray()); writer.Write((uint)Language); writer.Write(CompilerHash); writer.Write(Arguments.Count); foreach (Argument arg in Arguments) { cancellationToken.ThrowIfCancellationRequested(); arg.WriteToBinaryWriter(writer); } writer.Flush(); cancellationToken.ThrowIfCancellationRequested(); // Write the length of the request int length = checked((int)memoryStream.Length); // Back out if the request is too large if (memoryStream.Length > MaximumRequestSize) { throw new ArgumentOutOfRangeException($"Request is over {MaximumRequestSize >> 20}MB in length"); } await outStream.WriteAsync(BitConverter.GetBytes(length), 0, 4, cancellationToken).ConfigureAwait(false); memoryStream.Position = 0; await memoryStream.CopyToAsync(outStream, bufferSize: length, cancellationToken: cancellationToken).ConfigureAwait(false); } /// <summary> /// A command line argument to the compilation. /// An argument is formatted as follows: /// /// Field Name Type Size (bytes) /// -------------------------------------------------- /// ID UInteger 4 /// Index UInteger 4 /// Value String Variable /// /// Strings are encoded via a length prefix as a signed /// 32-bit integer, followed by an array of characters. /// </summary> public readonly struct Argument { public readonly ArgumentId ArgumentId; public readonly int ArgumentIndex; public readonly string? Value; public Argument(ArgumentId argumentId, int argumentIndex, string? value) { ArgumentId = argumentId; ArgumentIndex = argumentIndex; Value = value; } public static Argument ReadFromBinaryReader(BinaryReader reader) { var argId = (ArgumentId)reader.ReadInt32(); var argIndex = reader.ReadInt32(); string? value = ReadLengthPrefixedString(reader); return new Argument(argId, argIndex, value); } public void WriteToBinaryWriter(BinaryWriter writer) { writer.Write((int)ArgumentId); writer.Write(ArgumentIndex); WriteLengthPrefixedString(writer, Value); } } } /// <summary> /// Base class for all possible responses to a request. /// The ResponseType enum should list all possible response types /// and ReadResponse creates the appropriate response subclass based /// on the response type sent by the client. /// The format of a response is: /// /// Field Name Field Type Size (bytes) /// ------------------------------------------------- /// responseLength int (positive) 4 /// responseType enum ResponseType 4 /// responseBody Response subclass variable /// </summary> internal abstract class BuildResponse { public enum ResponseType { // The client and server are using incompatible protocol versions. MismatchedVersion, // The build request completed on the server and the results are contained // in the message. Completed, // The build request could not be run on the server due because it created // an unresolvable inconsistency with analyzers. AnalyzerInconsistency, // The shutdown request completed and the server process information is // contained in the message. Shutdown, // The request was rejected by the server. Rejected, // The server hash did not match the one supplied by the client IncorrectHash, } public abstract ResponseType Type { get; } public async Task WriteAsync(Stream outStream, CancellationToken cancellationToken) { using (var memoryStream = new MemoryStream()) using (var writer = new BinaryWriter(memoryStream, Encoding.Unicode)) { writer.Write((int)Type); AddResponseBody(writer); writer.Flush(); cancellationToken.ThrowIfCancellationRequested(); // Send the response to the client // Write the length of the response int length = checked((int)memoryStream.Length); // There is no way to know the number of bytes written to // the pipe stream. We just have to assume all of them are written. await outStream.WriteAsync(BitConverter.GetBytes(length), 0, 4, cancellationToken).ConfigureAwait(false); memoryStream.Position = 0; await memoryStream.CopyToAsync(outStream, bufferSize: length, cancellationToken: cancellationToken).ConfigureAwait(false); } } protected abstract void AddResponseBody(BinaryWriter writer); /// <summary> /// May throw exceptions if there are pipe problems. /// </summary> /// <param name="stream"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public static async Task<BuildResponse> ReadAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { // Read the response length var lengthBuffer = new byte[4]; await ReadAllAsync(stream, lengthBuffer, 4, cancellationToken).ConfigureAwait(false); var length = BitConverter.ToUInt32(lengthBuffer, 0); // Read the response var responseBuffer = new byte[length]; await ReadAllAsync(stream, responseBuffer, responseBuffer.Length, cancellationToken).ConfigureAwait(false); using (var reader = new BinaryReader(new MemoryStream(responseBuffer), Encoding.Unicode)) { var responseType = (ResponseType)reader.ReadInt32(); switch (responseType) { case ResponseType.Completed: return CompletedBuildResponse.Create(reader); case ResponseType.MismatchedVersion: return new MismatchedVersionBuildResponse(); case ResponseType.IncorrectHash: return new IncorrectHashBuildResponse(); case ResponseType.AnalyzerInconsistency: return AnalyzerInconsistencyBuildResponse.Create(reader); case ResponseType.Shutdown: return ShutdownBuildResponse.Create(reader); case ResponseType.Rejected: return RejectedBuildResponse.Create(reader); default: throw new InvalidOperationException("Received invalid response type from server."); } } } } /// <summary> /// Represents a Response from the server. A response is as follows. /// /// Field Name Type Size (bytes) /// -------------------------------------------------- /// Length UInteger 4 /// ReturnCode Integer 4 /// Output String Variable /// /// Strings are encoded via a character count prefix as a /// 32-bit integer, followed by an array of characters. /// /// </summary> internal sealed class CompletedBuildResponse : BuildResponse { public readonly int ReturnCode; public readonly bool Utf8Output; public readonly string Output; public CompletedBuildResponse(int returnCode, bool utf8output, string? output) { ReturnCode = returnCode; Utf8Output = utf8output; Output = output ?? string.Empty; } public override ResponseType Type => ResponseType.Completed; public static CompletedBuildResponse Create(BinaryReader reader) { var returnCode = reader.ReadInt32(); var utf8Output = reader.ReadBoolean(); var output = ReadLengthPrefixedString(reader); return new CompletedBuildResponse(returnCode, utf8Output, output); } protected override void AddResponseBody(BinaryWriter writer) { writer.Write(ReturnCode); writer.Write(Utf8Output); WriteLengthPrefixedString(writer, Output); } } internal sealed class ShutdownBuildResponse : BuildResponse { public readonly int ServerProcessId; public ShutdownBuildResponse(int serverProcessId) { ServerProcessId = serverProcessId; } public override ResponseType Type => ResponseType.Shutdown; protected override void AddResponseBody(BinaryWriter writer) { writer.Write(ServerProcessId); } public static ShutdownBuildResponse Create(BinaryReader reader) { var serverProcessId = reader.ReadInt32(); return new ShutdownBuildResponse(serverProcessId); } } internal sealed class MismatchedVersionBuildResponse : BuildResponse { public override ResponseType Type => ResponseType.MismatchedVersion; /// <summary> /// MismatchedVersion has no body. /// </summary> protected override void AddResponseBody(BinaryWriter writer) { } } internal sealed class IncorrectHashBuildResponse : BuildResponse { public override ResponseType Type => ResponseType.IncorrectHash; /// <summary> /// IncorrectHash has no body. /// </summary> protected override void AddResponseBody(BinaryWriter writer) { } } internal sealed class AnalyzerInconsistencyBuildResponse : BuildResponse { public override ResponseType Type => ResponseType.AnalyzerInconsistency; public ReadOnlyCollection<string> ErrorMessages { get; } public AnalyzerInconsistencyBuildResponse(ReadOnlyCollection<string> errorMessages) { ErrorMessages = errorMessages; } protected override void AddResponseBody(BinaryWriter writer) { writer.Write(ErrorMessages.Count); foreach (var message in ErrorMessages) { WriteLengthPrefixedString(writer, message); } } public static AnalyzerInconsistencyBuildResponse Create(BinaryReader reader) { var count = reader.ReadInt32(); var list = new List<string>(count); for (var i = 0; i < count; i++) { list.Add(ReadLengthPrefixedString(reader) ?? ""); } return new AnalyzerInconsistencyBuildResponse(new ReadOnlyCollection<string>(list)); } } internal sealed class RejectedBuildResponse : BuildResponse { public string Reason; public override ResponseType Type => ResponseType.Rejected; public RejectedBuildResponse(string reason) { Reason = reason; } protected override void AddResponseBody(BinaryWriter writer) { WriteLengthPrefixedString(writer, Reason); } public static RejectedBuildResponse Create(BinaryReader reader) { var reason = ReadLengthPrefixedString(reader); Debug.Assert(reason is object); return new RejectedBuildResponse(reason); } } // The id numbers below are just random. It's useful to use id numbers // that won't occur accidentally for debugging. internal enum RequestLanguage { CSharpCompile = 0x44532521, VisualBasicCompile = 0x44532522, } /// <summary> /// Constants about the protocol. /// </summary> internal static class BuildProtocolConstants { // Arguments for CSharp and VB Compiler public enum ArgumentId { // The current directory of the client CurrentDirectory = 0x51147221, // A comment line argument. The argument index indicates which one (0 .. N) CommandLineArgument, // The "LIB" environment variable of the client LibEnvVariable, // Request a longer keep alive time for the server KeepAlive, // Request a server shutdown from the client Shutdown, // The directory to use for temporary operations. TempDirectory, } /// <summary> /// Read a string from the Reader where the string is encoded /// as a length prefix (signed 32-bit integer) followed by /// a sequence of characters. /// </summary> public static string? ReadLengthPrefixedString(BinaryReader reader) { var length = reader.ReadInt32(); if (length < 0) { return null; } return new String(reader.ReadChars(length)); } /// <summary> /// Write a string to the Writer where the string is encoded /// as a length prefix (signed 32-bit integer) follows by /// a sequence of characters. /// </summary> public static void WriteLengthPrefixedString(BinaryWriter writer, string? value) { if (value is object) { writer.Write(value.Length); writer.Write(value.ToCharArray()); } else { writer.Write(-1); } } /// <summary> /// Reads the value of <see cref="CommitHashAttribute.Hash"/> of the assembly <see cref="BuildRequest"/> is defined in /// </summary> /// <returns>The hash value of the current assembly or an empty string</returns> public static string? GetCommitHash() { var hashAttributes = typeof(BuildRequest).Assembly.GetCustomAttributes<CommitHashAttribute>(); var hashAttributeCount = hashAttributes.Count(); if (hashAttributeCount != 1) { return null; } return hashAttributes.Single().Hash; } /// <summary> /// This task does not complete until we are completely done reading. /// </summary> internal static async Task ReadAllAsync( Stream stream, byte[] buffer, int count, CancellationToken cancellationToken) { int totalBytesRead = 0; do { int bytesRead = await stream.ReadAsync(buffer, totalBytesRead, count - totalBytesRead, cancellationToken).ConfigureAwait(false); if (bytesRead == 0) { throw new EndOfStreamException("Reached end of stream before end of read."); } totalBytesRead += bytesRead; } while (totalBytesRead < count); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using static Microsoft.CodeAnalysis.CommandLine.BuildProtocolConstants; using static Microsoft.CodeAnalysis.CommandLine.CompilerServerLogger; // This file describes data structures about the protocol from client program to server that is // used. The basic protocol is this. // // After the server pipe is connected, it forks off a thread to handle the connection, and creates // a new instance of the pipe to listen for new clients. When it gets a request, it validates // the security and elevation level of the client. If that fails, it disconnects the client. Otherwise, // it handles the request, sends a response (described by Response class) back to the client, then // disconnects the pipe and ends the thread. namespace Microsoft.CodeAnalysis.CommandLine { /// <summary> /// Represents a request from the client. A request is as follows. /// /// Field Name Type Size (bytes) /// ---------------------------------------------------- /// Length Integer 4 /// RequestId Guid 16 /// Language RequestLanguage 4 /// CompilerHash String Variable /// Argument Count UInteger 4 /// Arguments Argument[] Variable /// /// See <see cref="Argument"/> for the format of an /// Argument. /// /// </summary> internal sealed class BuildRequest { /// <summary> /// The maximum size of a request supported by the compiler server. /// </summary> /// <remarks> /// Currently this limit is 5MB. /// </remarks> private const int MaximumRequestSize = 0x500000; public readonly Guid RequestId; public readonly RequestLanguage Language; public readonly ReadOnlyCollection<Argument> Arguments; public readonly string CompilerHash; public BuildRequest(RequestLanguage language, string compilerHash, IEnumerable<Argument> arguments, Guid? requestId = null) { RequestId = requestId ?? Guid.Empty; Language = language; Arguments = new ReadOnlyCollection<Argument>(arguments.ToList()); CompilerHash = compilerHash; Debug.Assert(!string.IsNullOrWhiteSpace(CompilerHash), "A hash value is required to communicate with the server"); } public static BuildRequest Create(RequestLanguage language, IList<string> args, string workingDirectory, string tempDirectory, string compilerHash, Guid? requestId = null, string? keepAlive = null, string? libDirectory = null) { Debug.Assert(!string.IsNullOrWhiteSpace(compilerHash), "CompilerHash is required to send request to the build server"); var requestLength = args.Count + 1 + (libDirectory == null ? 0 : 1); var requestArgs = new List<Argument>(requestLength); requestArgs.Add(new Argument(ArgumentId.CurrentDirectory, 0, workingDirectory)); requestArgs.Add(new Argument(ArgumentId.TempDirectory, 0, tempDirectory)); if (keepAlive != null) { requestArgs.Add(new Argument(ArgumentId.KeepAlive, 0, keepAlive)); } if (libDirectory != null) { requestArgs.Add(new Argument(ArgumentId.LibEnvVariable, 0, libDirectory)); } for (int i = 0; i < args.Count; ++i) { var arg = args[i]; requestArgs.Add(new Argument(ArgumentId.CommandLineArgument, i, arg)); } return new BuildRequest(language, compilerHash, requestArgs, requestId); } public static BuildRequest CreateShutdown() { var requestArgs = new[] { new Argument(ArgumentId.Shutdown, argumentIndex: 0, value: "") }; return new BuildRequest(RequestLanguage.CSharpCompile, GetCommitHash() ?? "", requestArgs); } /// <summary> /// Read a Request from the given stream. /// /// The total request size must be less than <see cref="MaximumRequestSize"/>. /// </summary> /// <returns>null if the Request was too large, the Request otherwise.</returns> public static async Task<BuildRequest> ReadAsync(Stream inStream, CancellationToken cancellationToken) { // Read the length of the request var lengthBuffer = new byte[4]; await ReadAllAsync(inStream, lengthBuffer, 4, cancellationToken).ConfigureAwait(false); var length = BitConverter.ToInt32(lengthBuffer, 0); // Back out if the request is too large if (length > MaximumRequestSize) { throw new ArgumentException($"Request is over {MaximumRequestSize >> 20}MB in length"); } cancellationToken.ThrowIfCancellationRequested(); // Read the full request var requestBuffer = new byte[length]; await ReadAllAsync(inStream, requestBuffer, length, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); // Parse the request into the Request data structure. using var reader = new BinaryReader(new MemoryStream(requestBuffer), Encoding.Unicode); var requestId = readGuid(reader); var language = (RequestLanguage)reader.ReadUInt32(); var compilerHash = reader.ReadString(); uint argumentCount = reader.ReadUInt32(); var argumentsBuilder = new List<Argument>((int)argumentCount); for (int i = 0; i < argumentCount; i++) { cancellationToken.ThrowIfCancellationRequested(); argumentsBuilder.Add(BuildRequest.Argument.ReadFromBinaryReader(reader)); } return new BuildRequest(language, compilerHash, argumentsBuilder, requestId); static Guid readGuid(BinaryReader reader) { const int size = 16; var bytes = new byte[size]; if (size != reader.Read(bytes, 0, size)) { throw new InvalidOperationException(); } return new Guid(bytes); } } /// <summary> /// Write a Request to the stream. /// </summary> public async Task WriteAsync(Stream outStream, CancellationToken cancellationToken = default(CancellationToken)) { using var memoryStream = new MemoryStream(); using var writer = new BinaryWriter(memoryStream, Encoding.Unicode); writer.Write(RequestId.ToByteArray()); writer.Write((uint)Language); writer.Write(CompilerHash); writer.Write(Arguments.Count); foreach (Argument arg in Arguments) { cancellationToken.ThrowIfCancellationRequested(); arg.WriteToBinaryWriter(writer); } writer.Flush(); cancellationToken.ThrowIfCancellationRequested(); // Write the length of the request int length = checked((int)memoryStream.Length); // Back out if the request is too large if (memoryStream.Length > MaximumRequestSize) { throw new ArgumentOutOfRangeException($"Request is over {MaximumRequestSize >> 20}MB in length"); } await outStream.WriteAsync(BitConverter.GetBytes(length), 0, 4, cancellationToken).ConfigureAwait(false); memoryStream.Position = 0; await memoryStream.CopyToAsync(outStream, bufferSize: length, cancellationToken: cancellationToken).ConfigureAwait(false); } /// <summary> /// A command line argument to the compilation. /// An argument is formatted as follows: /// /// Field Name Type Size (bytes) /// -------------------------------------------------- /// ID UInteger 4 /// Index UInteger 4 /// Value String Variable /// /// Strings are encoded via a length prefix as a signed /// 32-bit integer, followed by an array of characters. /// </summary> public readonly struct Argument { public readonly ArgumentId ArgumentId; public readonly int ArgumentIndex; public readonly string? Value; public Argument(ArgumentId argumentId, int argumentIndex, string? value) { ArgumentId = argumentId; ArgumentIndex = argumentIndex; Value = value; } public static Argument ReadFromBinaryReader(BinaryReader reader) { var argId = (ArgumentId)reader.ReadInt32(); var argIndex = reader.ReadInt32(); string? value = ReadLengthPrefixedString(reader); return new Argument(argId, argIndex, value); } public void WriteToBinaryWriter(BinaryWriter writer) { writer.Write((int)ArgumentId); writer.Write(ArgumentIndex); WriteLengthPrefixedString(writer, Value); } } } /// <summary> /// Base class for all possible responses to a request. /// The ResponseType enum should list all possible response types /// and ReadResponse creates the appropriate response subclass based /// on the response type sent by the client. /// The format of a response is: /// /// Field Name Field Type Size (bytes) /// ------------------------------------------------- /// responseLength int (positive) 4 /// responseType enum ResponseType 4 /// responseBody Response subclass variable /// </summary> internal abstract class BuildResponse { public enum ResponseType { // The client and server are using incompatible protocol versions. MismatchedVersion, // The build request completed on the server and the results are contained // in the message. Completed, // The build request could not be run on the server due because it created // an unresolvable inconsistency with analyzers. AnalyzerInconsistency, // The shutdown request completed and the server process information is // contained in the message. Shutdown, // The request was rejected by the server. Rejected, // The server hash did not match the one supplied by the client IncorrectHash, } public abstract ResponseType Type { get; } public async Task WriteAsync(Stream outStream, CancellationToken cancellationToken) { using (var memoryStream = new MemoryStream()) using (var writer = new BinaryWriter(memoryStream, Encoding.Unicode)) { writer.Write((int)Type); AddResponseBody(writer); writer.Flush(); cancellationToken.ThrowIfCancellationRequested(); // Send the response to the client // Write the length of the response int length = checked((int)memoryStream.Length); // There is no way to know the number of bytes written to // the pipe stream. We just have to assume all of them are written. await outStream.WriteAsync(BitConverter.GetBytes(length), 0, 4, cancellationToken).ConfigureAwait(false); memoryStream.Position = 0; await memoryStream.CopyToAsync(outStream, bufferSize: length, cancellationToken: cancellationToken).ConfigureAwait(false); } } protected abstract void AddResponseBody(BinaryWriter writer); /// <summary> /// May throw exceptions if there are pipe problems. /// </summary> /// <param name="stream"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public static async Task<BuildResponse> ReadAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken)) { // Read the response length var lengthBuffer = new byte[4]; await ReadAllAsync(stream, lengthBuffer, 4, cancellationToken).ConfigureAwait(false); var length = BitConverter.ToUInt32(lengthBuffer, 0); // Read the response var responseBuffer = new byte[length]; await ReadAllAsync(stream, responseBuffer, responseBuffer.Length, cancellationToken).ConfigureAwait(false); using (var reader = new BinaryReader(new MemoryStream(responseBuffer), Encoding.Unicode)) { var responseType = (ResponseType)reader.ReadInt32(); switch (responseType) { case ResponseType.Completed: return CompletedBuildResponse.Create(reader); case ResponseType.MismatchedVersion: return new MismatchedVersionBuildResponse(); case ResponseType.IncorrectHash: return new IncorrectHashBuildResponse(); case ResponseType.AnalyzerInconsistency: return AnalyzerInconsistencyBuildResponse.Create(reader); case ResponseType.Shutdown: return ShutdownBuildResponse.Create(reader); case ResponseType.Rejected: return RejectedBuildResponse.Create(reader); default: throw new InvalidOperationException("Received invalid response type from server."); } } } } /// <summary> /// Represents a Response from the server. A response is as follows. /// /// Field Name Type Size (bytes) /// -------------------------------------------------- /// Length UInteger 4 /// ReturnCode Integer 4 /// Output String Variable /// /// Strings are encoded via a character count prefix as a /// 32-bit integer, followed by an array of characters. /// /// </summary> internal sealed class CompletedBuildResponse : BuildResponse { public readonly int ReturnCode; public readonly bool Utf8Output; public readonly string Output; public CompletedBuildResponse(int returnCode, bool utf8output, string? output) { ReturnCode = returnCode; Utf8Output = utf8output; Output = output ?? string.Empty; } public override ResponseType Type => ResponseType.Completed; public static CompletedBuildResponse Create(BinaryReader reader) { var returnCode = reader.ReadInt32(); var utf8Output = reader.ReadBoolean(); var output = ReadLengthPrefixedString(reader); return new CompletedBuildResponse(returnCode, utf8Output, output); } protected override void AddResponseBody(BinaryWriter writer) { writer.Write(ReturnCode); writer.Write(Utf8Output); WriteLengthPrefixedString(writer, Output); } } internal sealed class ShutdownBuildResponse : BuildResponse { public readonly int ServerProcessId; public ShutdownBuildResponse(int serverProcessId) { ServerProcessId = serverProcessId; } public override ResponseType Type => ResponseType.Shutdown; protected override void AddResponseBody(BinaryWriter writer) { writer.Write(ServerProcessId); } public static ShutdownBuildResponse Create(BinaryReader reader) { var serverProcessId = reader.ReadInt32(); return new ShutdownBuildResponse(serverProcessId); } } internal sealed class MismatchedVersionBuildResponse : BuildResponse { public override ResponseType Type => ResponseType.MismatchedVersion; /// <summary> /// MismatchedVersion has no body. /// </summary> protected override void AddResponseBody(BinaryWriter writer) { } } internal sealed class IncorrectHashBuildResponse : BuildResponse { public override ResponseType Type => ResponseType.IncorrectHash; /// <summary> /// IncorrectHash has no body. /// </summary> protected override void AddResponseBody(BinaryWriter writer) { } } internal sealed class AnalyzerInconsistencyBuildResponse : BuildResponse { public override ResponseType Type => ResponseType.AnalyzerInconsistency; public ReadOnlyCollection<string> ErrorMessages { get; } public AnalyzerInconsistencyBuildResponse(ReadOnlyCollection<string> errorMessages) { ErrorMessages = errorMessages; } protected override void AddResponseBody(BinaryWriter writer) { writer.Write(ErrorMessages.Count); foreach (var message in ErrorMessages) { WriteLengthPrefixedString(writer, message); } } public static AnalyzerInconsistencyBuildResponse Create(BinaryReader reader) { var count = reader.ReadInt32(); var list = new List<string>(count); for (var i = 0; i < count; i++) { list.Add(ReadLengthPrefixedString(reader) ?? ""); } return new AnalyzerInconsistencyBuildResponse(new ReadOnlyCollection<string>(list)); } } internal sealed class RejectedBuildResponse : BuildResponse { public string Reason; public override ResponseType Type => ResponseType.Rejected; public RejectedBuildResponse(string reason) { Reason = reason; } protected override void AddResponseBody(BinaryWriter writer) { WriteLengthPrefixedString(writer, Reason); } public static RejectedBuildResponse Create(BinaryReader reader) { var reason = ReadLengthPrefixedString(reader); Debug.Assert(reason is object); return new RejectedBuildResponse(reason); } } // The id numbers below are just random. It's useful to use id numbers // that won't occur accidentally for debugging. internal enum RequestLanguage { CSharpCompile = 0x44532521, VisualBasicCompile = 0x44532522, } /// <summary> /// Constants about the protocol. /// </summary> internal static class BuildProtocolConstants { // Arguments for CSharp and VB Compiler public enum ArgumentId { // The current directory of the client CurrentDirectory = 0x51147221, // A comment line argument. The argument index indicates which one (0 .. N) CommandLineArgument, // The "LIB" environment variable of the client LibEnvVariable, // Request a longer keep alive time for the server KeepAlive, // Request a server shutdown from the client Shutdown, // The directory to use for temporary operations. TempDirectory, } /// <summary> /// Read a string from the Reader where the string is encoded /// as a length prefix (signed 32-bit integer) followed by /// a sequence of characters. /// </summary> public static string? ReadLengthPrefixedString(BinaryReader reader) { var length = reader.ReadInt32(); if (length < 0) { return null; } return new String(reader.ReadChars(length)); } /// <summary> /// Write a string to the Writer where the string is encoded /// as a length prefix (signed 32-bit integer) follows by /// a sequence of characters. /// </summary> public static void WriteLengthPrefixedString(BinaryWriter writer, string? value) { if (value is object) { writer.Write(value.Length); writer.Write(value.ToCharArray()); } else { writer.Write(-1); } } /// <summary> /// Reads the value of <see cref="CommitHashAttribute.Hash"/> of the assembly <see cref="BuildRequest"/> is defined in /// </summary> /// <returns>The hash value of the current assembly or an empty string</returns> public static string? GetCommitHash() { var hashAttributes = typeof(BuildRequest).Assembly.GetCustomAttributes<CommitHashAttribute>(); var hashAttributeCount = hashAttributes.Count(); if (hashAttributeCount != 1) { return null; } return hashAttributes.Single().Hash; } /// <summary> /// This task does not complete until we are completely done reading. /// </summary> internal static async Task ReadAllAsync( Stream stream, byte[] buffer, int count, CancellationToken cancellationToken) { int totalBytesRead = 0; do { int bytesRead = await stream.ReadAsync(buffer, totalBytesRead, count - totalBytesRead, cancellationToken).ConfigureAwait(false); if (bytesRead == 0) { throw new EndOfStreamException("Reached end of stream before end of read."); } totalBytesRead += bytesRead; } while (totalBytesRead < count); } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/INamedTypeSymbolExtensions.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.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class INamedTypeSymbolExtensions { public static IEnumerable<INamedTypeSymbol> GetBaseTypesAndThis(this INamedTypeSymbol? namedType) { var current = namedType; while (current != null) { yield return current; current = current.BaseType; } } public static ImmutableArray<ITypeParameterSymbol> GetAllTypeParameters(this INamedTypeSymbol? symbol) { var stack = GetContainmentStack(symbol); return stack.SelectMany(n => n.TypeParameters).ToImmutableArray(); } public static IEnumerable<ITypeSymbol> GetAllTypeArguments(this INamedTypeSymbol? symbol) { var stack = GetContainmentStack(symbol); return stack.SelectMany(n => n.TypeArguments); } private static Stack<INamedTypeSymbol> GetContainmentStack(INamedTypeSymbol? symbol) { var stack = new Stack<INamedTypeSymbol>(); for (var current = symbol; current != null; current = current.ContainingType) { stack.Push(current); } return stack; } public static bool IsContainedWithin([NotNullWhen(returnValue: true)] this INamedTypeSymbol? symbol, INamedTypeSymbol outer) { // TODO(cyrusn): Should we be using OriginalSymbol here? for (var current = symbol; current != null; current = current.ContainingType) { if (current.Equals(outer)) { return true; } } return false; } public static ISymbol? FindImplementationForAbstractMember(this INamedTypeSymbol? type, ISymbol symbol) { if (symbol.IsAbstract) { return type.GetBaseTypesAndThis().SelectMany(t => t.GetMembers(symbol.Name)) .FirstOrDefault(s => symbol.Equals(s.GetOverriddenMember())); } return null; } private static bool ImplementationExists(INamedTypeSymbol classOrStructType, ISymbol member) => classOrStructType.FindImplementationForInterfaceMember(member) != null; private static bool IsImplemented( this INamedTypeSymbol classOrStructType, ISymbol member, Func<INamedTypeSymbol, ISymbol, bool> isValidImplementation, CancellationToken cancellationToken) { if (member.ContainingType.TypeKind == TypeKind.Interface) { if (member.Kind == SymbolKind.Property) { return IsInterfacePropertyImplemented(classOrStructType, (IPropertySymbol)member); } else { return isValidImplementation(classOrStructType, member); } } if (member.IsAbstract) { if (member.Kind == SymbolKind.Property) { return IsAbstractPropertyImplemented(classOrStructType, (IPropertySymbol)member); } else { return classOrStructType.FindImplementationForAbstractMember(member) != null; } } return true; } private static bool IsInterfacePropertyImplemented(INamedTypeSymbol classOrStructType, IPropertySymbol propertySymbol) { // A property is only fully implemented if both it's setter and getter is implemented. return IsAccessorImplemented(propertySymbol.GetMethod, classOrStructType) && IsAccessorImplemented(propertySymbol.SetMethod, classOrStructType); // local functions static bool IsAccessorImplemented(IMethodSymbol? accessor, INamedTypeSymbol classOrStructType) { return accessor == null || !IsImplementable(accessor) || classOrStructType.FindImplementationForInterfaceMember(accessor) != null; } } private static bool IsAbstractPropertyImplemented(INamedTypeSymbol classOrStructType, IPropertySymbol propertySymbol) { // A property is only fully implemented if both it's setter and getter is implemented. if (propertySymbol.GetMethod != null) { if (classOrStructType.FindImplementationForAbstractMember(propertySymbol.GetMethod) == null) { return false; } } if (propertySymbol.SetMethod != null) { if (classOrStructType.FindImplementationForAbstractMember(propertySymbol.SetMethod) == null) { return false; } } return true; } private static bool IsExplicitlyImplemented( this INamedTypeSymbol classOrStructType, ISymbol member, Func<INamedTypeSymbol, ISymbol, bool> isValid, CancellationToken cancellationToken) { var implementation = classOrStructType.FindImplementationForInterfaceMember(member); if (implementation?.ContainingType.TypeKind == TypeKind.Interface) { // Treat all implementations in interfaces as explicit, even the original declaration with implementation. // There are no implicit interface implementations in derived interfaces and it feels reasonable to treat // original declaration with implementation as an explicit implementation as well, the implementation is // explicitly provided after all. All implementations in interfaces will be treated uniformly. return true; } return implementation switch { IEventSymbol @event => @event.ExplicitInterfaceImplementations.Length > 0, IMethodSymbol method => method.ExplicitInterfaceImplementations.Length > 0, IPropertySymbol property => property.ExplicitInterfaceImplementations.Length > 0, _ => false, }; } public static ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> GetAllUnimplementedMembers( this INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfaces, bool includeMembersRequiringExplicitImplementation, CancellationToken cancellationToken) { Func<INamedTypeSymbol, ISymbol, ImmutableArray<ISymbol>> GetMembers; if (includeMembersRequiringExplicitImplementation) { GetMembers = GetExplicitlyImplementableMembers; } else { GetMembers = GetImplicitlyImplementableMembers; } return classOrStructType.GetAllUnimplementedMembers( interfaces, IsImplemented, ImplementationExists, GetMembers, allowReimplementation: false, cancellationToken: cancellationToken); // local functions static ImmutableArray<ISymbol> GetImplicitlyImplementableMembers(INamedTypeSymbol type, ISymbol within) { if (type.TypeKind == TypeKind.Interface) { return type.GetMembers().WhereAsArray(m => m.DeclaredAccessibility == Accessibility.Public && m.Kind != SymbolKind.NamedType && IsImplementable(m) && !IsPropertyWithNonPublicImplementableAccessor(m) && IsImplicitlyImplementable(m, within)); } return type.GetMembers(); } static bool IsPropertyWithNonPublicImplementableAccessor(ISymbol member) { if (member.Kind != SymbolKind.Property) { return false; } var property = (IPropertySymbol)member; return IsNonPublicImplementableAccessor(property.GetMethod) || IsNonPublicImplementableAccessor(property.SetMethod); } static bool IsNonPublicImplementableAccessor(IMethodSymbol? accessor) { return accessor != null && IsImplementable(accessor) && accessor.DeclaredAccessibility != Accessibility.Public; } static bool IsImplicitlyImplementable(ISymbol member, ISymbol within) { if (member is IMethodSymbol { IsStatic: true, IsAbstract: true, MethodKind: MethodKind.UserDefinedOperator } method) { // For example, the following is not implementable implicitly. // interface I { static abstract int operator -(I x); } // But the following is implementable: // interface I<T> where T : I<T> { static abstract int operator -(T x); } // See https://github.com/dotnet/csharplang/blob/main/spec/classes.md#unary-operators. return method.Parameters.Any(p => p.Type.Equals(within, SymbolEqualityComparer.Default)); } return true; } } private static bool IsImplementable(ISymbol m) => m.IsVirtual || m.IsAbstract; public static ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> GetAllUnimplementedMembersInThis( this INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses, CancellationToken cancellationToken) { return classOrStructType.GetAllUnimplementedMembers( interfacesOrAbstractClasses, IsImplemented, (t, m) => { var implementation = classOrStructType.FindImplementationForInterfaceMember(m); return implementation != null && Equals(implementation.ContainingType, classOrStructType); }, GetMembers, allowReimplementation: true, cancellationToken: cancellationToken); } public static ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> GetAllUnimplementedMembersInThis( this INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses, Func<INamedTypeSymbol, ISymbol, ImmutableArray<ISymbol>> interfaceMemberGetter, CancellationToken cancellationToken) { return classOrStructType.GetAllUnimplementedMembers( interfacesOrAbstractClasses, IsImplemented, (t, m) => { var implementation = classOrStructType.FindImplementationForInterfaceMember(m); return implementation != null && Equals(implementation.ContainingType, classOrStructType); }, interfaceMemberGetter, allowReimplementation: true, cancellationToken: cancellationToken); } public static ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> GetAllUnimplementedExplicitMembers( this INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfaces, CancellationToken cancellationToken) { return classOrStructType.GetAllUnimplementedMembers( interfaces, IsExplicitlyImplemented, ImplementationExists, GetExplicitlyImplementableMembers, allowReimplementation: false, cancellationToken: cancellationToken); } private static ImmutableArray<ISymbol> GetExplicitlyImplementableMembers(INamedTypeSymbol type, ISymbol within) { if (type.TypeKind == TypeKind.Interface) { return type.GetMembers().WhereAsArray(m => m.Kind != SymbolKind.NamedType && IsImplementable(m) && m.IsAccessibleWithin(within) && !IsPropertyWithInaccessibleImplementableAccessor(m, within)); } return type.GetMembers(); } private static bool IsPropertyWithInaccessibleImplementableAccessor(ISymbol member, ISymbol within) { if (member.Kind != SymbolKind.Property) { return false; } var property = (IPropertySymbol)member; return IsInaccessibleImplementableAccessor(property.GetMethod, within) || IsInaccessibleImplementableAccessor(property.SetMethod, within); } private static bool IsInaccessibleImplementableAccessor(IMethodSymbol? accessor, ISymbol within) => accessor != null && IsImplementable(accessor) && !accessor.IsAccessibleWithin(within); private static ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> GetAllUnimplementedMembers( this INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses, Func<INamedTypeSymbol, ISymbol, Func<INamedTypeSymbol, ISymbol, bool>, CancellationToken, bool> isImplemented, Func<INamedTypeSymbol, ISymbol, bool> isValidImplementation, Func<INamedTypeSymbol, ISymbol, ImmutableArray<ISymbol>> interfaceMemberGetter, bool allowReimplementation, CancellationToken cancellationToken) { Contract.ThrowIfNull(classOrStructType); Contract.ThrowIfNull(interfacesOrAbstractClasses); Contract.ThrowIfNull(isImplemented); if (classOrStructType.TypeKind is not TypeKind.Class and not TypeKind.Struct) { return ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; } if (!interfacesOrAbstractClasses.Any()) { return ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; } if (!interfacesOrAbstractClasses.All(i => i.TypeKind == TypeKind.Interface) && !interfacesOrAbstractClasses.All(i => i.IsAbstractClass())) { return ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; } var typesToImplement = GetTypesToImplement(classOrStructType, interfacesOrAbstractClasses, allowReimplementation, cancellationToken); return typesToImplement.SelectAsArray(s => (s, members: GetUnimplementedMembers(classOrStructType, s, isImplemented, isValidImplementation, interfaceMemberGetter, cancellationToken))) .WhereAsArray(t => t.members.Length > 0); } private static ImmutableArray<INamedTypeSymbol> GetTypesToImplement( INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses, bool allowReimplementation, CancellationToken cancellationToken) { return interfacesOrAbstractClasses.First().TypeKind == TypeKind.Interface ? GetInterfacesToImplement(classOrStructType, interfacesOrAbstractClasses, allowReimplementation, cancellationToken) : GetAbstractClassesToImplement(interfacesOrAbstractClasses); } private static ImmutableArray<INamedTypeSymbol> GetAbstractClassesToImplement( IEnumerable<INamedTypeSymbol> abstractClasses) { return abstractClasses.SelectMany(a => a.GetBaseTypesAndThis()) .Where(t => t.IsAbstractClass()) .ToImmutableArray(); } private static ImmutableArray<INamedTypeSymbol> GetInterfacesToImplement( INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfaces, bool allowReimplementation, CancellationToken cancellationToken) { // We need to not only implement the specified interface, but also everything it // inherits from. cancellationToken.ThrowIfCancellationRequested(); var interfacesToImplement = new List<INamedTypeSymbol>( interfaces.SelectMany(i => i.GetAllInterfacesIncludingThis()).Distinct()); // However, there's no need to re-implement any interfaces that our base types already // implement. By definition they must contain all the necessary methods. var baseType = classOrStructType.BaseType; var alreadyImplementedInterfaces = baseType == null || allowReimplementation ? SpecializedCollections.EmptyEnumerable<INamedTypeSymbol>() : baseType.AllInterfaces; cancellationToken.ThrowIfCancellationRequested(); interfacesToImplement.RemoveRange(alreadyImplementedInterfaces); return interfacesToImplement.ToImmutableArray(); } private static ImmutableArray<ISymbol> GetUnimplementedMembers( this INamedTypeSymbol classOrStructType, INamedTypeSymbol interfaceType, Func<INamedTypeSymbol, ISymbol, Func<INamedTypeSymbol, ISymbol, bool>, CancellationToken, bool> isImplemented, Func<INamedTypeSymbol, ISymbol, bool> isValidImplementation, Func<INamedTypeSymbol, ISymbol, ImmutableArray<ISymbol>> interfaceMemberGetter, CancellationToken cancellationToken) { var q = from m in interfaceMemberGetter(interfaceType, classOrStructType) where m.Kind != SymbolKind.NamedType where m.Kind != SymbolKind.Method || ((IMethodSymbol)m).MethodKind is MethodKind.Ordinary or MethodKind.UserDefinedOperator where m.Kind != SymbolKind.Property || ((IPropertySymbol)m).IsIndexer || ((IPropertySymbol)m).CanBeReferencedByName where m.Kind != SymbolKind.Event || ((IEventSymbol)m).CanBeReferencedByName where !isImplemented(classOrStructType, m, isValidImplementation, cancellationToken) select m; return q.ToImmutableArray(); } public static IEnumerable<ISymbol> GetAttributeNamedParameters( this INamedTypeSymbol attributeSymbol, Compilation compilation, ISymbol within) { using var _ = PooledHashSet<string>.GetInstance(out var seenNames); var systemAttributeType = compilation.AttributeType(); foreach (var type in attributeSymbol.GetBaseTypesAndThis()) { if (type.Equals(systemAttributeType)) { break; } foreach (var member in type.GetMembers()) { var namedParameter = IsAttributeNamedParameter(member, within ?? compilation.Assembly); if (namedParameter != null && seenNames.Add(namedParameter.Name)) { yield return namedParameter; } } } } private static ISymbol? IsAttributeNamedParameter( ISymbol symbol, ISymbol within) { if (!symbol.CanBeReferencedByName || !symbol.IsAccessibleWithin(within)) { return null; } switch (symbol.Kind) { case SymbolKind.Field: var fieldSymbol = (IFieldSymbol)symbol; if (!fieldSymbol.IsConst && !fieldSymbol.IsReadOnly && !fieldSymbol.IsStatic) { return fieldSymbol; } break; case SymbolKind.Property: var propertySymbol = (IPropertySymbol)symbol; if (!propertySymbol.IsReadOnly && !propertySymbol.IsWriteOnly && !propertySymbol.IsStatic && propertySymbol.GetMethod != null && propertySymbol.SetMethod != null && propertySymbol.GetMethod.IsAccessibleWithin(within) && propertySymbol.SetMethod.IsAccessibleWithin(within)) { return propertySymbol; } break; } return null; } private static ImmutableArray<ISymbol> GetMembers(INamedTypeSymbol type, ISymbol within) => type.GetMembers(); /// <summary> /// Gets the set of members in the inheritance chain of <paramref name="containingType"/> that /// are overridable. The members will be returned in furthest-base type to closest-base /// type order. i.e. the overridable members of <see cref="System.Object"/> will be at the start /// of the list, and the members of the direct parent type of <paramref name="containingType"/> /// will be at the end of the list. /// /// If a member has already been overridden (in <paramref name="containingType"/> or any base type) /// it will not be included in the list. /// </summary> public static ImmutableArray<ISymbol> GetOverridableMembers( this INamedTypeSymbol containingType, CancellationToken cancellationToken) { // Keep track of the symbols we've seen and what order we saw them in. The // order allows us to produce the symbols in the end from the furthest base-type // to the closest base-type var result = new Dictionary<ISymbol, int>(); var index = 0; if (containingType != null && !containingType.IsScriptClass && !containingType.IsImplicitClass && !containingType.IsStatic) { if (containingType.TypeKind is TypeKind.Class or TypeKind.Struct) { var baseTypes = containingType.GetBaseTypes().Reverse(); foreach (var type in baseTypes) { cancellationToken.ThrowIfCancellationRequested(); // Prefer overrides in derived classes RemoveOverriddenMembers(result, type, cancellationToken); // Retain overridable methods AddOverridableMembers(result, containingType, type, ref index, cancellationToken); } // Don't suggest already overridden members RemoveOverriddenMembers(result, containingType, cancellationToken); } } return result.Keys.OrderBy(s => result[s]).ToImmutableArray(); } private static void AddOverridableMembers( Dictionary<ISymbol, int> result, INamedTypeSymbol containingType, INamedTypeSymbol type, ref int index, CancellationToken cancellationToken) { foreach (var member in type.GetMembers()) { cancellationToken.ThrowIfCancellationRequested(); if (IsOverridable(member, containingType)) { result[member] = index++; } } } private static bool IsOverridable(ISymbol member, INamedTypeSymbol containingType) { if (!member.IsAbstract && !member.IsVirtual && !member.IsOverride) return false; if (member.IsSealed) return false; if (!member.IsAccessibleWithin(containingType)) return false; return member switch { IEventSymbol => true, IMethodSymbol { MethodKind: MethodKind.Ordinary, CanBeReferencedByName: true } => true, IPropertySymbol { IsWithEvents: false } => true, _ => false, }; } private static void RemoveOverriddenMembers( Dictionary<ISymbol, int> result, INamedTypeSymbol containingType, CancellationToken cancellationToken) { foreach (var member in containingType.GetMembers()) { cancellationToken.ThrowIfCancellationRequested(); // An implicitly declared override is still something the user can provide their own explicit override // for. This is true for all implicit overrides *except* for the one for `bool object.Equals(object)`. // This override is not one the user is allowed to provide their own override for as it must have a very // particular implementation to ensure proper record equality semantics. if (!member.IsImplicitlyDeclared || IsEqualsObjectOverride(member)) { var overriddenMember = member.GetOverriddenMember(); if (overriddenMember != null) result.Remove(overriddenMember); } } } private static bool IsEqualsObjectOverride(ISymbol? member) { if (member == null) return false; if (IsEqualsObject(member)) return true; return IsEqualsObjectOverride(member.GetOverriddenMember()); } private static bool IsEqualsObject(ISymbol member) { return member is IMethodSymbol { Name: nameof(Equals), IsStatic: false, ContainingType: { SpecialType: SpecialType.System_Object }, Parameters: { Length: 1 }, }; } public static INamedTypeSymbol TryConstruct(this INamedTypeSymbol type, ITypeSymbol[] typeArguments) => typeArguments.Length > 0 ? type.Construct(typeArguments) : 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; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class INamedTypeSymbolExtensions { public static IEnumerable<INamedTypeSymbol> GetBaseTypesAndThis(this INamedTypeSymbol? namedType) { var current = namedType; while (current != null) { yield return current; current = current.BaseType; } } public static ImmutableArray<ITypeParameterSymbol> GetAllTypeParameters(this INamedTypeSymbol? symbol) { var stack = GetContainmentStack(symbol); return stack.SelectMany(n => n.TypeParameters).ToImmutableArray(); } public static IEnumerable<ITypeSymbol> GetAllTypeArguments(this INamedTypeSymbol? symbol) { var stack = GetContainmentStack(symbol); return stack.SelectMany(n => n.TypeArguments); } private static Stack<INamedTypeSymbol> GetContainmentStack(INamedTypeSymbol? symbol) { var stack = new Stack<INamedTypeSymbol>(); for (var current = symbol; current != null; current = current.ContainingType) { stack.Push(current); } return stack; } public static bool IsContainedWithin([NotNullWhen(returnValue: true)] this INamedTypeSymbol? symbol, INamedTypeSymbol outer) { // TODO(cyrusn): Should we be using OriginalSymbol here? for (var current = symbol; current != null; current = current.ContainingType) { if (current.Equals(outer)) { return true; } } return false; } public static ISymbol? FindImplementationForAbstractMember(this INamedTypeSymbol? type, ISymbol symbol) { if (symbol.IsAbstract) { return type.GetBaseTypesAndThis().SelectMany(t => t.GetMembers(symbol.Name)) .FirstOrDefault(s => symbol.Equals(s.GetOverriddenMember())); } return null; } private static bool ImplementationExists(INamedTypeSymbol classOrStructType, ISymbol member) => classOrStructType.FindImplementationForInterfaceMember(member) != null; private static bool IsImplemented( this INamedTypeSymbol classOrStructType, ISymbol member, Func<INamedTypeSymbol, ISymbol, bool> isValidImplementation, CancellationToken cancellationToken) { if (member.ContainingType.TypeKind == TypeKind.Interface) { if (member.Kind == SymbolKind.Property) { return IsInterfacePropertyImplemented(classOrStructType, (IPropertySymbol)member); } else { return isValidImplementation(classOrStructType, member); } } if (member.IsAbstract) { if (member.Kind == SymbolKind.Property) { return IsAbstractPropertyImplemented(classOrStructType, (IPropertySymbol)member); } else { return classOrStructType.FindImplementationForAbstractMember(member) != null; } } return true; } private static bool IsInterfacePropertyImplemented(INamedTypeSymbol classOrStructType, IPropertySymbol propertySymbol) { // A property is only fully implemented if both it's setter and getter is implemented. return IsAccessorImplemented(propertySymbol.GetMethod, classOrStructType) && IsAccessorImplemented(propertySymbol.SetMethod, classOrStructType); // local functions static bool IsAccessorImplemented(IMethodSymbol? accessor, INamedTypeSymbol classOrStructType) { return accessor == null || !IsImplementable(accessor) || classOrStructType.FindImplementationForInterfaceMember(accessor) != null; } } private static bool IsAbstractPropertyImplemented(INamedTypeSymbol classOrStructType, IPropertySymbol propertySymbol) { // A property is only fully implemented if both it's setter and getter is implemented. if (propertySymbol.GetMethod != null) { if (classOrStructType.FindImplementationForAbstractMember(propertySymbol.GetMethod) == null) { return false; } } if (propertySymbol.SetMethod != null) { if (classOrStructType.FindImplementationForAbstractMember(propertySymbol.SetMethod) == null) { return false; } } return true; } private static bool IsExplicitlyImplemented( this INamedTypeSymbol classOrStructType, ISymbol member, Func<INamedTypeSymbol, ISymbol, bool> isValid, CancellationToken cancellationToken) { var implementation = classOrStructType.FindImplementationForInterfaceMember(member); if (implementation?.ContainingType.TypeKind == TypeKind.Interface) { // Treat all implementations in interfaces as explicit, even the original declaration with implementation. // There are no implicit interface implementations in derived interfaces and it feels reasonable to treat // original declaration with implementation as an explicit implementation as well, the implementation is // explicitly provided after all. All implementations in interfaces will be treated uniformly. return true; } return implementation switch { IEventSymbol @event => @event.ExplicitInterfaceImplementations.Length > 0, IMethodSymbol method => method.ExplicitInterfaceImplementations.Length > 0, IPropertySymbol property => property.ExplicitInterfaceImplementations.Length > 0, _ => false, }; } public static ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> GetAllUnimplementedMembers( this INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfaces, bool includeMembersRequiringExplicitImplementation, CancellationToken cancellationToken) { Func<INamedTypeSymbol, ISymbol, ImmutableArray<ISymbol>> GetMembers; if (includeMembersRequiringExplicitImplementation) { GetMembers = GetExplicitlyImplementableMembers; } else { GetMembers = GetImplicitlyImplementableMembers; } return classOrStructType.GetAllUnimplementedMembers( interfaces, IsImplemented, ImplementationExists, GetMembers, allowReimplementation: false, cancellationToken: cancellationToken); // local functions static ImmutableArray<ISymbol> GetImplicitlyImplementableMembers(INamedTypeSymbol type, ISymbol within) { if (type.TypeKind == TypeKind.Interface) { return type.GetMembers().WhereAsArray(m => m.DeclaredAccessibility == Accessibility.Public && m.Kind != SymbolKind.NamedType && IsImplementable(m) && !IsPropertyWithNonPublicImplementableAccessor(m) && IsImplicitlyImplementable(m, within)); } return type.GetMembers(); } static bool IsPropertyWithNonPublicImplementableAccessor(ISymbol member) { if (member.Kind != SymbolKind.Property) { return false; } var property = (IPropertySymbol)member; return IsNonPublicImplementableAccessor(property.GetMethod) || IsNonPublicImplementableAccessor(property.SetMethod); } static bool IsNonPublicImplementableAccessor(IMethodSymbol? accessor) { return accessor != null && IsImplementable(accessor) && accessor.DeclaredAccessibility != Accessibility.Public; } static bool IsImplicitlyImplementable(ISymbol member, ISymbol within) { if (member is IMethodSymbol { IsStatic: true, IsAbstract: true, MethodKind: MethodKind.UserDefinedOperator } method) { // For example, the following is not implementable implicitly. // interface I { static abstract int operator -(I x); } // But the following is implementable: // interface I<T> where T : I<T> { static abstract int operator -(T x); } // See https://github.com/dotnet/csharplang/blob/main/spec/classes.md#unary-operators. return method.Parameters.Any(p => p.Type.Equals(within, SymbolEqualityComparer.Default)); } return true; } } private static bool IsImplementable(ISymbol m) => m.IsVirtual || m.IsAbstract; public static ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> GetAllUnimplementedMembersInThis( this INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses, CancellationToken cancellationToken) { return classOrStructType.GetAllUnimplementedMembers( interfacesOrAbstractClasses, IsImplemented, (t, m) => { var implementation = classOrStructType.FindImplementationForInterfaceMember(m); return implementation != null && Equals(implementation.ContainingType, classOrStructType); }, GetMembers, allowReimplementation: true, cancellationToken: cancellationToken); } public static ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> GetAllUnimplementedMembersInThis( this INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses, Func<INamedTypeSymbol, ISymbol, ImmutableArray<ISymbol>> interfaceMemberGetter, CancellationToken cancellationToken) { return classOrStructType.GetAllUnimplementedMembers( interfacesOrAbstractClasses, IsImplemented, (t, m) => { var implementation = classOrStructType.FindImplementationForInterfaceMember(m); return implementation != null && Equals(implementation.ContainingType, classOrStructType); }, interfaceMemberGetter, allowReimplementation: true, cancellationToken: cancellationToken); } public static ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> GetAllUnimplementedExplicitMembers( this INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfaces, CancellationToken cancellationToken) { return classOrStructType.GetAllUnimplementedMembers( interfaces, IsExplicitlyImplemented, ImplementationExists, GetExplicitlyImplementableMembers, allowReimplementation: false, cancellationToken: cancellationToken); } private static ImmutableArray<ISymbol> GetExplicitlyImplementableMembers(INamedTypeSymbol type, ISymbol within) { if (type.TypeKind == TypeKind.Interface) { return type.GetMembers().WhereAsArray(m => m.Kind != SymbolKind.NamedType && IsImplementable(m) && m.IsAccessibleWithin(within) && !IsPropertyWithInaccessibleImplementableAccessor(m, within)); } return type.GetMembers(); } private static bool IsPropertyWithInaccessibleImplementableAccessor(ISymbol member, ISymbol within) { if (member.Kind != SymbolKind.Property) { return false; } var property = (IPropertySymbol)member; return IsInaccessibleImplementableAccessor(property.GetMethod, within) || IsInaccessibleImplementableAccessor(property.SetMethod, within); } private static bool IsInaccessibleImplementableAccessor(IMethodSymbol? accessor, ISymbol within) => accessor != null && IsImplementable(accessor) && !accessor.IsAccessibleWithin(within); private static ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)> GetAllUnimplementedMembers( this INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses, Func<INamedTypeSymbol, ISymbol, Func<INamedTypeSymbol, ISymbol, bool>, CancellationToken, bool> isImplemented, Func<INamedTypeSymbol, ISymbol, bool> isValidImplementation, Func<INamedTypeSymbol, ISymbol, ImmutableArray<ISymbol>> interfaceMemberGetter, bool allowReimplementation, CancellationToken cancellationToken) { Contract.ThrowIfNull(classOrStructType); Contract.ThrowIfNull(interfacesOrAbstractClasses); Contract.ThrowIfNull(isImplemented); if (classOrStructType.TypeKind is not TypeKind.Class and not TypeKind.Struct) { return ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; } if (!interfacesOrAbstractClasses.Any()) { return ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; } if (!interfacesOrAbstractClasses.All(i => i.TypeKind == TypeKind.Interface) && !interfacesOrAbstractClasses.All(i => i.IsAbstractClass())) { return ImmutableArray<(INamedTypeSymbol type, ImmutableArray<ISymbol> members)>.Empty; } var typesToImplement = GetTypesToImplement(classOrStructType, interfacesOrAbstractClasses, allowReimplementation, cancellationToken); return typesToImplement.SelectAsArray(s => (s, members: GetUnimplementedMembers(classOrStructType, s, isImplemented, isValidImplementation, interfaceMemberGetter, cancellationToken))) .WhereAsArray(t => t.members.Length > 0); } private static ImmutableArray<INamedTypeSymbol> GetTypesToImplement( INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfacesOrAbstractClasses, bool allowReimplementation, CancellationToken cancellationToken) { return interfacesOrAbstractClasses.First().TypeKind == TypeKind.Interface ? GetInterfacesToImplement(classOrStructType, interfacesOrAbstractClasses, allowReimplementation, cancellationToken) : GetAbstractClassesToImplement(interfacesOrAbstractClasses); } private static ImmutableArray<INamedTypeSymbol> GetAbstractClassesToImplement( IEnumerable<INamedTypeSymbol> abstractClasses) { return abstractClasses.SelectMany(a => a.GetBaseTypesAndThis()) .Where(t => t.IsAbstractClass()) .ToImmutableArray(); } private static ImmutableArray<INamedTypeSymbol> GetInterfacesToImplement( INamedTypeSymbol classOrStructType, IEnumerable<INamedTypeSymbol> interfaces, bool allowReimplementation, CancellationToken cancellationToken) { // We need to not only implement the specified interface, but also everything it // inherits from. cancellationToken.ThrowIfCancellationRequested(); var interfacesToImplement = new List<INamedTypeSymbol>( interfaces.SelectMany(i => i.GetAllInterfacesIncludingThis()).Distinct()); // However, there's no need to re-implement any interfaces that our base types already // implement. By definition they must contain all the necessary methods. var baseType = classOrStructType.BaseType; var alreadyImplementedInterfaces = baseType == null || allowReimplementation ? SpecializedCollections.EmptyEnumerable<INamedTypeSymbol>() : baseType.AllInterfaces; cancellationToken.ThrowIfCancellationRequested(); interfacesToImplement.RemoveRange(alreadyImplementedInterfaces); return interfacesToImplement.ToImmutableArray(); } private static ImmutableArray<ISymbol> GetUnimplementedMembers( this INamedTypeSymbol classOrStructType, INamedTypeSymbol interfaceType, Func<INamedTypeSymbol, ISymbol, Func<INamedTypeSymbol, ISymbol, bool>, CancellationToken, bool> isImplemented, Func<INamedTypeSymbol, ISymbol, bool> isValidImplementation, Func<INamedTypeSymbol, ISymbol, ImmutableArray<ISymbol>> interfaceMemberGetter, CancellationToken cancellationToken) { var q = from m in interfaceMemberGetter(interfaceType, classOrStructType) where m.Kind != SymbolKind.NamedType where m.Kind != SymbolKind.Method || ((IMethodSymbol)m).MethodKind is MethodKind.Ordinary or MethodKind.UserDefinedOperator where m.Kind != SymbolKind.Property || ((IPropertySymbol)m).IsIndexer || ((IPropertySymbol)m).CanBeReferencedByName where m.Kind != SymbolKind.Event || ((IEventSymbol)m).CanBeReferencedByName where !isImplemented(classOrStructType, m, isValidImplementation, cancellationToken) select m; return q.ToImmutableArray(); } public static IEnumerable<ISymbol> GetAttributeNamedParameters( this INamedTypeSymbol attributeSymbol, Compilation compilation, ISymbol within) { using var _ = PooledHashSet<string>.GetInstance(out var seenNames); var systemAttributeType = compilation.AttributeType(); foreach (var type in attributeSymbol.GetBaseTypesAndThis()) { if (type.Equals(systemAttributeType)) { break; } foreach (var member in type.GetMembers()) { var namedParameter = IsAttributeNamedParameter(member, within ?? compilation.Assembly); if (namedParameter != null && seenNames.Add(namedParameter.Name)) { yield return namedParameter; } } } } private static ISymbol? IsAttributeNamedParameter( ISymbol symbol, ISymbol within) { if (!symbol.CanBeReferencedByName || !symbol.IsAccessibleWithin(within)) { return null; } switch (symbol.Kind) { case SymbolKind.Field: var fieldSymbol = (IFieldSymbol)symbol; if (!fieldSymbol.IsConst && !fieldSymbol.IsReadOnly && !fieldSymbol.IsStatic) { return fieldSymbol; } break; case SymbolKind.Property: var propertySymbol = (IPropertySymbol)symbol; if (!propertySymbol.IsReadOnly && !propertySymbol.IsWriteOnly && !propertySymbol.IsStatic && propertySymbol.GetMethod != null && propertySymbol.SetMethod != null && propertySymbol.GetMethod.IsAccessibleWithin(within) && propertySymbol.SetMethod.IsAccessibleWithin(within)) { return propertySymbol; } break; } return null; } private static ImmutableArray<ISymbol> GetMembers(INamedTypeSymbol type, ISymbol within) => type.GetMembers(); /// <summary> /// Gets the set of members in the inheritance chain of <paramref name="containingType"/> that /// are overridable. The members will be returned in furthest-base type to closest-base /// type order. i.e. the overridable members of <see cref="System.Object"/> will be at the start /// of the list, and the members of the direct parent type of <paramref name="containingType"/> /// will be at the end of the list. /// /// If a member has already been overridden (in <paramref name="containingType"/> or any base type) /// it will not be included in the list. /// </summary> public static ImmutableArray<ISymbol> GetOverridableMembers( this INamedTypeSymbol containingType, CancellationToken cancellationToken) { // Keep track of the symbols we've seen and what order we saw them in. The // order allows us to produce the symbols in the end from the furthest base-type // to the closest base-type var result = new Dictionary<ISymbol, int>(); var index = 0; if (containingType != null && !containingType.IsScriptClass && !containingType.IsImplicitClass && !containingType.IsStatic) { if (containingType.TypeKind is TypeKind.Class or TypeKind.Struct) { var baseTypes = containingType.GetBaseTypes().Reverse(); foreach (var type in baseTypes) { cancellationToken.ThrowIfCancellationRequested(); // Prefer overrides in derived classes RemoveOverriddenMembers(result, type, cancellationToken); // Retain overridable methods AddOverridableMembers(result, containingType, type, ref index, cancellationToken); } // Don't suggest already overridden members RemoveOverriddenMembers(result, containingType, cancellationToken); } } return result.Keys.OrderBy(s => result[s]).ToImmutableArray(); } private static void AddOverridableMembers( Dictionary<ISymbol, int> result, INamedTypeSymbol containingType, INamedTypeSymbol type, ref int index, CancellationToken cancellationToken) { foreach (var member in type.GetMembers()) { cancellationToken.ThrowIfCancellationRequested(); if (IsOverridable(member, containingType)) { result[member] = index++; } } } private static bool IsOverridable(ISymbol member, INamedTypeSymbol containingType) { if (!member.IsAbstract && !member.IsVirtual && !member.IsOverride) return false; if (member.IsSealed) return false; if (!member.IsAccessibleWithin(containingType)) return false; return member switch { IEventSymbol => true, IMethodSymbol { MethodKind: MethodKind.Ordinary, CanBeReferencedByName: true } => true, IPropertySymbol { IsWithEvents: false } => true, _ => false, }; } private static void RemoveOverriddenMembers( Dictionary<ISymbol, int> result, INamedTypeSymbol containingType, CancellationToken cancellationToken) { foreach (var member in containingType.GetMembers()) { cancellationToken.ThrowIfCancellationRequested(); // An implicitly declared override is still something the user can provide their own explicit override // for. This is true for all implicit overrides *except* for the one for `bool object.Equals(object)`. // This override is not one the user is allowed to provide their own override for as it must have a very // particular implementation to ensure proper record equality semantics. if (!member.IsImplicitlyDeclared || IsEqualsObjectOverride(member)) { var overriddenMember = member.GetOverriddenMember(); if (overriddenMember != null) result.Remove(overriddenMember); } } } private static bool IsEqualsObjectOverride(ISymbol? member) { if (member == null) return false; if (IsEqualsObject(member)) return true; return IsEqualsObjectOverride(member.GetOverriddenMember()); } private static bool IsEqualsObject(ISymbol member) { return member is IMethodSymbol { Name: nameof(Equals), IsStatic: false, ContainingType: { SpecialType: SpecialType.System_Object }, Parameters: { Length: 1 }, }; } public static INamedTypeSymbol TryConstruct(this INamedTypeSymbol type, ITypeSymbol[] typeArguments) => typeArguments.Length > 0 ? type.Construct(typeArguments) : type; } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Workspaces/Core/Portable/Editing/SyntaxEditor.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.CodeAnalysis; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editing { /// <summary> /// An editor for making changes to a syntax tree. /// </summary> public class SyntaxEditor { private readonly SyntaxGenerator _generator; private readonly List<Change> _changes; private bool _allowEditsOnLazilyCreatedTrackedNewNodes; private HashSet<SyntaxNode>? _lazyTrackedNewNodesOpt; /// <summary> /// Creates a new <see cref="SyntaxEditor"/> instance. /// </summary> public SyntaxEditor(SyntaxNode root, Workspace workspace) { if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } OriginalRoot = root ?? throw new ArgumentNullException(nameof(root)); _generator = SyntaxGenerator.GetGenerator(workspace, root.Language); _changes = new List<Change>(); } internal SyntaxEditor(SyntaxNode root, SyntaxGenerator generator) { OriginalRoot = root ?? throw new ArgumentNullException(nameof(root)); _generator = generator; _changes = new List<Change>(); } [return: NotNullIfNotNull("node")] private SyntaxNode? ApplyTrackingToNewNode(SyntaxNode? node) { if (node == null) { return null; } _lazyTrackedNewNodesOpt ??= new HashSet<SyntaxNode>(); foreach (var descendant in node.DescendantNodesAndSelf()) { _lazyTrackedNewNodesOpt.Add(descendant); } return node.TrackNodes(node.DescendantNodesAndSelf()); } private IEnumerable<SyntaxNode> ApplyTrackingToNewNodes(IEnumerable<SyntaxNode> nodes) { foreach (var node in nodes) { var result = ApplyTrackingToNewNode(node); yield return result; } } /// <summary> /// The <see cref="SyntaxNode"/> that was specified when the <see cref="SyntaxEditor"/> was constructed. /// </summary> public SyntaxNode OriginalRoot { get; } /// <summary> /// A <see cref="SyntaxGenerator"/> to use to create and change <see cref="SyntaxNode"/>'s. /// </summary> public SyntaxGenerator Generator => _generator; /// <summary> /// Returns the changed root node. /// </summary> public SyntaxNode GetChangedRoot() { var nodes = Enumerable.Distinct(_changes.Where(c => OriginalRoot.Contains(c.Node)) .Select(c => c.Node)); var newRoot = OriginalRoot.TrackNodes(nodes); foreach (var change in _changes) { newRoot = change.Apply(newRoot, _generator); } return newRoot; } /// <summary> /// Makes sure the node is tracked, even if it is not changed. /// </summary> public void TrackNode(SyntaxNode node) { CheckNodeInOriginalTreeOrTracked(node); _changes.Add(new NoChange(node)); } /// <summary> /// Remove the node from the tree. /// </summary> /// <param name="node">The node to remove that currently exists as part of the tree.</param> public void RemoveNode(SyntaxNode node) => RemoveNode(node, SyntaxGenerator.DefaultRemoveOptions); /// <summary> /// Remove the node from the tree. /// </summary> /// <param name="node">The node to remove that currently exists as part of the tree.</param> /// <param name="options">Options that affect how node removal works.</param> public void RemoveNode(SyntaxNode node, SyntaxRemoveOptions options) { CheckNodeInOriginalTreeOrTracked(node); _changes.Add(new RemoveChange(node, options)); } /// <summary> /// Replace the specified node with a node produced by the function. /// </summary> /// <param name="node">The node to replace that already exists in the tree.</param> /// <param name="computeReplacement">A function that computes a replacement node. /// The node passed into the compute function includes changes from prior edits. It will not appear as a descendant of the original root.</param> public void ReplaceNode(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> computeReplacement) { CheckNodeInOriginalTreeOrTracked(node); if (computeReplacement == null) { throw new ArgumentNullException(nameof(computeReplacement)); } _allowEditsOnLazilyCreatedTrackedNewNodes = true; _changes.Add(new ReplaceChange(node, computeReplacement, this)); } internal void ReplaceNode(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, IEnumerable<SyntaxNode>> computeReplacement) { CheckNodeInOriginalTreeOrTracked(node); if (computeReplacement == null) { throw new ArgumentNullException(nameof(computeReplacement)); } _allowEditsOnLazilyCreatedTrackedNewNodes = true; _changes.Add(new ReplaceWithCollectionChange(node, computeReplacement, this)); } internal void ReplaceNode<TArgument>(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> computeReplacement, TArgument argument) { CheckNodeInOriginalTreeOrTracked(node); if (computeReplacement == null) { throw new ArgumentNullException(nameof(computeReplacement)); } _allowEditsOnLazilyCreatedTrackedNewNodes = true; _changes.Add(new ReplaceChange<TArgument>(node, computeReplacement, argument, this)); } /// <summary> /// Replace the specified node with a different node. /// </summary> /// <param name="node">The node to replace that already exists in the tree.</param> /// <param name="newNode">The new node that will be placed into the tree in the existing node's location.</param> public void ReplaceNode(SyntaxNode node, SyntaxNode newNode) { CheckNodeInOriginalTreeOrTracked(node); if (node == newNode) { return; } newNode = ApplyTrackingToNewNode(newNode); _changes.Add(new ReplaceChange(node, (n, g) => newNode, this)); } /// <summary> /// Insert the new nodes before the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed before. This must be a node this is contained within a syntax list.</param> /// <param name="newNodes">The nodes to place before the existing node. These nodes must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertBefore(SyntaxNode node, IEnumerable<SyntaxNode> newNodes) { CheckNodeInOriginalTreeOrTracked(node); if (newNodes == null) { throw new ArgumentNullException(nameof(newNodes)); } newNodes = ApplyTrackingToNewNodes(newNodes); _changes.Add(new InsertChange(node, newNodes, isBefore: true)); } /// <summary> /// Insert the new node before the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed before. This must be a node this is contained within a syntax list.</param> /// <param name="newNode">The node to place before the existing node. This node must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertBefore(SyntaxNode node, SyntaxNode newNode) => InsertBefore(node, new[] { newNode }); /// <summary> /// Insert the new nodes after the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed after. This must be a node this is contained within a syntax list.</param> /// <param name="newNodes">The nodes to place after the existing node. These nodes must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertAfter(SyntaxNode node, IEnumerable<SyntaxNode> newNodes) { CheckNodeInOriginalTreeOrTracked(node); if (newNodes == null) { throw new ArgumentNullException(nameof(newNodes)); } newNodes = ApplyTrackingToNewNodes(newNodes); _changes.Add(new InsertChange(node, newNodes, isBefore: false)); } /// <summary> /// Insert the new node after the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed after. This must be a node this is contained within a syntax list.</param> /// <param name="newNode">The node to place after the existing node. This node must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertAfter(SyntaxNode node, SyntaxNode newNode) => this.InsertAfter(node, new[] { newNode }); private void CheckNodeInOriginalTreeOrTracked(SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (OriginalRoot.Contains(node)) { // Node is contained in the original tree. return; } if (_allowEditsOnLazilyCreatedTrackedNewNodes) { // This could be a node that is handed to us lazily from one of the prior edits // which support lazy replacement nodes, we conservatively avoid throwing here. // If this was indeed an unsupported node, syntax editor will throw an exception later // when attempting to compute changed root. return; } if (_lazyTrackedNewNodesOpt?.Contains(node) == true) { // Node is one of the new nodes, which is already tracked and supported. return; } throw new ArgumentException(WorkspacesResources.The_node_is_not_part_of_the_tree, nameof(node)); } private abstract class Change { internal readonly SyntaxNode Node; public Change(SyntaxNode node) => this.Node = node; public abstract SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator); } private class NoChange : Change { public NoChange(SyntaxNode node) : base(node) { } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) => root; } private class RemoveChange : Change { private readonly SyntaxRemoveOptions _options; public RemoveChange(SyntaxNode node, SyntaxRemoveOptions options) : base(node) { _options = options; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) => generator.RemoveNode(root, root.GetCurrentNode(this.Node), _options); } private class ReplaceChange : Change { private readonly Func<SyntaxNode, SyntaxGenerator, SyntaxNode?> _modifier; private readonly SyntaxEditor _editor; public ReplaceChange( SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, SyntaxNode?> modifier, SyntaxEditor editor) : base(node) { Contract.ThrowIfNull(node, "Passed in node is null."); _modifier = modifier; _editor = editor; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); if (current is null) { Contract.Fail($"GetCurrentNode returned null with the following node: {this.Node}"); } var newNode = _modifier(current, generator); newNode = _editor.ApplyTrackingToNewNode(newNode); return generator.ReplaceNode(root, current, newNode); } } private class ReplaceWithCollectionChange : Change { private readonly Func<SyntaxNode, SyntaxGenerator, IEnumerable<SyntaxNode>> _modifier; private readonly SyntaxEditor _editor; public ReplaceWithCollectionChange( SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, IEnumerable<SyntaxNode>> modifier, SyntaxEditor editor) : base(node) { _modifier = modifier; _editor = editor; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); if (current is null) { Contract.Fail($"GetCurrentNode returned null with the following node: {this.Node}"); } var newNodes = _modifier(current, generator).ToList(); for (var i = 0; i < newNodes.Count; i++) { newNodes[i] = _editor.ApplyTrackingToNewNode(newNodes[i]); } return SyntaxGenerator.ReplaceNode(root, current, newNodes); } } private class ReplaceChange<TArgument> : Change { private readonly Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> _modifier; private readonly TArgument _argument; private readonly SyntaxEditor _editor; public ReplaceChange( SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> modifier, TArgument argument, SyntaxEditor editor) : base(node) { _modifier = modifier; _argument = argument; _editor = editor; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); if (current is null) { Contract.Fail($"GetCurrentNode returned null with the following node: {this.Node}"); } var newNode = _modifier(current, generator, _argument); newNode = _editor.ApplyTrackingToNewNode(newNode); return generator.ReplaceNode(root, current, newNode); } } private class InsertChange : Change { private readonly List<SyntaxNode> _newNodes; private readonly bool _isBefore; public InsertChange(SyntaxNode node, IEnumerable<SyntaxNode> newNodes, bool isBefore) : base(node) { _newNodes = newNodes.ToList(); _isBefore = isBefore; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { if (_isBefore) { return generator.InsertNodesBefore(root, root.GetCurrentNode(this.Node), _newNodes); } else { return generator.InsertNodesAfter(root, root.GetCurrentNode(this.Node), _newNodes); } } } } }
// Licensed to the .NET Foundation under one or more 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.CodeAnalysis; using System.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editing { /// <summary> /// An editor for making changes to a syntax tree. /// </summary> public class SyntaxEditor { private readonly SyntaxGenerator _generator; private readonly List<Change> _changes; private bool _allowEditsOnLazilyCreatedTrackedNewNodes; private HashSet<SyntaxNode>? _lazyTrackedNewNodesOpt; /// <summary> /// Creates a new <see cref="SyntaxEditor"/> instance. /// </summary> public SyntaxEditor(SyntaxNode root, Workspace workspace) { if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } OriginalRoot = root ?? throw new ArgumentNullException(nameof(root)); _generator = SyntaxGenerator.GetGenerator(workspace, root.Language); _changes = new List<Change>(); } internal SyntaxEditor(SyntaxNode root, SyntaxGenerator generator) { OriginalRoot = root ?? throw new ArgumentNullException(nameof(root)); _generator = generator; _changes = new List<Change>(); } [return: NotNullIfNotNull("node")] private SyntaxNode? ApplyTrackingToNewNode(SyntaxNode? node) { if (node == null) { return null; } _lazyTrackedNewNodesOpt ??= new HashSet<SyntaxNode>(); foreach (var descendant in node.DescendantNodesAndSelf()) { _lazyTrackedNewNodesOpt.Add(descendant); } return node.TrackNodes(node.DescendantNodesAndSelf()); } private IEnumerable<SyntaxNode> ApplyTrackingToNewNodes(IEnumerable<SyntaxNode> nodes) { foreach (var node in nodes) { var result = ApplyTrackingToNewNode(node); yield return result; } } /// <summary> /// The <see cref="SyntaxNode"/> that was specified when the <see cref="SyntaxEditor"/> was constructed. /// </summary> public SyntaxNode OriginalRoot { get; } /// <summary> /// A <see cref="SyntaxGenerator"/> to use to create and change <see cref="SyntaxNode"/>'s. /// </summary> public SyntaxGenerator Generator => _generator; /// <summary> /// Returns the changed root node. /// </summary> public SyntaxNode GetChangedRoot() { var nodes = Enumerable.Distinct(_changes.Where(c => OriginalRoot.Contains(c.Node)) .Select(c => c.Node)); var newRoot = OriginalRoot.TrackNodes(nodes); foreach (var change in _changes) { newRoot = change.Apply(newRoot, _generator); } return newRoot; } /// <summary> /// Makes sure the node is tracked, even if it is not changed. /// </summary> public void TrackNode(SyntaxNode node) { CheckNodeInOriginalTreeOrTracked(node); _changes.Add(new NoChange(node)); } /// <summary> /// Remove the node from the tree. /// </summary> /// <param name="node">The node to remove that currently exists as part of the tree.</param> public void RemoveNode(SyntaxNode node) => RemoveNode(node, SyntaxGenerator.DefaultRemoveOptions); /// <summary> /// Remove the node from the tree. /// </summary> /// <param name="node">The node to remove that currently exists as part of the tree.</param> /// <param name="options">Options that affect how node removal works.</param> public void RemoveNode(SyntaxNode node, SyntaxRemoveOptions options) { CheckNodeInOriginalTreeOrTracked(node); _changes.Add(new RemoveChange(node, options)); } /// <summary> /// Replace the specified node with a node produced by the function. /// </summary> /// <param name="node">The node to replace that already exists in the tree.</param> /// <param name="computeReplacement">A function that computes a replacement node. /// The node passed into the compute function includes changes from prior edits. It will not appear as a descendant of the original root.</param> public void ReplaceNode(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> computeReplacement) { CheckNodeInOriginalTreeOrTracked(node); if (computeReplacement == null) { throw new ArgumentNullException(nameof(computeReplacement)); } _allowEditsOnLazilyCreatedTrackedNewNodes = true; _changes.Add(new ReplaceChange(node, computeReplacement, this)); } internal void ReplaceNode(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, IEnumerable<SyntaxNode>> computeReplacement) { CheckNodeInOriginalTreeOrTracked(node); if (computeReplacement == null) { throw new ArgumentNullException(nameof(computeReplacement)); } _allowEditsOnLazilyCreatedTrackedNewNodes = true; _changes.Add(new ReplaceWithCollectionChange(node, computeReplacement, this)); } internal void ReplaceNode<TArgument>(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> computeReplacement, TArgument argument) { CheckNodeInOriginalTreeOrTracked(node); if (computeReplacement == null) { throw new ArgumentNullException(nameof(computeReplacement)); } _allowEditsOnLazilyCreatedTrackedNewNodes = true; _changes.Add(new ReplaceChange<TArgument>(node, computeReplacement, argument, this)); } /// <summary> /// Replace the specified node with a different node. /// </summary> /// <param name="node">The node to replace that already exists in the tree.</param> /// <param name="newNode">The new node that will be placed into the tree in the existing node's location.</param> public void ReplaceNode(SyntaxNode node, SyntaxNode newNode) { CheckNodeInOriginalTreeOrTracked(node); if (node == newNode) { return; } newNode = ApplyTrackingToNewNode(newNode); _changes.Add(new ReplaceChange(node, (n, g) => newNode, this)); } /// <summary> /// Insert the new nodes before the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed before. This must be a node this is contained within a syntax list.</param> /// <param name="newNodes">The nodes to place before the existing node. These nodes must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertBefore(SyntaxNode node, IEnumerable<SyntaxNode> newNodes) { CheckNodeInOriginalTreeOrTracked(node); if (newNodes == null) { throw new ArgumentNullException(nameof(newNodes)); } newNodes = ApplyTrackingToNewNodes(newNodes); _changes.Add(new InsertChange(node, newNodes, isBefore: true)); } /// <summary> /// Insert the new node before the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed before. This must be a node this is contained within a syntax list.</param> /// <param name="newNode">The node to place before the existing node. This node must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertBefore(SyntaxNode node, SyntaxNode newNode) => InsertBefore(node, new[] { newNode }); /// <summary> /// Insert the new nodes after the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed after. This must be a node this is contained within a syntax list.</param> /// <param name="newNodes">The nodes to place after the existing node. These nodes must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertAfter(SyntaxNode node, IEnumerable<SyntaxNode> newNodes) { CheckNodeInOriginalTreeOrTracked(node); if (newNodes == null) { throw new ArgumentNullException(nameof(newNodes)); } newNodes = ApplyTrackingToNewNodes(newNodes); _changes.Add(new InsertChange(node, newNodes, isBefore: false)); } /// <summary> /// Insert the new node after the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed after. This must be a node this is contained within a syntax list.</param> /// <param name="newNode">The node to place after the existing node. This node must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertAfter(SyntaxNode node, SyntaxNode newNode) => this.InsertAfter(node, new[] { newNode }); private void CheckNodeInOriginalTreeOrTracked(SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } if (OriginalRoot.Contains(node)) { // Node is contained in the original tree. return; } if (_allowEditsOnLazilyCreatedTrackedNewNodes) { // This could be a node that is handed to us lazily from one of the prior edits // which support lazy replacement nodes, we conservatively avoid throwing here. // If this was indeed an unsupported node, syntax editor will throw an exception later // when attempting to compute changed root. return; } if (_lazyTrackedNewNodesOpt?.Contains(node) == true) { // Node is one of the new nodes, which is already tracked and supported. return; } throw new ArgumentException(WorkspacesResources.The_node_is_not_part_of_the_tree, nameof(node)); } private abstract class Change { internal readonly SyntaxNode Node; public Change(SyntaxNode node) => this.Node = node; public abstract SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator); } private class NoChange : Change { public NoChange(SyntaxNode node) : base(node) { } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) => root; } private class RemoveChange : Change { private readonly SyntaxRemoveOptions _options; public RemoveChange(SyntaxNode node, SyntaxRemoveOptions options) : base(node) { _options = options; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) => generator.RemoveNode(root, root.GetCurrentNode(this.Node), _options); } private class ReplaceChange : Change { private readonly Func<SyntaxNode, SyntaxGenerator, SyntaxNode?> _modifier; private readonly SyntaxEditor _editor; public ReplaceChange( SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, SyntaxNode?> modifier, SyntaxEditor editor) : base(node) { Contract.ThrowIfNull(node, "Passed in node is null."); _modifier = modifier; _editor = editor; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); if (current is null) { Contract.Fail($"GetCurrentNode returned null with the following node: {this.Node}"); } var newNode = _modifier(current, generator); newNode = _editor.ApplyTrackingToNewNode(newNode); return generator.ReplaceNode(root, current, newNode); } } private class ReplaceWithCollectionChange : Change { private readonly Func<SyntaxNode, SyntaxGenerator, IEnumerable<SyntaxNode>> _modifier; private readonly SyntaxEditor _editor; public ReplaceWithCollectionChange( SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, IEnumerable<SyntaxNode>> modifier, SyntaxEditor editor) : base(node) { _modifier = modifier; _editor = editor; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); if (current is null) { Contract.Fail($"GetCurrentNode returned null with the following node: {this.Node}"); } var newNodes = _modifier(current, generator).ToList(); for (var i = 0; i < newNodes.Count; i++) { newNodes[i] = _editor.ApplyTrackingToNewNode(newNodes[i]); } return SyntaxGenerator.ReplaceNode(root, current, newNodes); } } private class ReplaceChange<TArgument> : Change { private readonly Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> _modifier; private readonly TArgument _argument; private readonly SyntaxEditor _editor; public ReplaceChange( SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> modifier, TArgument argument, SyntaxEditor editor) : base(node) { _modifier = modifier; _argument = argument; _editor = editor; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); if (current is null) { Contract.Fail($"GetCurrentNode returned null with the following node: {this.Node}"); } var newNode = _modifier(current, generator, _argument); newNode = _editor.ApplyTrackingToNewNode(newNode); return generator.ReplaceNode(root, current, newNode); } } private class InsertChange : Change { private readonly List<SyntaxNode> _newNodes; private readonly bool _isBefore; public InsertChange(SyntaxNode node, IEnumerable<SyntaxNode> newNodes, bool isBefore) : base(node) { _newNodes = newNodes.ToList(); _isBefore = isBefore; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { if (_isBefore) { return generator.InsertNodesBefore(root, root.GetCurrentNode(this.Node), _newNodes); } else { return generator.InsertNodesAfter(root, root.GetCurrentNode(this.Node), _newNodes); } } } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Compilers/CSharp/Portable/Syntax/CSharpSyntaxTree.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.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The parsed representation of a C# source document. /// </summary> public abstract partial class CSharpSyntaxTree : SyntaxTree { internal static readonly SyntaxTree Dummy = new DummySyntaxTree(); /// <summary> /// The options used by the parser to produce the syntax tree. /// </summary> public new abstract CSharpParseOptions Options { get; } // REVIEW: I would prefer to not expose CloneAsRoot and make the functionality // internal to CaaS layer, to ensure that for a given SyntaxTree there can not // be multiple trees claiming to be its children. // // However, as long as we provide GetRoot extensibility point on SyntaxTree // the guarantee above cannot be implemented and we have to provide some way for // creating root nodes. // // Therefore I place CloneAsRoot API on SyntaxTree and make it protected to // at least limit its visibility to SyntaxTree extenders. /// <summary> /// Produces a clone of a <see cref="CSharpSyntaxNode"/> which will have current syntax tree as its parent. /// /// Caller must guarantee that if the same instance of <see cref="CSharpSyntaxNode"/> makes multiple calls /// to this function, only one result is observable. /// </summary> /// <typeparam name="T">Type of the syntax node.</typeparam> /// <param name="node">The original syntax node.</param> /// <returns>A clone of the original syntax node that has current <see cref="CSharpSyntaxTree"/> as its parent.</returns> protected T CloneNodeAsRoot<T>(T node) where T : CSharpSyntaxNode { return CSharpSyntaxNode.CloneNodeAsRoot(node, this); } /// <summary> /// Gets the root node of the syntax tree. /// </summary> public new abstract CSharpSyntaxNode GetRoot(CancellationToken cancellationToken = default); /// <summary> /// Gets the root node of the syntax tree if it is already available. /// </summary> public abstract bool TryGetRoot([NotNullWhen(true)] out CSharpSyntaxNode? root); /// <summary> /// Gets the root node of the syntax tree asynchronously. /// </summary> /// <remarks> /// By default, the work associated with this method will be executed immediately on the current thread. /// Implementations that wish to schedule this work differently should override <see cref="GetRootAsync(CancellationToken)"/>. /// </remarks> public new virtual Task<CSharpSyntaxNode> GetRootAsync(CancellationToken cancellationToken = default) { return Task.FromResult(this.TryGetRoot(out CSharpSyntaxNode? node) ? node : this.GetRoot(cancellationToken)); } /// <summary> /// Gets the root of the syntax tree statically typed as <see cref="CompilationUnitSyntax"/>. /// </summary> /// <remarks> /// Ensure that <see cref="SyntaxTree.HasCompilationUnitRoot"/> is true for this tree prior to invoking this method. /// </remarks> /// <exception cref="InvalidCastException">Throws this exception if <see cref="SyntaxTree.HasCompilationUnitRoot"/> is false.</exception> public CompilationUnitSyntax GetCompilationUnitRoot(CancellationToken cancellationToken = default) { return (CompilationUnitSyntax)this.GetRoot(cancellationToken); } /// <summary> /// Determines if two trees are the same, disregarding trivia differences. /// </summary> /// <param name="tree">The tree to compare against.</param> /// <param name="topLevel"> /// If true then the trees are equivalent if the contained nodes and tokens declaring metadata visible symbolic information are equivalent, /// ignoring any differences of nodes inside method bodies or initializer expressions, otherwise all nodes and tokens must be equivalent. /// </param> public override bool IsEquivalentTo(SyntaxTree tree, bool topLevel = false) { return SyntaxFactory.AreEquivalent(this, tree, topLevel); } internal bool HasReferenceDirectives { get { Debug.Assert(HasCompilationUnitRoot); return Options.Kind == SourceCodeKind.Script && GetCompilationUnitRoot().GetReferenceDirectives().Count > 0; } } internal bool HasReferenceOrLoadDirectives { get { Debug.Assert(HasCompilationUnitRoot); if (Options.Kind == SourceCodeKind.Script) { var compilationUnitRoot = GetCompilationUnitRoot(); return compilationUnitRoot.GetReferenceDirectives().Count > 0 || compilationUnitRoot.GetLoadDirectives().Count > 0; } return false; } } #region Preprocessor Symbols private bool _hasDirectives; private InternalSyntax.DirectiveStack _directives; internal void SetDirectiveStack(InternalSyntax.DirectiveStack directives) { _directives = directives; _hasDirectives = true; } private InternalSyntax.DirectiveStack GetDirectives() { if (!_hasDirectives) { var stack = this.GetRoot().CsGreen.ApplyDirectives(default); SetDirectiveStack(stack); } return _directives; } internal bool IsAnyPreprocessorSymbolDefined(ImmutableArray<string> conditionalSymbols) { Debug.Assert(conditionalSymbols != null); foreach (string conditionalSymbol in conditionalSymbols) { if (IsPreprocessorSymbolDefined(conditionalSymbol)) { return true; } } return false; } internal bool IsPreprocessorSymbolDefined(string symbolName) { return IsPreprocessorSymbolDefined(GetDirectives(), symbolName); } private bool IsPreprocessorSymbolDefined(InternalSyntax.DirectiveStack directives, string symbolName) { switch (directives.IsDefined(symbolName)) { case InternalSyntax.DefineState.Defined: return true; case InternalSyntax.DefineState.Undefined: return false; default: return this.Options.PreprocessorSymbols.Contains(symbolName); } } /// <summary> /// Stores positions where preprocessor state changes. Sorted by position. /// The updated state can be found in <see cref="_preprocessorStates"/> array at the same index. /// </summary> private ImmutableArray<int> _preprocessorStateChangePositions; /// <summary> /// Preprocessor states corresponding to positions in <see cref="_preprocessorStateChangePositions"/>. /// </summary> private ImmutableArray<InternalSyntax.DirectiveStack> _preprocessorStates; internal bool IsPreprocessorSymbolDefined(string symbolName, int position) { if (_preprocessorStateChangePositions.IsDefault) { BuildPreprocessorStateChangeMap(); } int searchResult = _preprocessorStateChangePositions.BinarySearch(position); InternalSyntax.DirectiveStack directives; if (searchResult < 0) { searchResult = (~searchResult) - 1; if (searchResult >= 0) { directives = _preprocessorStates[searchResult]; } else { directives = InternalSyntax.DirectiveStack.Empty; } } else { directives = _preprocessorStates[searchResult]; } return IsPreprocessorSymbolDefined(directives, symbolName); } private void BuildPreprocessorStateChangeMap() { InternalSyntax.DirectiveStack currentState = InternalSyntax.DirectiveStack.Empty; var positions = ArrayBuilder<int>.GetInstance(); var states = ArrayBuilder<InternalSyntax.DirectiveStack>.GetInstance(); foreach (DirectiveTriviaSyntax directive in this.GetRoot().GetDirectives(d => { switch (d.Kind()) { case SyntaxKind.IfDirectiveTrivia: case SyntaxKind.ElifDirectiveTrivia: case SyntaxKind.ElseDirectiveTrivia: case SyntaxKind.EndIfDirectiveTrivia: case SyntaxKind.DefineDirectiveTrivia: case SyntaxKind.UndefDirectiveTrivia: return true; default: return false; } })) { currentState = directive.ApplyDirectives(currentState); switch (directive.Kind()) { case SyntaxKind.IfDirectiveTrivia: // #if directive doesn't affect the set of defined/undefined symbols break; case SyntaxKind.ElifDirectiveTrivia: states.Add(currentState); positions.Add(((ElifDirectiveTriviaSyntax)directive).ElifKeyword.SpanStart); break; case SyntaxKind.ElseDirectiveTrivia: states.Add(currentState); positions.Add(((ElseDirectiveTriviaSyntax)directive).ElseKeyword.SpanStart); break; case SyntaxKind.EndIfDirectiveTrivia: states.Add(currentState); positions.Add(((EndIfDirectiveTriviaSyntax)directive).EndIfKeyword.SpanStart); break; case SyntaxKind.DefineDirectiveTrivia: states.Add(currentState); positions.Add(((DefineDirectiveTriviaSyntax)directive).Name.SpanStart); break; case SyntaxKind.UndefDirectiveTrivia: states.Add(currentState); positions.Add(((UndefDirectiveTriviaSyntax)directive).Name.SpanStart); break; default: throw ExceptionUtilities.UnexpectedValue(directive.Kind()); } } #if DEBUG int currentPos = -1; foreach (int pos in positions) { Debug.Assert(currentPos < pos); currentPos = pos; } #endif ImmutableInterlocked.InterlockedInitialize(ref _preprocessorStates, states.ToImmutableAndFree()); ImmutableInterlocked.InterlockedInitialize(ref _preprocessorStateChangePositions, positions.ToImmutableAndFree()); } #endregion #region Factories // The overload that has more parameters is itself obsolete, as an intentional break to allow future // expansion #pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Creates a new syntax tree from a syntax node. /// </summary> public static SyntaxTree Create(CSharpSyntaxNode root, CSharpParseOptions? options = null, string path = "", Encoding? encoding = null) { #pragma warning disable CS0618 // We are calling into the obsolete member as that's the one that still does the real work return Create(root, options, path, encoding, diagnosticOptions: null); #pragma warning restore CS0618 } #pragma warning restore RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Creates a new syntax tree from a syntax node. /// </summary> /// <param name="diagnosticOptions">An obsolete parameter. Diagnostic options should now be passed with <see cref="CompilationOptions.SyntaxTreeOptionsProvider"/></param> /// <param name="isGeneratedCode">An obsolete parameter. It is unused.</param> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree Create( CSharpSyntaxNode root, CSharpParseOptions? options, string path, Encoding? encoding, // obsolete parameter -- unused ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, // obsolete parameter -- unused bool? isGeneratedCode) { if (root == null) { throw new ArgumentNullException(nameof(root)); } var directives = root.Kind() == SyntaxKind.CompilationUnit ? ((CompilationUnitSyntax)root).GetConditionalDirectivesStack() : InternalSyntax.DirectiveStack.Empty; return new ParsedSyntaxTree( textOpt: null, encodingOpt: encoding, checksumAlgorithm: SourceHashAlgorithm.Sha1, path: path, options: options ?? CSharpParseOptions.Default, root: root, directives: directives, diagnosticOptions, cloneRoot: true); } /// <summary> /// Creates a new syntax tree from a syntax node with text that should correspond to the syntax node. /// </summary> /// <remarks>This is used by the ExpressionEvaluator.</remarks> internal static SyntaxTree CreateForDebugger(CSharpSyntaxNode root, SourceText text, CSharpParseOptions options) { Debug.Assert(root != null); return new DebuggerSyntaxTree(root, text, options); } /// <summary> /// <para> /// Internal helper for <see cref="CSharpSyntaxNode"/> class to create a new syntax tree rooted at the given root node. /// This method does not create a clone of the given root, but instead preserves it's reference identity. /// </para> /// <para>NOTE: This method is only intended to be used from <see cref="CSharpSyntaxNode.SyntaxTree"/> property.</para> /// <para>NOTE: Do not use this method elsewhere, instead use <see cref="Create(CSharpSyntaxNode, CSharpParseOptions, string, Encoding)"/> method for creating a syntax tree.</para> /// </summary> internal static SyntaxTree CreateWithoutClone(CSharpSyntaxNode root) { Debug.Assert(root != null); return new ParsedSyntaxTree( textOpt: null, encodingOpt: null, checksumAlgorithm: SourceHashAlgorithm.Sha1, path: "", options: CSharpParseOptions.Default, root: root, directives: InternalSyntax.DirectiveStack.Empty, diagnosticOptions: null, cloneRoot: false); } /// <summary> /// Produces a syntax tree by parsing the source text lazily. The syntax tree is realized when /// <see cref="CSharpSyntaxTree.GetRoot(CancellationToken)"/> is called. /// </summary> internal static SyntaxTree ParseTextLazy( SourceText text, CSharpParseOptions? options = null, string path = "") { return new LazySyntaxTree(text, options ?? CSharpParseOptions.Default, path, diagnosticOptions: null); } // The overload that has more parameters is itself obsolete, as an intentional break to allow future // expansion #pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Produces a syntax tree by parsing the source text. /// </summary> public static SyntaxTree ParseText( string text, CSharpParseOptions? options = null, string path = "", Encoding? encoding = null, CancellationToken cancellationToken = default) { #pragma warning disable CS0618 // We are calling into the obsolete member as that's the one that still does the real work return ParseText(text, options, path, encoding, diagnosticOptions: null, cancellationToken); #pragma warning restore CS0618 } #pragma warning restore RS0027 /// <summary> /// Produces a syntax tree by parsing the source text. /// </summary> /// <param name="diagnosticOptions">An obsolete parameter. Diagnostic options should now be passed with <see cref="CompilationOptions.SyntaxTreeOptionsProvider"/></param> /// <param name="isGeneratedCode">An obsolete parameter. It is unused.</param> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseText( string text, CSharpParseOptions? options, string path, Encoding? encoding, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, bool? isGeneratedCode, CancellationToken cancellationToken) { return ParseText(SourceText.From(text, encoding), options, path, diagnosticOptions, isGeneratedCode, cancellationToken); } // The overload that has more parameters is itself obsolete, as an intentional break to allow future // expansion #pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Produces a syntax tree by parsing the source text. /// </summary> public static SyntaxTree ParseText( SourceText text, CSharpParseOptions? options = null, string path = "", CancellationToken cancellationToken = default) { #pragma warning disable CS0618 // We are calling into the obsolete member as that's the one that still does the real work return ParseText(text, options, path, diagnosticOptions: null, cancellationToken); #pragma warning restore CS0618 } #pragma warning restore RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Produces a syntax tree by parsing the source text. /// </summary> /// <param name="diagnosticOptions">An obsolete parameter. Diagnostic options should now be passed with <see cref="CompilationOptions.SyntaxTreeOptionsProvider"/></param> /// <param name="isGeneratedCode">An obsolete parameter. It is unused.</param> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseText( SourceText text, CSharpParseOptions? options, string path, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, bool? isGeneratedCode, CancellationToken cancellationToken) { if (text == null) { throw new ArgumentNullException(nameof(text)); } options = options ?? CSharpParseOptions.Default; using var lexer = new InternalSyntax.Lexer(text, options); using var parser = new InternalSyntax.LanguageParser(lexer, oldTree: null, changes: null, cancellationToken: cancellationToken); var compilationUnit = (CompilationUnitSyntax)parser.ParseCompilationUnit().CreateRed(); var tree = new ParsedSyntaxTree( text, text.Encoding, text.ChecksumAlgorithm, path, options, compilationUnit, parser.Directives, diagnosticOptions: diagnosticOptions, cloneRoot: true); tree.VerifySource(); return tree; } #endregion #region Changes /// <summary> /// Creates a new syntax based off this tree using a new source text. /// </summary> /// <remarks> /// If the new source text is a minor change from the current source text an incremental parse will occur /// reusing most of the current syntax tree internal data. Otherwise, a full parse will occur using the new /// source text. /// </remarks> public override SyntaxTree WithChangedText(SourceText newText) { // try to find the changes between the old text and the new text. if (this.TryGetText(out SourceText? oldText)) { var changes = newText.GetChangeRanges(oldText); if (changes.Count == 0 && newText == oldText) { return this; } return this.WithChanges(newText, changes); } // if we do not easily know the old text, then specify entire text as changed so we do a full reparse. return this.WithChanges(newText, new[] { new TextChangeRange(new TextSpan(0, this.Length), newText.Length) }); } private SyntaxTree WithChanges(SourceText newText, IReadOnlyList<TextChangeRange> changes) { if (changes == null) { throw new ArgumentNullException(nameof(changes)); } IReadOnlyList<TextChangeRange>? workingChanges = changes; CSharpSyntaxTree? oldTree = this; // if changes is entire text do a full reparse if (workingChanges.Count == 1 && workingChanges[0].Span == new TextSpan(0, this.Length) && workingChanges[0].NewLength == newText.Length) { // parser will do a full parse if we give it no changes workingChanges = null; oldTree = null; } using var lexer = new InternalSyntax.Lexer(newText, this.Options); using var parser = new InternalSyntax.LanguageParser(lexer, oldTree?.GetRoot(), workingChanges); var compilationUnit = (CompilationUnitSyntax)parser.ParseCompilationUnit().CreateRed(); var tree = new ParsedSyntaxTree( newText, newText.Encoding, newText.ChecksumAlgorithm, FilePath, Options, compilationUnit, parser.Directives, #pragma warning disable CS0618 DiagnosticOptions, #pragma warning restore CS0618 cloneRoot: true); tree.VerifySource(changes); return tree; } /// <summary> /// Produces a pessimistic list of spans that denote the regions of text in this tree that /// are changed from the text of the old tree. /// </summary> /// <param name="oldTree">The old tree. Cannot be <c>null</c>.</param> /// <remarks>The list is pessimistic because it may claim more or larger regions than actually changed.</remarks> public override IList<TextSpan> GetChangedSpans(SyntaxTree oldTree) { if (oldTree == null) { throw new ArgumentNullException(nameof(oldTree)); } return SyntaxDiffer.GetPossiblyDifferentTextSpans(oldTree, this); } /// <summary> /// Gets a list of text changes that when applied to the old tree produce this tree. /// </summary> /// <param name="oldTree">The old tree. Cannot be <c>null</c>.</param> /// <remarks>The list of changes may be different than the original changes that produced this tree.</remarks> public override IList<TextChange> GetChanges(SyntaxTree oldTree) { if (oldTree == null) { throw new ArgumentNullException(nameof(oldTree)); } return SyntaxDiffer.GetTextChanges(oldTree, this); } #endregion #region LinePositions and Locations private CSharpLineDirectiveMap GetDirectiveMap() { if (_lazyLineDirectiveMap == null) { // Create the line directive map on demand. Interlocked.CompareExchange(ref _lazyLineDirectiveMap, new CSharpLineDirectiveMap(this), null); } return _lazyLineDirectiveMap; } /// <summary> /// Gets the location in terms of path, line and column for a given span. /// </summary> /// <param name="span">Span within the tree.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// <see cref="FileLinePositionSpan"/> that contains path, line and column information. /// </returns> /// <remarks>The values are not affected by line mapping directives (<c>#line</c>).</remarks> public override FileLinePositionSpan GetLineSpan(TextSpan span, CancellationToken cancellationToken = default) => new(FilePath, GetLinePosition(span.Start, cancellationToken), GetLinePosition(span.End, cancellationToken)); /// <summary> /// Gets the location in terms of path, line and column after applying source line mapping directives (<c>#line</c>). /// </summary> /// <param name="span">Span within the tree.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// <para>A valid <see cref="FileLinePositionSpan"/> that contains path, line and column information.</para> /// <para> /// If the location path is mapped the resulting path is the path specified in the corresponding <c>#line</c>, /// otherwise it's <see cref="SyntaxTree.FilePath"/>. /// </para> /// <para> /// A location path is considered mapped if the first <c>#line</c> directive that precedes it and that /// either specifies an explicit file path or is <c>#line default</c> exists and specifies an explicit path. /// </para> /// </returns> public override FileLinePositionSpan GetMappedLineSpan(TextSpan span, CancellationToken cancellationToken = default) => GetDirectiveMap().TranslateSpan(GetText(cancellationToken), this.FilePath, span); /// <inheritdoc/> public override LineVisibility GetLineVisibility(int position, CancellationToken cancellationToken = default) => GetDirectiveMap().GetLineVisibility(GetText(cancellationToken), position); /// <inheritdoc/> public override IEnumerable<LineMapping> GetLineMappings(CancellationToken cancellationToken = default) { var map = GetDirectiveMap(); Debug.Assert(map.Entries.Length >= 1); return (map.Entries.Length == 1) ? Array.Empty<LineMapping>() : map.GetLineMappings(GetText(cancellationToken).Lines); } /// <summary> /// Gets a <see cref="FileLinePositionSpan"/> for a <see cref="TextSpan"/>. FileLinePositionSpans are used /// primarily for diagnostics and source locations. /// </summary> /// <param name="span">The source <see cref="TextSpan" /> to convert.</param> /// <param name="isHiddenPosition">When the method returns, contains a boolean value indicating whether this span is considered hidden or not.</param> /// <returns>A resulting <see cref="FileLinePositionSpan"/>.</returns> internal override FileLinePositionSpan GetMappedLineSpanAndVisibility(TextSpan span, out bool isHiddenPosition) => GetDirectiveMap().TranslateSpanAndVisibility(GetText(), FilePath, span, out isHiddenPosition); /// <summary> /// Gets a boolean value indicating whether there are any hidden regions in the tree. /// </summary> /// <returns>True if there is at least one hidden region.</returns> public override bool HasHiddenRegions() => GetDirectiveMap().HasAnyHiddenRegions(); /// <summary> /// Given the error code and the source location, get the warning state based on <c>#pragma warning</c> directives. /// </summary> /// <param name="id">Error code.</param> /// <param name="position">Source location.</param> internal PragmaWarningState GetPragmaDirectiveWarningState(string id, int position) { if (_lazyPragmaWarningStateMap == null) { // Create the warning state map on demand. Interlocked.CompareExchange(ref _lazyPragmaWarningStateMap, new CSharpPragmaWarningStateMap(this), null); } return _lazyPragmaWarningStateMap.GetWarningState(id, position); } private NullableContextStateMap GetNullableContextStateMap() { if (_lazyNullableContextStateMap == null) { // Create the #nullable directive map on demand. Interlocked.CompareExchange( ref _lazyNullableContextStateMap, new StrongBox<NullableContextStateMap>(NullableContextStateMap.Create(this)), null); } return _lazyNullableContextStateMap.Value; } internal NullableContextState GetNullableContextState(int position) => GetNullableContextStateMap().GetContextState(position); internal bool? IsNullableAnalysisEnabled(TextSpan span) => GetNullableContextStateMap().IsNullableAnalysisEnabled(span); internal bool IsGeneratedCode(SyntaxTreeOptionsProvider? provider, CancellationToken cancellationToken) { return provider?.IsGenerated(this, cancellationToken) switch { null or GeneratedKind.Unknown => isGeneratedHeuristic(), GeneratedKind kind => kind != GeneratedKind.NotGenerated }; bool isGeneratedHeuristic() { if (_lazyIsGeneratedCode == GeneratedKind.Unknown) { // Create the generated code status on demand bool isGenerated = GeneratedCodeUtilities.IsGeneratedCode( this, isComment: trivia => trivia.Kind() == SyntaxKind.SingleLineCommentTrivia || trivia.Kind() == SyntaxKind.MultiLineCommentTrivia, cancellationToken: default); _lazyIsGeneratedCode = isGenerated ? GeneratedKind.MarkedGenerated : GeneratedKind.NotGenerated; } return _lazyIsGeneratedCode == GeneratedKind.MarkedGenerated; } } private CSharpLineDirectiveMap? _lazyLineDirectiveMap; private CSharpPragmaWarningStateMap? _lazyPragmaWarningStateMap; private StrongBox<NullableContextStateMap>? _lazyNullableContextStateMap; private GeneratedKind _lazyIsGeneratedCode = GeneratedKind.Unknown; private LinePosition GetLinePosition(int position, CancellationToken cancellationToken) => GetText(cancellationToken).Lines.GetLinePosition(position); /// <summary> /// Gets a <see cref="Location"/> for the specified text <paramref name="span"/>. /// </summary> public override Location GetLocation(TextSpan span) { return new SourceLocation(this, span); } #endregion #region Diagnostics /// <summary> /// Gets a list of all the diagnostics in the sub tree that has the specified node as its root. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } return GetDiagnostics(node.Green, node.Position); } private IEnumerable<Diagnostic> GetDiagnostics(GreenNode greenNode, int position) { if (greenNode == null) { throw new InvalidOperationException(); } if (greenNode.ContainsDiagnostics) { return EnumerateDiagnostics(greenNode, position); } return SpecializedCollections.EmptyEnumerable<Diagnostic>(); } private IEnumerable<Diagnostic> EnumerateDiagnostics(GreenNode node, int position) { var enumerator = new SyntaxTreeDiagnosticEnumerator(this, node, position); while (enumerator.MoveNext()) { yield return enumerator.Current; } } /// <summary> /// Gets a list of all the diagnostics associated with the token and any related trivia. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(SyntaxToken token) { if (token.Node == null) { throw new InvalidOperationException(); } return GetDiagnostics(token.Node, token.Position); } /// <summary> /// Gets a list of all the diagnostics associated with the trivia. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(SyntaxTrivia trivia) { if (trivia.UnderlyingNode == null) { throw new InvalidOperationException(); } return GetDiagnostics(trivia.UnderlyingNode, trivia.Position); } /// <summary> /// Gets a list of all the diagnostics in either the sub tree that has the specified node as its root or /// associated with the token and its related trivia. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(SyntaxNodeOrToken nodeOrToken) { if (nodeOrToken.UnderlyingNode == null) { throw new InvalidOperationException(); } return GetDiagnostics(nodeOrToken.UnderlyingNode, nodeOrToken.Position); } /// <summary> /// Gets a list of all the diagnostics in the syntax tree. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(CancellationToken cancellationToken = default) { return this.GetDiagnostics(this.GetRoot(cancellationToken)); } #endregion #region SyntaxTree protected override SyntaxNode GetRootCore(CancellationToken cancellationToken) { return this.GetRoot(cancellationToken); } protected override async Task<SyntaxNode> GetRootAsyncCore(CancellationToken cancellationToken) { return await this.GetRootAsync(cancellationToken).ConfigureAwait(false); } protected override bool TryGetRootCore([NotNullWhen(true)] out SyntaxNode? root) { if (this.TryGetRoot(out CSharpSyntaxNode? node)) { root = node; return true; } else { root = null; return false; } } protected override ParseOptions OptionsCore { get { return this.Options; } } #endregion // 3.3 BACK COMPAT OVERLOAD -- DO NOT MODIFY [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseText( SourceText text, CSharpParseOptions? options, string path, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, CancellationToken cancellationToken) => ParseText(text, options, path, diagnosticOptions, isGeneratedCode: null, cancellationToken); // 3.3 BACK COMPAT OVERLOAD -- DO NOT MODIFY [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseText( string text, CSharpParseOptions? options, string path, Encoding? encoding, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, CancellationToken cancellationToken) => ParseText(text, options, path, encoding, diagnosticOptions, isGeneratedCode: null, cancellationToken); // 3.3 BACK COMPAT OVERLOAD -- DO NOT MODIFY [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree Create( CSharpSyntaxNode root, CSharpParseOptions? options, string path, Encoding? encoding, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions) => Create(root, options, path, encoding, diagnosticOptions, isGeneratedCode: 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.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The parsed representation of a C# source document. /// </summary> public abstract partial class CSharpSyntaxTree : SyntaxTree { internal static readonly SyntaxTree Dummy = new DummySyntaxTree(); /// <summary> /// The options used by the parser to produce the syntax tree. /// </summary> public new abstract CSharpParseOptions Options { get; } // REVIEW: I would prefer to not expose CloneAsRoot and make the functionality // internal to CaaS layer, to ensure that for a given SyntaxTree there can not // be multiple trees claiming to be its children. // // However, as long as we provide GetRoot extensibility point on SyntaxTree // the guarantee above cannot be implemented and we have to provide some way for // creating root nodes. // // Therefore I place CloneAsRoot API on SyntaxTree and make it protected to // at least limit its visibility to SyntaxTree extenders. /// <summary> /// Produces a clone of a <see cref="CSharpSyntaxNode"/> which will have current syntax tree as its parent. /// /// Caller must guarantee that if the same instance of <see cref="CSharpSyntaxNode"/> makes multiple calls /// to this function, only one result is observable. /// </summary> /// <typeparam name="T">Type of the syntax node.</typeparam> /// <param name="node">The original syntax node.</param> /// <returns>A clone of the original syntax node that has current <see cref="CSharpSyntaxTree"/> as its parent.</returns> protected T CloneNodeAsRoot<T>(T node) where T : CSharpSyntaxNode { return CSharpSyntaxNode.CloneNodeAsRoot(node, this); } /// <summary> /// Gets the root node of the syntax tree. /// </summary> public new abstract CSharpSyntaxNode GetRoot(CancellationToken cancellationToken = default); /// <summary> /// Gets the root node of the syntax tree if it is already available. /// </summary> public abstract bool TryGetRoot([NotNullWhen(true)] out CSharpSyntaxNode? root); /// <summary> /// Gets the root node of the syntax tree asynchronously. /// </summary> /// <remarks> /// By default, the work associated with this method will be executed immediately on the current thread. /// Implementations that wish to schedule this work differently should override <see cref="GetRootAsync(CancellationToken)"/>. /// </remarks> public new virtual Task<CSharpSyntaxNode> GetRootAsync(CancellationToken cancellationToken = default) { return Task.FromResult(this.TryGetRoot(out CSharpSyntaxNode? node) ? node : this.GetRoot(cancellationToken)); } /// <summary> /// Gets the root of the syntax tree statically typed as <see cref="CompilationUnitSyntax"/>. /// </summary> /// <remarks> /// Ensure that <see cref="SyntaxTree.HasCompilationUnitRoot"/> is true for this tree prior to invoking this method. /// </remarks> /// <exception cref="InvalidCastException">Throws this exception if <see cref="SyntaxTree.HasCompilationUnitRoot"/> is false.</exception> public CompilationUnitSyntax GetCompilationUnitRoot(CancellationToken cancellationToken = default) { return (CompilationUnitSyntax)this.GetRoot(cancellationToken); } /// <summary> /// Determines if two trees are the same, disregarding trivia differences. /// </summary> /// <param name="tree">The tree to compare against.</param> /// <param name="topLevel"> /// If true then the trees are equivalent if the contained nodes and tokens declaring metadata visible symbolic information are equivalent, /// ignoring any differences of nodes inside method bodies or initializer expressions, otherwise all nodes and tokens must be equivalent. /// </param> public override bool IsEquivalentTo(SyntaxTree tree, bool topLevel = false) { return SyntaxFactory.AreEquivalent(this, tree, topLevel); } internal bool HasReferenceDirectives { get { Debug.Assert(HasCompilationUnitRoot); return Options.Kind == SourceCodeKind.Script && GetCompilationUnitRoot().GetReferenceDirectives().Count > 0; } } internal bool HasReferenceOrLoadDirectives { get { Debug.Assert(HasCompilationUnitRoot); if (Options.Kind == SourceCodeKind.Script) { var compilationUnitRoot = GetCompilationUnitRoot(); return compilationUnitRoot.GetReferenceDirectives().Count > 0 || compilationUnitRoot.GetLoadDirectives().Count > 0; } return false; } } #region Preprocessor Symbols private bool _hasDirectives; private InternalSyntax.DirectiveStack _directives; internal void SetDirectiveStack(InternalSyntax.DirectiveStack directives) { _directives = directives; _hasDirectives = true; } private InternalSyntax.DirectiveStack GetDirectives() { if (!_hasDirectives) { var stack = this.GetRoot().CsGreen.ApplyDirectives(default); SetDirectiveStack(stack); } return _directives; } internal bool IsAnyPreprocessorSymbolDefined(ImmutableArray<string> conditionalSymbols) { Debug.Assert(conditionalSymbols != null); foreach (string conditionalSymbol in conditionalSymbols) { if (IsPreprocessorSymbolDefined(conditionalSymbol)) { return true; } } return false; } internal bool IsPreprocessorSymbolDefined(string symbolName) { return IsPreprocessorSymbolDefined(GetDirectives(), symbolName); } private bool IsPreprocessorSymbolDefined(InternalSyntax.DirectiveStack directives, string symbolName) { switch (directives.IsDefined(symbolName)) { case InternalSyntax.DefineState.Defined: return true; case InternalSyntax.DefineState.Undefined: return false; default: return this.Options.PreprocessorSymbols.Contains(symbolName); } } /// <summary> /// Stores positions where preprocessor state changes. Sorted by position. /// The updated state can be found in <see cref="_preprocessorStates"/> array at the same index. /// </summary> private ImmutableArray<int> _preprocessorStateChangePositions; /// <summary> /// Preprocessor states corresponding to positions in <see cref="_preprocessorStateChangePositions"/>. /// </summary> private ImmutableArray<InternalSyntax.DirectiveStack> _preprocessorStates; internal bool IsPreprocessorSymbolDefined(string symbolName, int position) { if (_preprocessorStateChangePositions.IsDefault) { BuildPreprocessorStateChangeMap(); } int searchResult = _preprocessorStateChangePositions.BinarySearch(position); InternalSyntax.DirectiveStack directives; if (searchResult < 0) { searchResult = (~searchResult) - 1; if (searchResult >= 0) { directives = _preprocessorStates[searchResult]; } else { directives = InternalSyntax.DirectiveStack.Empty; } } else { directives = _preprocessorStates[searchResult]; } return IsPreprocessorSymbolDefined(directives, symbolName); } private void BuildPreprocessorStateChangeMap() { InternalSyntax.DirectiveStack currentState = InternalSyntax.DirectiveStack.Empty; var positions = ArrayBuilder<int>.GetInstance(); var states = ArrayBuilder<InternalSyntax.DirectiveStack>.GetInstance(); foreach (DirectiveTriviaSyntax directive in this.GetRoot().GetDirectives(d => { switch (d.Kind()) { case SyntaxKind.IfDirectiveTrivia: case SyntaxKind.ElifDirectiveTrivia: case SyntaxKind.ElseDirectiveTrivia: case SyntaxKind.EndIfDirectiveTrivia: case SyntaxKind.DefineDirectiveTrivia: case SyntaxKind.UndefDirectiveTrivia: return true; default: return false; } })) { currentState = directive.ApplyDirectives(currentState); switch (directive.Kind()) { case SyntaxKind.IfDirectiveTrivia: // #if directive doesn't affect the set of defined/undefined symbols break; case SyntaxKind.ElifDirectiveTrivia: states.Add(currentState); positions.Add(((ElifDirectiveTriviaSyntax)directive).ElifKeyword.SpanStart); break; case SyntaxKind.ElseDirectiveTrivia: states.Add(currentState); positions.Add(((ElseDirectiveTriviaSyntax)directive).ElseKeyword.SpanStart); break; case SyntaxKind.EndIfDirectiveTrivia: states.Add(currentState); positions.Add(((EndIfDirectiveTriviaSyntax)directive).EndIfKeyword.SpanStart); break; case SyntaxKind.DefineDirectiveTrivia: states.Add(currentState); positions.Add(((DefineDirectiveTriviaSyntax)directive).Name.SpanStart); break; case SyntaxKind.UndefDirectiveTrivia: states.Add(currentState); positions.Add(((UndefDirectiveTriviaSyntax)directive).Name.SpanStart); break; default: throw ExceptionUtilities.UnexpectedValue(directive.Kind()); } } #if DEBUG int currentPos = -1; foreach (int pos in positions) { Debug.Assert(currentPos < pos); currentPos = pos; } #endif ImmutableInterlocked.InterlockedInitialize(ref _preprocessorStates, states.ToImmutableAndFree()); ImmutableInterlocked.InterlockedInitialize(ref _preprocessorStateChangePositions, positions.ToImmutableAndFree()); } #endregion #region Factories // The overload that has more parameters is itself obsolete, as an intentional break to allow future // expansion #pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Creates a new syntax tree from a syntax node. /// </summary> public static SyntaxTree Create(CSharpSyntaxNode root, CSharpParseOptions? options = null, string path = "", Encoding? encoding = null) { #pragma warning disable CS0618 // We are calling into the obsolete member as that's the one that still does the real work return Create(root, options, path, encoding, diagnosticOptions: null); #pragma warning restore CS0618 } #pragma warning restore RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Creates a new syntax tree from a syntax node. /// </summary> /// <param name="diagnosticOptions">An obsolete parameter. Diagnostic options should now be passed with <see cref="CompilationOptions.SyntaxTreeOptionsProvider"/></param> /// <param name="isGeneratedCode">An obsolete parameter. It is unused.</param> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree Create( CSharpSyntaxNode root, CSharpParseOptions? options, string path, Encoding? encoding, // obsolete parameter -- unused ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, // obsolete parameter -- unused bool? isGeneratedCode) { if (root == null) { throw new ArgumentNullException(nameof(root)); } var directives = root.Kind() == SyntaxKind.CompilationUnit ? ((CompilationUnitSyntax)root).GetConditionalDirectivesStack() : InternalSyntax.DirectiveStack.Empty; return new ParsedSyntaxTree( textOpt: null, encodingOpt: encoding, checksumAlgorithm: SourceHashAlgorithm.Sha1, path: path, options: options ?? CSharpParseOptions.Default, root: root, directives: directives, diagnosticOptions, cloneRoot: true); } /// <summary> /// Creates a new syntax tree from a syntax node with text that should correspond to the syntax node. /// </summary> /// <remarks>This is used by the ExpressionEvaluator.</remarks> internal static SyntaxTree CreateForDebugger(CSharpSyntaxNode root, SourceText text, CSharpParseOptions options) { Debug.Assert(root != null); return new DebuggerSyntaxTree(root, text, options); } /// <summary> /// <para> /// Internal helper for <see cref="CSharpSyntaxNode"/> class to create a new syntax tree rooted at the given root node. /// This method does not create a clone of the given root, but instead preserves it's reference identity. /// </para> /// <para>NOTE: This method is only intended to be used from <see cref="CSharpSyntaxNode.SyntaxTree"/> property.</para> /// <para>NOTE: Do not use this method elsewhere, instead use <see cref="Create(CSharpSyntaxNode, CSharpParseOptions, string, Encoding)"/> method for creating a syntax tree.</para> /// </summary> internal static SyntaxTree CreateWithoutClone(CSharpSyntaxNode root) { Debug.Assert(root != null); return new ParsedSyntaxTree( textOpt: null, encodingOpt: null, checksumAlgorithm: SourceHashAlgorithm.Sha1, path: "", options: CSharpParseOptions.Default, root: root, directives: InternalSyntax.DirectiveStack.Empty, diagnosticOptions: null, cloneRoot: false); } /// <summary> /// Produces a syntax tree by parsing the source text lazily. The syntax tree is realized when /// <see cref="CSharpSyntaxTree.GetRoot(CancellationToken)"/> is called. /// </summary> internal static SyntaxTree ParseTextLazy( SourceText text, CSharpParseOptions? options = null, string path = "") { return new LazySyntaxTree(text, options ?? CSharpParseOptions.Default, path, diagnosticOptions: null); } // The overload that has more parameters is itself obsolete, as an intentional break to allow future // expansion #pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Produces a syntax tree by parsing the source text. /// </summary> public static SyntaxTree ParseText( string text, CSharpParseOptions? options = null, string path = "", Encoding? encoding = null, CancellationToken cancellationToken = default) { #pragma warning disable CS0618 // We are calling into the obsolete member as that's the one that still does the real work return ParseText(text, options, path, encoding, diagnosticOptions: null, cancellationToken); #pragma warning restore CS0618 } #pragma warning restore RS0027 /// <summary> /// Produces a syntax tree by parsing the source text. /// </summary> /// <param name="diagnosticOptions">An obsolete parameter. Diagnostic options should now be passed with <see cref="CompilationOptions.SyntaxTreeOptionsProvider"/></param> /// <param name="isGeneratedCode">An obsolete parameter. It is unused.</param> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseText( string text, CSharpParseOptions? options, string path, Encoding? encoding, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, bool? isGeneratedCode, CancellationToken cancellationToken) { return ParseText(SourceText.From(text, encoding), options, path, diagnosticOptions, isGeneratedCode, cancellationToken); } // The overload that has more parameters is itself obsolete, as an intentional break to allow future // expansion #pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Produces a syntax tree by parsing the source text. /// </summary> public static SyntaxTree ParseText( SourceText text, CSharpParseOptions? options = null, string path = "", CancellationToken cancellationToken = default) { #pragma warning disable CS0618 // We are calling into the obsolete member as that's the one that still does the real work return ParseText(text, options, path, diagnosticOptions: null, cancellationToken); #pragma warning restore CS0618 } #pragma warning restore RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads. /// <summary> /// Produces a syntax tree by parsing the source text. /// </summary> /// <param name="diagnosticOptions">An obsolete parameter. Diagnostic options should now be passed with <see cref="CompilationOptions.SyntaxTreeOptionsProvider"/></param> /// <param name="isGeneratedCode">An obsolete parameter. It is unused.</param> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseText( SourceText text, CSharpParseOptions? options, string path, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, bool? isGeneratedCode, CancellationToken cancellationToken) { if (text == null) { throw new ArgumentNullException(nameof(text)); } options = options ?? CSharpParseOptions.Default; using var lexer = new InternalSyntax.Lexer(text, options); using var parser = new InternalSyntax.LanguageParser(lexer, oldTree: null, changes: null, cancellationToken: cancellationToken); var compilationUnit = (CompilationUnitSyntax)parser.ParseCompilationUnit().CreateRed(); var tree = new ParsedSyntaxTree( text, text.Encoding, text.ChecksumAlgorithm, path, options, compilationUnit, parser.Directives, diagnosticOptions: diagnosticOptions, cloneRoot: true); tree.VerifySource(); return tree; } #endregion #region Changes /// <summary> /// Creates a new syntax based off this tree using a new source text. /// </summary> /// <remarks> /// If the new source text is a minor change from the current source text an incremental parse will occur /// reusing most of the current syntax tree internal data. Otherwise, a full parse will occur using the new /// source text. /// </remarks> public override SyntaxTree WithChangedText(SourceText newText) { // try to find the changes between the old text and the new text. if (this.TryGetText(out SourceText? oldText)) { var changes = newText.GetChangeRanges(oldText); if (changes.Count == 0 && newText == oldText) { return this; } return this.WithChanges(newText, changes); } // if we do not easily know the old text, then specify entire text as changed so we do a full reparse. return this.WithChanges(newText, new[] { new TextChangeRange(new TextSpan(0, this.Length), newText.Length) }); } private SyntaxTree WithChanges(SourceText newText, IReadOnlyList<TextChangeRange> changes) { if (changes == null) { throw new ArgumentNullException(nameof(changes)); } IReadOnlyList<TextChangeRange>? workingChanges = changes; CSharpSyntaxTree? oldTree = this; // if changes is entire text do a full reparse if (workingChanges.Count == 1 && workingChanges[0].Span == new TextSpan(0, this.Length) && workingChanges[0].NewLength == newText.Length) { // parser will do a full parse if we give it no changes workingChanges = null; oldTree = null; } using var lexer = new InternalSyntax.Lexer(newText, this.Options); using var parser = new InternalSyntax.LanguageParser(lexer, oldTree?.GetRoot(), workingChanges); var compilationUnit = (CompilationUnitSyntax)parser.ParseCompilationUnit().CreateRed(); var tree = new ParsedSyntaxTree( newText, newText.Encoding, newText.ChecksumAlgorithm, FilePath, Options, compilationUnit, parser.Directives, #pragma warning disable CS0618 DiagnosticOptions, #pragma warning restore CS0618 cloneRoot: true); tree.VerifySource(changes); return tree; } /// <summary> /// Produces a pessimistic list of spans that denote the regions of text in this tree that /// are changed from the text of the old tree. /// </summary> /// <param name="oldTree">The old tree. Cannot be <c>null</c>.</param> /// <remarks>The list is pessimistic because it may claim more or larger regions than actually changed.</remarks> public override IList<TextSpan> GetChangedSpans(SyntaxTree oldTree) { if (oldTree == null) { throw new ArgumentNullException(nameof(oldTree)); } return SyntaxDiffer.GetPossiblyDifferentTextSpans(oldTree, this); } /// <summary> /// Gets a list of text changes that when applied to the old tree produce this tree. /// </summary> /// <param name="oldTree">The old tree. Cannot be <c>null</c>.</param> /// <remarks>The list of changes may be different than the original changes that produced this tree.</remarks> public override IList<TextChange> GetChanges(SyntaxTree oldTree) { if (oldTree == null) { throw new ArgumentNullException(nameof(oldTree)); } return SyntaxDiffer.GetTextChanges(oldTree, this); } #endregion #region LinePositions and Locations private CSharpLineDirectiveMap GetDirectiveMap() { if (_lazyLineDirectiveMap == null) { // Create the line directive map on demand. Interlocked.CompareExchange(ref _lazyLineDirectiveMap, new CSharpLineDirectiveMap(this), null); } return _lazyLineDirectiveMap; } /// <summary> /// Gets the location in terms of path, line and column for a given span. /// </summary> /// <param name="span">Span within the tree.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// <see cref="FileLinePositionSpan"/> that contains path, line and column information. /// </returns> /// <remarks>The values are not affected by line mapping directives (<c>#line</c>).</remarks> public override FileLinePositionSpan GetLineSpan(TextSpan span, CancellationToken cancellationToken = default) => new(FilePath, GetLinePosition(span.Start, cancellationToken), GetLinePosition(span.End, cancellationToken)); /// <summary> /// Gets the location in terms of path, line and column after applying source line mapping directives (<c>#line</c>). /// </summary> /// <param name="span">Span within the tree.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns> /// <para>A valid <see cref="FileLinePositionSpan"/> that contains path, line and column information.</para> /// <para> /// If the location path is mapped the resulting path is the path specified in the corresponding <c>#line</c>, /// otherwise it's <see cref="SyntaxTree.FilePath"/>. /// </para> /// <para> /// A location path is considered mapped if the first <c>#line</c> directive that precedes it and that /// either specifies an explicit file path or is <c>#line default</c> exists and specifies an explicit path. /// </para> /// </returns> public override FileLinePositionSpan GetMappedLineSpan(TextSpan span, CancellationToken cancellationToken = default) => GetDirectiveMap().TranslateSpan(GetText(cancellationToken), this.FilePath, span); /// <inheritdoc/> public override LineVisibility GetLineVisibility(int position, CancellationToken cancellationToken = default) => GetDirectiveMap().GetLineVisibility(GetText(cancellationToken), position); /// <inheritdoc/> public override IEnumerable<LineMapping> GetLineMappings(CancellationToken cancellationToken = default) { var map = GetDirectiveMap(); Debug.Assert(map.Entries.Length >= 1); return (map.Entries.Length == 1) ? Array.Empty<LineMapping>() : map.GetLineMappings(GetText(cancellationToken).Lines); } /// <summary> /// Gets a <see cref="FileLinePositionSpan"/> for a <see cref="TextSpan"/>. FileLinePositionSpans are used /// primarily for diagnostics and source locations. /// </summary> /// <param name="span">The source <see cref="TextSpan" /> to convert.</param> /// <param name="isHiddenPosition">When the method returns, contains a boolean value indicating whether this span is considered hidden or not.</param> /// <returns>A resulting <see cref="FileLinePositionSpan"/>.</returns> internal override FileLinePositionSpan GetMappedLineSpanAndVisibility(TextSpan span, out bool isHiddenPosition) => GetDirectiveMap().TranslateSpanAndVisibility(GetText(), FilePath, span, out isHiddenPosition); /// <summary> /// Gets a boolean value indicating whether there are any hidden regions in the tree. /// </summary> /// <returns>True if there is at least one hidden region.</returns> public override bool HasHiddenRegions() => GetDirectiveMap().HasAnyHiddenRegions(); /// <summary> /// Given the error code and the source location, get the warning state based on <c>#pragma warning</c> directives. /// </summary> /// <param name="id">Error code.</param> /// <param name="position">Source location.</param> internal PragmaWarningState GetPragmaDirectiveWarningState(string id, int position) { if (_lazyPragmaWarningStateMap == null) { // Create the warning state map on demand. Interlocked.CompareExchange(ref _lazyPragmaWarningStateMap, new CSharpPragmaWarningStateMap(this), null); } return _lazyPragmaWarningStateMap.GetWarningState(id, position); } private NullableContextStateMap GetNullableContextStateMap() { if (_lazyNullableContextStateMap == null) { // Create the #nullable directive map on demand. Interlocked.CompareExchange( ref _lazyNullableContextStateMap, new StrongBox<NullableContextStateMap>(NullableContextStateMap.Create(this)), null); } return _lazyNullableContextStateMap.Value; } internal NullableContextState GetNullableContextState(int position) => GetNullableContextStateMap().GetContextState(position); internal bool? IsNullableAnalysisEnabled(TextSpan span) => GetNullableContextStateMap().IsNullableAnalysisEnabled(span); internal bool IsGeneratedCode(SyntaxTreeOptionsProvider? provider, CancellationToken cancellationToken) { return provider?.IsGenerated(this, cancellationToken) switch { null or GeneratedKind.Unknown => isGeneratedHeuristic(), GeneratedKind kind => kind != GeneratedKind.NotGenerated }; bool isGeneratedHeuristic() { if (_lazyIsGeneratedCode == GeneratedKind.Unknown) { // Create the generated code status on demand bool isGenerated = GeneratedCodeUtilities.IsGeneratedCode( this, isComment: trivia => trivia.Kind() == SyntaxKind.SingleLineCommentTrivia || trivia.Kind() == SyntaxKind.MultiLineCommentTrivia, cancellationToken: default); _lazyIsGeneratedCode = isGenerated ? GeneratedKind.MarkedGenerated : GeneratedKind.NotGenerated; } return _lazyIsGeneratedCode == GeneratedKind.MarkedGenerated; } } private CSharpLineDirectiveMap? _lazyLineDirectiveMap; private CSharpPragmaWarningStateMap? _lazyPragmaWarningStateMap; private StrongBox<NullableContextStateMap>? _lazyNullableContextStateMap; private GeneratedKind _lazyIsGeneratedCode = GeneratedKind.Unknown; private LinePosition GetLinePosition(int position, CancellationToken cancellationToken) => GetText(cancellationToken).Lines.GetLinePosition(position); /// <summary> /// Gets a <see cref="Location"/> for the specified text <paramref name="span"/>. /// </summary> public override Location GetLocation(TextSpan span) { return new SourceLocation(this, span); } #endregion #region Diagnostics /// <summary> /// Gets a list of all the diagnostics in the sub tree that has the specified node as its root. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(SyntaxNode node) { if (node == null) { throw new ArgumentNullException(nameof(node)); } return GetDiagnostics(node.Green, node.Position); } private IEnumerable<Diagnostic> GetDiagnostics(GreenNode greenNode, int position) { if (greenNode == null) { throw new InvalidOperationException(); } if (greenNode.ContainsDiagnostics) { return EnumerateDiagnostics(greenNode, position); } return SpecializedCollections.EmptyEnumerable<Diagnostic>(); } private IEnumerable<Diagnostic> EnumerateDiagnostics(GreenNode node, int position) { var enumerator = new SyntaxTreeDiagnosticEnumerator(this, node, position); while (enumerator.MoveNext()) { yield return enumerator.Current; } } /// <summary> /// Gets a list of all the diagnostics associated with the token and any related trivia. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(SyntaxToken token) { if (token.Node == null) { throw new InvalidOperationException(); } return GetDiagnostics(token.Node, token.Position); } /// <summary> /// Gets a list of all the diagnostics associated with the trivia. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(SyntaxTrivia trivia) { if (trivia.UnderlyingNode == null) { throw new InvalidOperationException(); } return GetDiagnostics(trivia.UnderlyingNode, trivia.Position); } /// <summary> /// Gets a list of all the diagnostics in either the sub tree that has the specified node as its root or /// associated with the token and its related trivia. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(SyntaxNodeOrToken nodeOrToken) { if (nodeOrToken.UnderlyingNode == null) { throw new InvalidOperationException(); } return GetDiagnostics(nodeOrToken.UnderlyingNode, nodeOrToken.Position); } /// <summary> /// Gets a list of all the diagnostics in the syntax tree. /// </summary> /// <remarks> /// This method does not filter diagnostics based on <c>#pragma</c>s and compiler options /// like /nowarn, /warnaserror etc. /// </remarks> public override IEnumerable<Diagnostic> GetDiagnostics(CancellationToken cancellationToken = default) { return this.GetDiagnostics(this.GetRoot(cancellationToken)); } #endregion #region SyntaxTree protected override SyntaxNode GetRootCore(CancellationToken cancellationToken) { return this.GetRoot(cancellationToken); } protected override async Task<SyntaxNode> GetRootAsyncCore(CancellationToken cancellationToken) { return await this.GetRootAsync(cancellationToken).ConfigureAwait(false); } protected override bool TryGetRootCore([NotNullWhen(true)] out SyntaxNode? root) { if (this.TryGetRoot(out CSharpSyntaxNode? node)) { root = node; return true; } else { root = null; return false; } } protected override ParseOptions OptionsCore { get { return this.Options; } } #endregion // 3.3 BACK COMPAT OVERLOAD -- DO NOT MODIFY [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseText( SourceText text, CSharpParseOptions? options, string path, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, CancellationToken cancellationToken) => ParseText(text, options, path, diagnosticOptions, isGeneratedCode: null, cancellationToken); // 3.3 BACK COMPAT OVERLOAD -- DO NOT MODIFY [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree ParseText( string text, CSharpParseOptions? options, string path, Encoding? encoding, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions, CancellationToken cancellationToken) => ParseText(text, options, path, encoding, diagnosticOptions, isGeneratedCode: null, cancellationToken); // 3.3 BACK COMPAT OVERLOAD -- DO NOT MODIFY [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)] public static SyntaxTree Create( CSharpSyntaxNode root, CSharpParseOptions? options, string path, Encoding? encoding, ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions) => Create(root, options, path, encoding, diagnosticOptions, isGeneratedCode: null); } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/EditorFeatures/DiagnosticsTestUtilities/Diagnostics/AbstractSuppressionAllCodeTests.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.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { [UseExportProvider] public abstract class AbstractSuppressionAllCodeTests : IEqualityComparer<Diagnostic> { protected abstract TestWorkspace CreateWorkspaceFromFile(string definition, ParseOptions parseOptions); internal abstract Tuple<Analyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace); protected Task TestPragmaAsync(string code, ParseOptions options, Func<string, bool> verifier) { var set = new HashSet<ValueTuple<SyntaxToken, SyntaxToken>>(); return TestPragmaOrAttributeAsync(code, options, pragma: true, digInto: n => true, verifier: verifier, fixChecker: c => { var fix = (AbstractSuppressionCodeFixProvider.PragmaWarningCodeAction)c; var tuple = ValueTuple.Create(fix.StartToken_TestOnly, fix.EndToken_TestOnly); if (set.Contains(tuple)) { return true; } set.Add(tuple); return false; }); } protected Task TestSuppressionWithAttributeAsync(string code, ParseOptions options, Func<SyntaxNode, bool> digInto, Func<string, bool> verifier) { var set = new HashSet<ISymbol>(); return TestPragmaOrAttributeAsync(code, options, pragma: false, digInto: digInto, verifier: verifier, fixChecker: c => { var fix = (AbstractSuppressionCodeFixProvider.GlobalSuppressMessageCodeAction)c; if (set.Contains(fix.TargetSymbol_TestOnly)) { return true; } set.Add(fix.TargetSymbol_TestOnly); return false; }); } protected async Task TestPragmaOrAttributeAsync( string code, ParseOptions options, bool pragma, Func<SyntaxNode, bool> digInto, Func<string, bool> verifier, Func<CodeAction, bool> fixChecker) { using (var workspace = CreateWorkspaceFromFile(code, options)) { var (analyzer, fixer) = CreateDiagnosticProviderAndFixer(workspace); var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); var root = document.GetSyntaxRootAsync().GetAwaiter().GetResult(); var existingDiagnostics = root.GetDiagnostics().ToArray(); var descendants = root.DescendantNodesAndSelf(digInto).ToImmutableArray(); analyzer.AllNodes = descendants; var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(workspace, document, root.FullSpan); foreach (var diagnostic in diagnostics) { if (!fixer.IsFixableDiagnostic(diagnostic)) { continue; } var fixes = fixer.GetFixesAsync(document, diagnostic.Location.SourceSpan, SpecializedCollections.SingletonEnumerable(diagnostic), CancellationToken.None).GetAwaiter().GetResult(); if (fixes == null || fixes.Count() <= 0) { continue; } var fix = GetFix(fixes.Select(f => f.Action), pragma); if (fix == null) { continue; } // already same fix has been tested if (fixChecker(fix)) { continue; } var operations = fix.GetOperationsAsync(CancellationToken.None).GetAwaiter().GetResult(); var applyChangesOperation = operations.OfType<ApplyChangesOperation>().Single(); var newDocument = applyChangesOperation.ChangedSolution.Projects.Single().Documents.Single(); var newTree = newDocument.GetSyntaxTreeAsync().GetAwaiter().GetResult(); var newText = newTree.GetText().ToString(); Assert.True(verifier(newText)); var newDiagnostics = newTree.GetDiagnostics(); Assert.Equal(0, existingDiagnostics.Except(newDiagnostics, this).Count()); } } } private static CodeAction GetFix(IEnumerable<CodeAction> fixes, bool pragma) { if (pragma) { return fixes.FirstOrDefault(f => f is AbstractSuppressionCodeFixProvider.PragmaWarningCodeAction); } return fixes.OfType<AbstractSuppressionCodeFixProvider.GlobalSuppressMessageCodeAction>().FirstOrDefault(); } public bool Equals(Diagnostic x, Diagnostic y) => x.Id == y.Id && x.Descriptor.Category == y.Descriptor.Category; public int GetHashCode(Diagnostic obj) => Hash.Combine(obj.Id, obj.Descriptor.Category.GetHashCode()); internal class Analyzer : DiagnosticAnalyzer, IBuiltInAnalyzer { private readonly DiagnosticDescriptor _descriptor = new DiagnosticDescriptor("TestId", "Test", "Test", "Test", DiagnosticSeverity.Warning, isEnabledByDefault: true); public CodeActionRequestPriority RequestPriority => CodeActionRequestPriority.Normal; public bool OpenFileOnly(CodeAnalysis.Options.OptionSet options) => false; public ImmutableArray<SyntaxNode> AllNodes { get; set; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(_descriptor); } } public DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis; public override void Initialize(AnalysisContext analysisContext) { analysisContext.RegisterSyntaxTreeAction( context => { foreach (var node in AllNodes) { context.ReportDiagnostic(Diagnostic.Create(_descriptor, node.GetLocation())); } }); } } } }
// Licensed to the .NET Foundation under one or more 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.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests.Diagnostics; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics { [UseExportProvider] public abstract class AbstractSuppressionAllCodeTests : IEqualityComparer<Diagnostic> { protected abstract TestWorkspace CreateWorkspaceFromFile(string definition, ParseOptions parseOptions); internal abstract Tuple<Analyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace); protected Task TestPragmaAsync(string code, ParseOptions options, Func<string, bool> verifier) { var set = new HashSet<ValueTuple<SyntaxToken, SyntaxToken>>(); return TestPragmaOrAttributeAsync(code, options, pragma: true, digInto: n => true, verifier: verifier, fixChecker: c => { var fix = (AbstractSuppressionCodeFixProvider.PragmaWarningCodeAction)c; var tuple = ValueTuple.Create(fix.StartToken_TestOnly, fix.EndToken_TestOnly); if (set.Contains(tuple)) { return true; } set.Add(tuple); return false; }); } protected Task TestSuppressionWithAttributeAsync(string code, ParseOptions options, Func<SyntaxNode, bool> digInto, Func<string, bool> verifier) { var set = new HashSet<ISymbol>(); return TestPragmaOrAttributeAsync(code, options, pragma: false, digInto: digInto, verifier: verifier, fixChecker: c => { var fix = (AbstractSuppressionCodeFixProvider.GlobalSuppressMessageCodeAction)c; if (set.Contains(fix.TargetSymbol_TestOnly)) { return true; } set.Add(fix.TargetSymbol_TestOnly); return false; }); } protected async Task TestPragmaOrAttributeAsync( string code, ParseOptions options, bool pragma, Func<SyntaxNode, bool> digInto, Func<string, bool> verifier, Func<CodeAction, bool> fixChecker) { using (var workspace = CreateWorkspaceFromFile(code, options)) { var (analyzer, fixer) = CreateDiagnosticProviderAndFixer(workspace); var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer)); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var document = workspace.CurrentSolution.Projects.Single().Documents.Single(); var root = document.GetSyntaxRootAsync().GetAwaiter().GetResult(); var existingDiagnostics = root.GetDiagnostics().ToArray(); var descendants = root.DescendantNodesAndSelf(digInto).ToImmutableArray(); analyzer.AllNodes = descendants; var diagnostics = await DiagnosticProviderTestUtilities.GetAllDiagnosticsAsync(workspace, document, root.FullSpan); foreach (var diagnostic in diagnostics) { if (!fixer.IsFixableDiagnostic(diagnostic)) { continue; } var fixes = fixer.GetFixesAsync(document, diagnostic.Location.SourceSpan, SpecializedCollections.SingletonEnumerable(diagnostic), CancellationToken.None).GetAwaiter().GetResult(); if (fixes == null || fixes.Count() <= 0) { continue; } var fix = GetFix(fixes.Select(f => f.Action), pragma); if (fix == null) { continue; } // already same fix has been tested if (fixChecker(fix)) { continue; } var operations = fix.GetOperationsAsync(CancellationToken.None).GetAwaiter().GetResult(); var applyChangesOperation = operations.OfType<ApplyChangesOperation>().Single(); var newDocument = applyChangesOperation.ChangedSolution.Projects.Single().Documents.Single(); var newTree = newDocument.GetSyntaxTreeAsync().GetAwaiter().GetResult(); var newText = newTree.GetText().ToString(); Assert.True(verifier(newText)); var newDiagnostics = newTree.GetDiagnostics(); Assert.Equal(0, existingDiagnostics.Except(newDiagnostics, this).Count()); } } } private static CodeAction GetFix(IEnumerable<CodeAction> fixes, bool pragma) { if (pragma) { return fixes.FirstOrDefault(f => f is AbstractSuppressionCodeFixProvider.PragmaWarningCodeAction); } return fixes.OfType<AbstractSuppressionCodeFixProvider.GlobalSuppressMessageCodeAction>().FirstOrDefault(); } public bool Equals(Diagnostic x, Diagnostic y) => x.Id == y.Id && x.Descriptor.Category == y.Descriptor.Category; public int GetHashCode(Diagnostic obj) => Hash.Combine(obj.Id, obj.Descriptor.Category.GetHashCode()); internal class Analyzer : DiagnosticAnalyzer, IBuiltInAnalyzer { private readonly DiagnosticDescriptor _descriptor = new DiagnosticDescriptor("TestId", "Test", "Test", "Test", DiagnosticSeverity.Warning, isEnabledByDefault: true); public CodeActionRequestPriority RequestPriority => CodeActionRequestPriority.Normal; public bool OpenFileOnly(CodeAnalysis.Options.OptionSet options) => false; public ImmutableArray<SyntaxNode> AllNodes { get; set; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(_descriptor); } } public DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SyntaxTreeWithoutSemanticsAnalysis; public override void Initialize(AnalysisContext analysisContext) { analysisContext.RegisterSyntaxTreeAction( context => { foreach (var node in AllNodes) { context.ReportDiagnostic(Diagnostic.Create(_descriptor, node.GetLocation())); } }); } } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/EditorFeatures/VisualBasicTest/InvertIf/InvertMultiLineIfTests.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.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.InvertIf Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.InvertIf Public Class InvertMultiLineIfTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicInvertMultiLineIfCodeRefactoringProvider() End Function Public Async Function TestFixOneAsync(initial As String, expected As String) As Task Await TestInRegularAndScriptAsync(CreateTreeText(initial), CreateTreeText(expected)) End Function Public Shared Function CreateTreeText(initial As String) As String Return " Module Module1 Sub Main() Dim a As Boolean = True Dim b As Boolean = True Dim c As Boolean = True Dim d As Boolean = True " + initial + " End Sub Private Sub aMethod() End Sub Private Sub bMethod() End Sub Private Sub cMethod() End Sub Private Sub dMethod() End Sub End Module " End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMultiLineIdentifier() As Task Await TestFixOneAsync( " [||]If a Then aMethod() Else bMethod() End If ", " If Not a Then bMethod() Else aMethod() End If ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestElseIf() As Task Await TestMissingInRegularAndScriptAsync( " Sub Main() If a Then aMethod() [||]ElseIf b Then bMethod() Else cMethod() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestKeepElseIfKeyword() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() If a Then aMethod() [||]ElseIf b Then bMethod() Else cMethod() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMissingOnIfElseIfElse() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() I[||]f a Then aMethod() Else If b Then bMethod() Else cMethod() End If End Sub End Module") End Function <WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestSelection() As Task Await TestFixOneAsync( " [|If a Then aMethod() Else bMethod() End If|] ", " If Not a Then bMethod() Else aMethod() End If ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestDoesNotOverlapHiddenPosition1() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() #End ExternalSource goo() #ExternalSource File.vb 1 [||]If a Then aMethod() Else bMethod() End If End Sub End Module", "Module Program Sub Main() #End ExternalSource goo() #ExternalSource File.vb 1 If Not a Then bMethod() Else aMethod() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestDoesNotOverlapHiddenPosition2() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() #ExternalSource File.vb 1 [||]If a Then aMethod() Else bMethod() End If #End ExternalSource End Sub End Module", "Module Program Sub Main() #ExternalSource File.vb 1 If Not a Then bMethod() Else aMethod() End If #End ExternalSource End Sub End Module") End Function <WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMissingOnOverlapsHiddenPosition1() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() [||]If a Then #ExternalSource File.vb 1 aMethod() #End ExternalSource Else bMethod() End If End Sub End Module") End Function <WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMissingOnOverlapsHiddenPosition2() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() If a Then aMethod() [||]Else If b Then #ExternalSource File.vb 1 bMethod() #End ExternalSource Else cMethod() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMissingOnOverlapsHiddenPosition3() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() [||]If a Then aMethod() #ExternalSource File.vb 1 Else If b Then bMethod() #End ExternalSource Else cMethod() End If End Sub End Module") End Function <WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMissingOnOverlapsHiddenPosition4() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() [||]If a Then aMethod() Else #ExternalSource File.vb 1 bMethod() #End ExternalSource End If End Sub End Module") End Function <WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMissingOnOverlapsHiddenPosition5() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() [||]If a Then #ExternalSource File.vb 1 aMethod() Else bMethod() #End ExternalSource End If End Sub End Module") End Function <WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMissingOnOverlapsHiddenPosition6() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() [||]If a Then aMethod() #ExternalSource File.vb 1 Else #End ExternalSource bMethod() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMultipleStatementsMultiLineIfBlock() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() [||]If a Then goo() bar() Else you() too() End If End Sub End Module", "Module Program Sub Main() If Not a Then you() too() Else goo() bar() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestTriviaAfterMultiLineIfBlock() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() [||]If a Then aMethod() Else bMethod() End If ' I will stay put End Sub End Module", "Module Program Sub Main() If Not a Then bMethod() Else aMethod() End If ' I will stay put End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestKeepExplicitLineContinuationTriviaMethod() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() I[||]f a And b _ Or c Then aMethod() Else bMethod() End If End Sub End Module", "Module Program Sub Main() If (Not a Or Not b) _ And Not c Then bMethod() Else aMethod() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestKeepTriviaInStatementsInMultiLineIfBlock() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() [||]If a Then aMethod() Else bMethod() End If End Sub End Module", "Module Program Sub Main() If Not a Then bMethod() Else aMethod() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestSimplifyToLengthEqualsZero() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim x As String [||]If x.Length > 0 Then GreaterThanZero() Else EqualsZero() End If End Sub End Module", "Module Program Sub Main(args As String()) Dim x As String If x.Length = 0 Then EqualsZero() Else GreaterThanZero() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestSimplifyToLengthEqualsZero2() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim x() As String [||]If x.Length > 0 Then GreaterThanZero() Else EqualsZero() End If End Sub End Module", "Module Program Sub Main(args As String()) Dim x() As String If x.Length = 0 Then EqualsZero() Else GreaterThanZero() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestSimplifyToLengthEqualsZero4() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim x() As String [||]If x.Length > 0x0 Then GreaterThanZero() Else EqualsZero() End If End Sub End Module", "Module Program Sub Main(args As String()) Dim x() As String If x.Length = 0x0 Then EqualsZero() Else GreaterThanZero() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestSimplifyToLengthEqualsZero5() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim x As String [||]If 0 < x.Length Then GreaterThanZero() Else EqualsZero() End If End Sub End Module", "Module Program Sub Main(args As String()) Dim x As String If 0 = x.Length Then EqualsZero() Else GreaterThanZero() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestDoesNotSimplifyToLengthEqualsZero() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim x As String [||]If x.Length >= 0 Then aMethod() Else bMethod() End If End Sub End Module", "Module Program Sub Main(args As String()) Dim x As String If x.Length < 0 Then bMethod() Else aMethod() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestDoesNotSimplifyToLengthEqualsZero2() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim x As String [||]If x.Length > 0.0 Then aMethod() Else bMethod() End If End Sub End Module", "Module Program Sub Main(args As String()) Dim x As String If x.Length <= 0.0 Then bMethod() Else aMethod() End If End Sub End Module") End Function <WorkItem(529748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529748")> <WorkItem(530593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530593")> <WpfFact(Skip:="Bug 530593"), Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestColonAfterSingleLineIfWithEmptyElse() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() ' Invert If I[||]f False Then Return Else : Console.WriteLine(1) End Sub End Module", "Module Program Sub Main() ' Invert If If True Then Else Return Console.WriteLine(1) End Sub End Module") End Function <WorkItem(529756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529756")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestOnlyOnElseIf() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main(args As String()) If False Then Return ElseIf True [||]Then Console.WriteLine(""b"") Else Console.WriteLine(""a"") End If End Sub End Module") End Function <WorkItem(529756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529756")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestOnConditionOfMultiLineIfStatement() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) If [||]False Then Return Else Console.WriteLine(""a"") End If End Sub End Module", "Module Program Sub Main(args As String()) If [||]True Then Console.WriteLine(""a"") Else Return End If End Sub End Module") End Function <WorkItem(531474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531474")> <WpfFact(Skip:="531474"), Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestDoNotRemoveTypeCharactersDuringComplexification() As Task Dim markup = <File> Imports System Module Program Sub Main() Goo(Function(take) [||]If True Then Console.WriteLine("true") Else Console.WriteLine("false") take$.ToString() Return Function() 1 End Function) End Sub Sub Goo(Of T)(x As Func(Of String, T)) End Sub Sub Goo(Of T)(x As Func(Of Integer, T)) End Sub End Module </File> Dim expected = <File> Imports System Module Program Sub Main() Goo(Function(take) If False Then Console.WriteLine("false") Else Console.WriteLine("true") take$.ToString() Return Function() 1 End Function) End Sub Sub Goo(Of T)(x As Func(Of String, T)) End Sub Sub Goo(Of T)(x As Func(Of Integer, T)) End Sub End Module </File> Await TestAsync(markup, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function InvertIfWithoutStatements() As Task Await TestInRegularAndScriptAsync( "class C sub M(x as String) [||]If x = ""a"" Then Else DoSomething() End If end sub sub DoSomething() end sub end class", "class C sub M(x as String) If x <> ""a"" Then DoSomething() End If end sub sub DoSomething() end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function InvertIfWithOnlyComment() As Task Await TestInRegularAndScriptAsync( "class C sub M(x as String) [||]If x = ""a"" Then ' A comment in a blank if statement Else DoSomething() End If end sub sub DoSomething() end sub end class", "class C sub M(x as String) If x <> ""a"" Then DoSomething() Else ' A comment in a blank if statement End If end sub sub DoSomething() end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function InvertIfWithoutElse() As Task Await TestInRegularAndScriptAsync( "class C sub M(x as String) [||]If x = ""a"" Then ' Comment x += 1 End If end sub end class", "class C sub M(x as String) If x <> ""a"" Then Return End If ' Comment x += 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.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.InvertIf Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.InvertIf Public Class InvertMultiLineIfTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicInvertMultiLineIfCodeRefactoringProvider() End Function Public Async Function TestFixOneAsync(initial As String, expected As String) As Task Await TestInRegularAndScriptAsync(CreateTreeText(initial), CreateTreeText(expected)) End Function Public Shared Function CreateTreeText(initial As String) As String Return " Module Module1 Sub Main() Dim a As Boolean = True Dim b As Boolean = True Dim c As Boolean = True Dim d As Boolean = True " + initial + " End Sub Private Sub aMethod() End Sub Private Sub bMethod() End Sub Private Sub cMethod() End Sub Private Sub dMethod() End Sub End Module " End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMultiLineIdentifier() As Task Await TestFixOneAsync( " [||]If a Then aMethod() Else bMethod() End If ", " If Not a Then bMethod() Else aMethod() End If ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestElseIf() As Task Await TestMissingInRegularAndScriptAsync( " Sub Main() If a Then aMethod() [||]ElseIf b Then bMethod() Else cMethod() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestKeepElseIfKeyword() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() If a Then aMethod() [||]ElseIf b Then bMethod() Else cMethod() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMissingOnIfElseIfElse() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() I[||]f a Then aMethod() Else If b Then bMethod() Else cMethod() End If End Sub End Module") End Function <WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestSelection() As Task Await TestFixOneAsync( " [|If a Then aMethod() Else bMethod() End If|] ", " If Not a Then bMethod() Else aMethod() End If ") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestDoesNotOverlapHiddenPosition1() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() #End ExternalSource goo() #ExternalSource File.vb 1 [||]If a Then aMethod() Else bMethod() End If End Sub End Module", "Module Program Sub Main() #End ExternalSource goo() #ExternalSource File.vb 1 If Not a Then bMethod() Else aMethod() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestDoesNotOverlapHiddenPosition2() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() #ExternalSource File.vb 1 [||]If a Then aMethod() Else bMethod() End If #End ExternalSource End Sub End Module", "Module Program Sub Main() #ExternalSource File.vb 1 If Not a Then bMethod() Else aMethod() End If #End ExternalSource End Sub End Module") End Function <WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMissingOnOverlapsHiddenPosition1() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() [||]If a Then #ExternalSource File.vb 1 aMethod() #End ExternalSource Else bMethod() End If End Sub End Module") End Function <WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMissingOnOverlapsHiddenPosition2() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() If a Then aMethod() [||]Else If b Then #ExternalSource File.vb 1 bMethod() #End ExternalSource Else cMethod() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMissingOnOverlapsHiddenPosition3() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() [||]If a Then aMethod() #ExternalSource File.vb 1 Else If b Then bMethod() #End ExternalSource Else cMethod() End If End Sub End Module") End Function <WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMissingOnOverlapsHiddenPosition4() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() [||]If a Then aMethod() Else #ExternalSource File.vb 1 bMethod() #End ExternalSource End If End Sub End Module") End Function <WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMissingOnOverlapsHiddenPosition5() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() [||]If a Then #ExternalSource File.vb 1 aMethod() Else bMethod() #End ExternalSource End If End Sub End Module") End Function <WorkItem(529624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529624")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMissingOnOverlapsHiddenPosition6() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main() [||]If a Then aMethod() #ExternalSource File.vb 1 Else #End ExternalSource bMethod() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestMultipleStatementsMultiLineIfBlock() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() [||]If a Then goo() bar() Else you() too() End If End Sub End Module", "Module Program Sub Main() If Not a Then you() too() Else goo() bar() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestTriviaAfterMultiLineIfBlock() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() [||]If a Then aMethod() Else bMethod() End If ' I will stay put End Sub End Module", "Module Program Sub Main() If Not a Then bMethod() Else aMethod() End If ' I will stay put End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestKeepExplicitLineContinuationTriviaMethod() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() I[||]f a And b _ Or c Then aMethod() Else bMethod() End If End Sub End Module", "Module Program Sub Main() If (Not a Or Not b) _ And Not c Then bMethod() Else aMethod() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestKeepTriviaInStatementsInMultiLineIfBlock() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() [||]If a Then aMethod() Else bMethod() End If End Sub End Module", "Module Program Sub Main() If Not a Then bMethod() Else aMethod() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestSimplifyToLengthEqualsZero() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim x As String [||]If x.Length > 0 Then GreaterThanZero() Else EqualsZero() End If End Sub End Module", "Module Program Sub Main(args As String()) Dim x As String If x.Length = 0 Then EqualsZero() Else GreaterThanZero() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestSimplifyToLengthEqualsZero2() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim x() As String [||]If x.Length > 0 Then GreaterThanZero() Else EqualsZero() End If End Sub End Module", "Module Program Sub Main(args As String()) Dim x() As String If x.Length = 0 Then EqualsZero() Else GreaterThanZero() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestSimplifyToLengthEqualsZero4() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim x() As String [||]If x.Length > 0x0 Then GreaterThanZero() Else EqualsZero() End If End Sub End Module", "Module Program Sub Main(args As String()) Dim x() As String If x.Length = 0x0 Then EqualsZero() Else GreaterThanZero() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestSimplifyToLengthEqualsZero5() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim x As String [||]If 0 < x.Length Then GreaterThanZero() Else EqualsZero() End If End Sub End Module", "Module Program Sub Main(args As String()) Dim x As String If 0 = x.Length Then EqualsZero() Else GreaterThanZero() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestDoesNotSimplifyToLengthEqualsZero() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim x As String [||]If x.Length >= 0 Then aMethod() Else bMethod() End If End Sub End Module", "Module Program Sub Main(args As String()) Dim x As String If x.Length < 0 Then bMethod() Else aMethod() End If End Sub End Module") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestDoesNotSimplifyToLengthEqualsZero2() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) Dim x As String [||]If x.Length > 0.0 Then aMethod() Else bMethod() End If End Sub End Module", "Module Program Sub Main(args As String()) Dim x As String If x.Length <= 0.0 Then bMethod() Else aMethod() End If End Sub End Module") End Function <WorkItem(529748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529748")> <WorkItem(530593, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530593")> <WpfFact(Skip:="Bug 530593"), Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestColonAfterSingleLineIfWithEmptyElse() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main() ' Invert If I[||]f False Then Return Else : Console.WriteLine(1) End Sub End Module", "Module Program Sub Main() ' Invert If If True Then Else Return Console.WriteLine(1) End Sub End Module") End Function <WorkItem(529756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529756")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestOnlyOnElseIf() As Task Await TestMissingInRegularAndScriptAsync( "Module Program Sub Main(args As String()) If False Then Return ElseIf True [||]Then Console.WriteLine(""b"") Else Console.WriteLine(""a"") End If End Sub End Module") End Function <WorkItem(529756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529756")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestOnConditionOfMultiLineIfStatement() As Task Await TestInRegularAndScriptAsync( "Module Program Sub Main(args As String()) If [||]False Then Return Else Console.WriteLine(""a"") End If End Sub End Module", "Module Program Sub Main(args As String()) If [||]True Then Console.WriteLine(""a"") Else Return End If End Sub End Module") End Function <WorkItem(531474, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531474")> <WpfFact(Skip:="531474"), Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function TestDoNotRemoveTypeCharactersDuringComplexification() As Task Dim markup = <File> Imports System Module Program Sub Main() Goo(Function(take) [||]If True Then Console.WriteLine("true") Else Console.WriteLine("false") take$.ToString() Return Function() 1 End Function) End Sub Sub Goo(Of T)(x As Func(Of String, T)) End Sub Sub Goo(Of T)(x As Func(Of Integer, T)) End Sub End Module </File> Dim expected = <File> Imports System Module Program Sub Main() Goo(Function(take) If False Then Console.WriteLine("false") Else Console.WriteLine("true") take$.ToString() Return Function() 1 End Function) End Sub Sub Goo(Of T)(x As Func(Of String, T)) End Sub Sub Goo(Of T)(x As Func(Of Integer, T)) End Sub End Module </File> Await TestAsync(markup, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function InvertIfWithoutStatements() As Task Await TestInRegularAndScriptAsync( "class C sub M(x as String) [||]If x = ""a"" Then Else DoSomething() End If end sub sub DoSomething() end sub end class", "class C sub M(x as String) If x <> ""a"" Then DoSomething() End If end sub sub DoSomething() end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function InvertIfWithOnlyComment() As Task Await TestInRegularAndScriptAsync( "class C sub M(x as String) [||]If x = ""a"" Then ' A comment in a blank if statement Else DoSomething() End If end sub sub DoSomething() end sub end class", "class C sub M(x as String) If x <> ""a"" Then DoSomething() Else ' A comment in a blank if statement End If end sub sub DoSomething() end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)> Public Async Function InvertIfWithoutElse() As Task Await TestInRegularAndScriptAsync( "class C sub M(x as String) [||]If x = ""a"" Then ' Comment x += 1 End If end sub end class", "class C sub M(x as String) If x <> ""a"" Then Return End If ' Comment x += 1 end sub end class") End Function End Class End Namespace
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Workspaces/Core/Portable/Workspace/Solution/TextLoader.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.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A class that represents access to a source text and its version from a storage location. /// </summary> public abstract class TextLoader { private const double MaxDelaySecs = 1.0; private const int MaxRetries = 5; internal static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(MaxDelaySecs / MaxRetries); internal virtual string? FilePath => null; /// <summary> /// Load a text and a version of the document. /// </summary> /// <exception cref="IOException" /> /// <exception cref="InvalidDataException"/> /// <exception cref="OperationCanceledException"/> public abstract Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken); /// <summary> /// Load a text and a version of the document in the workspace. /// </summary> /// <exception cref="IOException" /> /// <exception cref="InvalidDataException"/> /// <exception cref="OperationCanceledException"/> internal virtual TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { // this implementation exists in case a custom derived type does not have access to internals return LoadTextAndVersionAsync(workspace, documentId, cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken); } internal async Task<TextAndVersion> LoadTextAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { var retries = 0; while (true) { try { return await LoadTextAndVersionAsync(workspace, documentId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (IOException e) { if (++retries > MaxRetries) { return CreateFailedText(workspace, documentId, e.Message); } // fall out to try again } catch (InvalidDataException e) { return CreateFailedText(workspace, documentId, e.Message); } // try again after a delay await Task.Delay(RetryDelay, cancellationToken).ConfigureAwait(false); } } internal TextAndVersion LoadTextSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { var retries = 0; while (true) { try { return LoadTextAndVersionSynchronously(workspace, documentId, cancellationToken); } catch (IOException e) { if (++retries > MaxRetries) { return CreateFailedText(workspace, documentId, e.Message); } // fall out to try again } catch (InvalidDataException e) { return CreateFailedText(workspace, documentId, e.Message); } // try again after a delay Thread.Sleep(RetryDelay); } } private TextAndVersion CreateFailedText(Workspace workspace, DocumentId documentId, string message) { // Notify workspace for backwards compatibility. workspace.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, message, documentId)); Location location; string display; var filePath = FilePath; if (filePath == null) { location = Location.None; display = documentId.ToString(); } else { location = Location.Create(filePath, textSpan: default, lineSpan: default); display = filePath; } return TextAndVersion.Create( SourceText.From(string.Empty, Encoding.UTF8), VersionStamp.Default, string.Empty, Diagnostic.Create(WorkspaceDiagnosticDescriptors.ErrorReadingFileContent, location, new[] { display, message })); } /// <summary> /// Creates a new <see cref="TextLoader"/> from an already existing source text and version. /// </summary> public static TextLoader From(TextAndVersion textAndVersion) { if (textAndVersion == null) { throw new ArgumentNullException(nameof(textAndVersion)); } return new TextDocumentLoader(textAndVersion); } /// <summary> /// Creates a <see cref="TextLoader"/> from a <see cref="SourceTextContainer"/> and version. /// /// The text obtained from the loader will be the current text of the container at the time /// the loader is accessed. /// </summary> public static TextLoader From(SourceTextContainer container, VersionStamp version, string? filePath = null) { if (container == null) { throw new ArgumentNullException(nameof(container)); } return new TextContainerLoader(container, version, filePath); } private sealed class TextDocumentLoader : TextLoader { private readonly TextAndVersion _textAndVersion; internal TextDocumentLoader(TextAndVersion textAndVersion) => _textAndVersion = textAndVersion; public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => Task.FromResult(_textAndVersion); internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => _textAndVersion; } private sealed class TextContainerLoader : TextLoader { private readonly SourceTextContainer _container; private readonly VersionStamp _version; private readonly string? _filePath; internal TextContainerLoader(SourceTextContainer container, VersionStamp version, string? filePath) { _container = container; _version = version; _filePath = filePath; } public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => Task.FromResult(LoadTextAndVersionSynchronously(workspace, documentId, cancellationToken)); internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => TextAndVersion.Create(_container.CurrentText, _version, _filePath); } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A class that represents access to a source text and its version from a storage location. /// </summary> public abstract class TextLoader { private const double MaxDelaySecs = 1.0; private const int MaxRetries = 5; internal static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(MaxDelaySecs / MaxRetries); internal virtual string? FilePath => null; /// <summary> /// Load a text and a version of the document. /// </summary> /// <exception cref="IOException" /> /// <exception cref="InvalidDataException"/> /// <exception cref="OperationCanceledException"/> public abstract Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken); /// <summary> /// Load a text and a version of the document in the workspace. /// </summary> /// <exception cref="IOException" /> /// <exception cref="InvalidDataException"/> /// <exception cref="OperationCanceledException"/> internal virtual TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { // this implementation exists in case a custom derived type does not have access to internals return LoadTextAndVersionAsync(workspace, documentId, cancellationToken).WaitAndGetResult_CanCallOnBackground(cancellationToken); } internal async Task<TextAndVersion> LoadTextAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { var retries = 0; while (true) { try { return await LoadTextAndVersionAsync(workspace, documentId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } catch (IOException e) { if (++retries > MaxRetries) { return CreateFailedText(workspace, documentId, e.Message); } // fall out to try again } catch (InvalidDataException e) { return CreateFailedText(workspace, documentId, e.Message); } // try again after a delay await Task.Delay(RetryDelay, cancellationToken).ConfigureAwait(false); } } internal TextAndVersion LoadTextSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) { var retries = 0; while (true) { try { return LoadTextAndVersionSynchronously(workspace, documentId, cancellationToken); } catch (IOException e) { if (++retries > MaxRetries) { return CreateFailedText(workspace, documentId, e.Message); } // fall out to try again } catch (InvalidDataException e) { return CreateFailedText(workspace, documentId, e.Message); } // try again after a delay Thread.Sleep(RetryDelay); } } private TextAndVersion CreateFailedText(Workspace workspace, DocumentId documentId, string message) { // Notify workspace for backwards compatibility. workspace.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, message, documentId)); Location location; string display; var filePath = FilePath; if (filePath == null) { location = Location.None; display = documentId.ToString(); } else { location = Location.Create(filePath, textSpan: default, lineSpan: default); display = filePath; } return TextAndVersion.Create( SourceText.From(string.Empty, Encoding.UTF8), VersionStamp.Default, string.Empty, Diagnostic.Create(WorkspaceDiagnosticDescriptors.ErrorReadingFileContent, location, new[] { display, message })); } /// <summary> /// Creates a new <see cref="TextLoader"/> from an already existing source text and version. /// </summary> public static TextLoader From(TextAndVersion textAndVersion) { if (textAndVersion == null) { throw new ArgumentNullException(nameof(textAndVersion)); } return new TextDocumentLoader(textAndVersion); } /// <summary> /// Creates a <see cref="TextLoader"/> from a <see cref="SourceTextContainer"/> and version. /// /// The text obtained from the loader will be the current text of the container at the time /// the loader is accessed. /// </summary> public static TextLoader From(SourceTextContainer container, VersionStamp version, string? filePath = null) { if (container == null) { throw new ArgumentNullException(nameof(container)); } return new TextContainerLoader(container, version, filePath); } private sealed class TextDocumentLoader : TextLoader { private readonly TextAndVersion _textAndVersion; internal TextDocumentLoader(TextAndVersion textAndVersion) => _textAndVersion = textAndVersion; public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => Task.FromResult(_textAndVersion); internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => _textAndVersion; } private sealed class TextContainerLoader : TextLoader { private readonly SourceTextContainer _container; private readonly VersionStamp _version; private readonly string? _filePath; internal TextContainerLoader(SourceTextContainer container, VersionStamp version, string? filePath) { _container = container; _version = version; _filePath = filePath; } public override Task<TextAndVersion> LoadTextAndVersionAsync(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => Task.FromResult(LoadTextAndVersionSynchronously(workspace, documentId, cancellationToken)); internal override TextAndVersion LoadTextAndVersionSynchronously(Workspace workspace, DocumentId documentId, CancellationToken cancellationToken) => TextAndVersion.Create(_container.CurrentText, _version, _filePath); } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Compilers/VisualBasic/Test/Emit/Attributes/AssemblyAttributes.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.IO Imports System.Reflection Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Public Class AssemblyAttributeTests Inherits BasicTestBase <Fact> Public Sub VersionAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("1.2.3.4")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal(New Version(1, 2, 3, 4), other.Assembly.Identity.Version) End Sub <Fact, WorkItem(543708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543708")> Public Sub VersionAttribute_FourParts() Dim comp As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("1.22.333.4444")> Public Class C End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) VerifyAssemblyTable(comp, Sub(r) Assert.Equal(New Version(1, 22, 333, 4444), r.Version) End Sub) End Sub <Fact> Public Sub VersionAttribute_TwoParts() Dim comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("1.2")> Public Class C End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) VerifyAssemblyTable(comp, Sub(r) Assert.Equal(1, r.Version.Major) Assert.Equal(2, r.Version.Minor) Assert.Equal(0, r.Version.Build) Assert.Equal(0, r.Version.Revision) End Sub) End Sub <Fact> Public Sub VersionAttribute_WildCard() Dim now = Date.Now Dim days = 0, seconds = 0 VersionTestHelpers.GetDefaultVersion(now, days, seconds) Dim comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("10101.0.*")> Public Class C End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCurrentLocalTime(now)) VerifyAssemblyTable(comp, Sub(r) Assert.Equal(10101, r.Version.Major) Assert.Equal(0, r.Version.Minor) Assert.Equal(days, r.Version.Build) Assert.Equal(seconds, r.Version.Revision) End Sub) End Sub <Fact> Public Sub VersionAttribute_Overflow() Dim comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("10101.0.*")> Public Class C End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCurrentLocalTime(#2300/1/1#)) VerifyAssemblyTable(comp, Sub(r) Assert.Equal(10101, r.Version.Major) Assert.Equal(0, r.Version.Minor) Assert.Equal(65535, r.Version.Build) Assert.Equal(0, r.Version.Revision) End Sub) End Sub <Fact, WorkItem(545948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545948")> Public Sub VersionAttributeErr() Dim comp As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("1.*")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) CompilationUtils.AssertTheseDiagnostics(comp, <error><![CDATA[ BC36962: The specified version string does not conform to the required format - major[.minor[.build|*[.revision|*]]] <Assembly: System.Reflection.AssemblyVersion("1.*")> ~~~~~ ]]></error>) ' --------------------------------------------- comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("-1")> Public Class C End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) CompilationUtils.AssertTheseDiagnostics(comp, <error><![CDATA[ BC36962: The specified version string does not conform to the required format - major[.minor[.build|*[.revision|*]]] <Assembly: System.Reflection.AssemblyVersion("-1")> ~~~~ ]]></error>) End Sub <Fact, WorkItem(545948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545948")> Public Sub SatelliteContractVersionAttributeErr() Dim comp As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[<Assembly: System.Resources.SatelliteContractVersionAttribute("1.2.3.A")>]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC36976: The specified version string does not conform to the recommended format - major.minor.build.revision <Assembly: System.Resources.SatelliteContractVersionAttribute("1.2.3.A")> ~~~~~~~~~ ]]></expected>) comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[<Assembly: System.Resources.SatelliteContractVersionAttribute("1.2.*")>]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC36976: The specified version string does not conform to the recommended format - major.minor.build.revision <Assembly: System.Resources.SatelliteContractVersionAttribute("1.2.*")> ~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub FileVersionAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyFileVersion("1.2.3.4")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("1.2.3.4", DirectCast(other.Assembly, SourceAssemblySymbol).FileVersion) End Sub <Fact> Public Sub FileVersionAttribute_MaxValue() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyFileVersion("65535.65535.65535.65535")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("65535.65535.65535.65535", DirectCast(other.Assembly, SourceAssemblySymbol).FileVersion) End Sub <Fact> Public Sub FileVersionAttribute_MissingParts() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyFileVersion("1.2")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("1.2", DirectCast(other.Assembly, SourceAssemblySymbol).FileVersion) End Sub <Fact> Public Sub FileVersionAttributeWrn_Wildcard() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyFileVersion("1.2.*")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) CompilationUtils.AssertTheseDiagnostics(other, <error><![CDATA[ BC42366: The specified version string does not conform to the recommended format - major.minor.build.revision <Assembly: System.Reflection.AssemblyFileVersion("1.2.*")> ~~~~~~~ ]]></error>) End Sub <Fact> Public Sub FileVersionAttributeWrn_OutOfRange() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyFileVersion("1.65536")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) CompilationUtils.AssertTheseDiagnostics(other, <error><![CDATA[ BC42366: The specified version string does not conform to the recommended format - major.minor.build.revision <Assembly: System.Reflection.AssemblyFileVersion("1.65536")> ~~~~~~~~~ ]]></error>) End Sub <Fact> Public Sub TitleAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyTitle("One Hundred Years Of Solitude")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("One Hundred Years Of Solitude", DirectCast(other.Assembly, SourceAssemblySymbol).Title) Assert.Equal(False, DirectCast(other.Assembly, SourceAssemblySymbol).MightContainNoPiaLocalTypes()) End Sub <Fact> Public Sub TitleAttributeNothing() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyTitle(Nothing)> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Null(DirectCast(other.Assembly, SourceAssemblySymbol).Title) End Sub <Fact> Public Sub DescriptionAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyDescription("A classic of magical realist literature")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("A classic of magical realist literature", DirectCast(other.Assembly, SourceAssemblySymbol).Description) End Sub <Fact> Public Sub CultureAttribute() Dim src = <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCulture("pt-BR")> Public Class C Shared Sub Main() End Sub End Class ]]> </file> </compilation> Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40(src, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("pt-BR", other.Assembly.Identity.CultureName) End Sub <Fact> Public Sub CultureAttribute02() Dim comp As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCulture("")> ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) VerifyAssemblyTable(comp, Sub(r) Assert.True(r.Culture.IsNil)) comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCulture(Nothing)> ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) VerifyAssemblyTable(comp, Sub(r) Assert.True(r.Culture.IsNil)) comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCulture("ja-JP")> ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) VerifyAssemblyTable(comp, Nothing, strData:="ja-JP") End Sub <Fact> Public Sub CultureAttribute03() Dim comp As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCulture("")> Public Class C Shared Sub Main() End Sub End Class ]]> </file> </compilation>, OutputKind.ConsoleApplication) VerifyAssemblyTable(comp, Sub(r) Assert.True(r.Culture.IsNil)) comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCulture(Nothing)> Public Class C Shared Sub Main() End Sub End Class ]]> </file> </compilation>, OutputKind.ConsoleApplication) VerifyAssemblyTable(comp, Sub(r) Assert.True(r.Culture.IsNil)) End Sub <Fact> Public Sub CultureAttributeNul() Dim comp As VisualBasicCompilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports Microsoft.VisualBasic <Assembly: System.Reflection.AssemblyCulture(vbNullChar)> ]]> </file> </compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) CompilationUtils.AssertTheseDiagnostics(comp, <error><![CDATA[ BC36982: Assembly culture strings may not contain embedded NUL characters. <Assembly: System.Reflection.AssemblyCulture(vbNullChar)> ~~~~~~~~~~ ]]></error>) End Sub <Fact, WorkItem(545951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545951")> Public Sub CultureAttributeErr() Dim src = <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCulture("pt-BR")> Public Class C Shared Sub Main() End Sub End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(src, OutputKind.ConsoleApplication) CompilationUtils.AssertTheseDiagnostics(comp, <error><![CDATA[ BC36977: Executables cannot be satellite assemblies; culture should always be empty <Assembly: System.Reflection.AssemblyCulture("pt-BR")> ~~~~~~~ ]]></error>) End Sub <Fact> <WorkItem(5866, "https://github.com/dotnet/roslyn/issues/5866")> Public Sub CultureAttributeMismatch() Dim neutral As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="neutral"> <file name="a.vb"><![CDATA[ public class neutral end class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll) Dim neutralRef = New VisualBasicCompilationReference(neutral) Dim en_UK As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="en_UK"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCultureAttribute("en-UK")> public class en_UK end class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll) Dim en_UKRef = New VisualBasicCompilationReference(en_UK) Dim en_us As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="en_us"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCultureAttribute("en-us")> public class en_us end class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll) Dim en_usRef = New VisualBasicCompilationReference(en_us) Dim compilation As VisualBasicCompilation compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCultureAttribute("en-US")> public class en_US Sub M(x as en_UK) End Sub end class ]]> </file> </compilation>, {en_UKRef, neutralRef}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC42371: Referenced assembly 'en_UK, Version=0.0.0.0, Culture=en-UK, PublicKeyToken=null' has different culture setting of 'en-UK'. </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseModule) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> </expected>) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> </file> </compilation>, {compilation.EmitToImageReference()}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC42371: Referenced assembly 'en_UK, Version=0.0.0.0, Culture=en-UK, PublicKeyToken=null' has different culture setting of 'en-UK'. </expected>) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="CultureAttributeMismatch1"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCultureAttribute("en-US")> public class Test Sub M(x as en_us) End Sub end class ]]> </file> </compilation>, {en_usRef}, TestOptions.ReleaseDll) CompileAndVerify(compilation).VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.ReleaseModule) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> </expected>) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="CultureAttributeMismatch2"> <file name="a.vb"> </file> </compilation>, {compilation.EmitToImageReference()}, TestOptions.ReleaseDll) CompileAndVerify(compilation, dependencies:={New ModuleData(en_usRef.Compilation.Assembly.Identity, OutputKind.DynamicallyLinkedLibrary, en_usRef.Compilation.EmitToArray(), ImmutableArray(Of Byte).Empty, False)}). VerifyDiagnostics() compilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="CultureAttributeMismatch3"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCultureAttribute("en-US")> public class en_US Sub M(x as neutral) End Sub end class ]]> </file> </compilation>, {en_UKRef, neutralRef}, TestOptions.ReleaseDll) CompileAndVerify(compilation).VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.ReleaseModule) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> </expected>) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="CultureAttributeMismatch4"> <file name="a.vb"> </file> </compilation>, {compilation.EmitToImageReference()}, TestOptions.ReleaseDll) CompileAndVerify(compilation, dependencies:={New ModuleData(en_UKRef.Compilation.Assembly.Identity, OutputKind.DynamicallyLinkedLibrary, en_UKRef.Compilation.EmitToArray(), ImmutableArray(Of Byte).Empty, False), New ModuleData(neutralRef.Compilation.Assembly.Identity, OutputKind.DynamicallyLinkedLibrary, neutralRef.Compilation.EmitToArray(), ImmutableArray(Of Byte).Empty, False)}, sourceSymbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(1, m.GetReferencedAssemblySymbols().Length) Dim naturalRef = m.ContainingAssembly.Modules(1).GetReferencedAssemblySymbols(1) Assert.True(naturalRef.IsMissing) Assert.Equal("neutral, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", naturalRef.ToTestDisplayString()) End Sub, symbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(2, m.GetReferencedAssemblySymbols().Length) Assert.Equal("neutral, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", m.GetReferencedAssemblySymbols()(1).ToTestDisplayString()) End Sub). VerifyDiagnostics() compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ public class neutral Sub M(x as en_UK) End Sub end class ]]> </file> </compilation>, {en_UKRef}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC42371: Referenced assembly 'en_UK, Version=0.0.0.0, Culture=en-UK, PublicKeyToken=null' has different culture setting of 'en-UK'. </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseModule) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> </expected>) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> </file> </compilation>, {compilation.EmitToImageReference()}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC42371: Referenced assembly 'en_UK, Version=0.0.0.0, Culture=en-UK, PublicKeyToken=null' has different culture setting of 'en-UK'. </expected>) End Sub <Fact> Public Sub CompanyAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCompany("MossBrain")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("MossBrain", DirectCast(other.Assembly, SourceAssemblySymbol).Company) other = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[<Assembly: System.Reflection.AssemblyCompany("微软")>]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("微软", DirectCast(other.Assembly, SourceAssemblySymbol).Company) End Sub <Fact> Public Sub ProductAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyProduct("Sound Cannon")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("Sound Cannon", DirectCast(other.Assembly, SourceAssemblySymbol).Product) End Sub <Fact> Public Sub CopyrightAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCopyright("مايكروسوفت")> Public Structure S End Structure ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("مايكروسوفت", DirectCast(other.Assembly, SourceAssemblySymbol).Copyright) End Sub <Fact> Public Sub TrademarkAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyTrademark("circle r")> Interface IGoo End Interface ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("circle r", DirectCast(other.Assembly, SourceAssemblySymbol).Trademark) End Sub <Fact> Public Sub InformationalVersionAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyInformationalVersion("1.2.3garbage")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) other.VerifyEmitDiagnostics() Assert.Equal("1.2.3garbage", DirectCast(other.Assembly, SourceAssemblySymbol).InformationalVersion) End Sub <Fact(), WorkItem(529922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529922")> Public Sub AlgorithmIdAttribute() Dim hash_module = TestReferences.SymbolsTests.netModule.hash_module Dim hash_resources = {New ResourceDescription("hash_resource", "snKey.snk", Function() New MemoryStream(TestResources.General.snKey, writable:=False), True)} Dim compilation As VisualBasicCompilation compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={hash_module}) CompileAndVerify(compilation, manifestResources:=hash_resources, validator:=Sub(peAssembly) Dim reader = peAssembly.ManifestModule.GetMetadataReader() Dim assembly As AssemblyDefinition = reader.GetAssemblyDefinition() Assert.Equal(AssemblyHashAlgorithm.Sha1, assembly.HashAlgorithm) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Assert.Equal(New Byte() {&H6C, &H9C, &H3E, &HDA, &H60, &HF, &H81, &H93, &H4A, &HC1, &HD, &H41, &HB3, &HE9, &HB2, &HB7, &H2D, &HEE, &H59, &HA8}, reader.GetBlobBytes(file1.HashValue)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal(New Byte() {&H7F, &H28, &HEA, &HD1, &HF4, &HA1, &H7C, &HB8, &HC, &H14, &HC0, &H2E, &H8C, &HFF, &H10, &HEC, &HB3, &HC2, &HA5, &H1D}, reader.GetBlobBytes(file2.HashValue)) Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)) End Sub) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.None)> class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={hash_module}) CompileAndVerify(compilation, manifestResources:=hash_resources, validator:=Sub(peAssembly) Dim reader = peAssembly.ManifestModule.GetMetadataReader() Dim assembly As AssemblyDefinition = reader.GetAssemblyDefinition() Assert.Equal(AssemblyHashAlgorithm.None, assembly.HashAlgorithm) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Assert.Equal(New Byte() {&H6C, &H9C, &H3E, &HDA, &H60, &HF, &H81, &H93, &H4A, &HC1, &HD, &H41, &HB3, &HE9, &HB2, &HB7, &H2D, &HEE, &H59, &HA8}, reader.GetBlobBytes(file1.HashValue)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal(New Byte() {&H7F, &H28, &HEA, &HD1, &HF4, &HA1, &H7C, &HB8, &HC, &H14, &HC0, &H2E, &H8C, &HFF, &H10, &HEC, &HB3, &HC2, &HA5, &H1D}, reader.GetBlobBytes(file2.HashValue)) Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)) End Sub) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(CUInt(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5))> class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={hash_module}) CompileAndVerify(compilation, manifestResources:=hash_resources, validator:=Sub(peAssembly) Dim reader = peAssembly.ManifestModule.GetMetadataReader() Dim assembly As AssemblyDefinition = reader.GetAssemblyDefinition() Assert.Equal(AssemblyHashAlgorithm.MD5, assembly.HashAlgorithm) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Assert.Equal(New Byte() {&H24, &H22, &H3, &HC3, &H94, &HD5, &HC2, &HD9, &H99, &HB3, &H6D, &H59, &HB2, &HCA, &H23, &HBC}, reader.GetBlobBytes(file1.HashValue)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal(New Byte() {&H8D, &HFE, &HBF, &H49, &H8D, &H62, &H2A, &H88, &H89, &HD1, &HE, &H0, &H9E, &H29, &H72, &HF1}, reader.GetBlobBytes(file2.HashValue)) Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)) End Sub) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA1)> class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={hash_module}) CompileAndVerify(compilation, manifestResources:=hash_resources, validator:=Sub(peAssembly) Dim reader = peAssembly.ManifestModule.GetMetadataReader() Dim assembly As AssemblyDefinition = reader.GetAssemblyDefinition() Assert.Equal(AssemblyHashAlgorithm.Sha1, assembly.HashAlgorithm) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Assert.Equal(New Byte() {&H6C, &H9C, &H3E, &HDA, &H60, &HF, &H81, &H93, &H4A, &HC1, &HD, &H41, &HB3, &HE9, &HB2, &HB7, &H2D, &HEE, &H59, &HA8}, reader.GetBlobBytes(file1.HashValue)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal(New Byte() {&H7F, &H28, &HEA, &HD1, &HF4, &HA1, &H7C, &HB8, &HC, &H14, &HC0, &H2E, &H8C, &HFF, &H10, &HEC, &HB3, &HC2, &HA5, &H1D}, reader.GetBlobBytes(file2.HashValue)) Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)) End Sub) compilation = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA256)> class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={MscorlibRef_v4_0_30316_17626, hash_module}) CompileAndVerify(compilation, verify:=Verification.Fails, manifestResources:=hash_resources, validator:=Sub(peAssembly) Dim reader = peAssembly.ManifestModule.GetMetadataReader() Dim assembly As AssemblyDefinition = reader.GetAssemblyDefinition() Assert.Equal(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA256, CType(assembly.HashAlgorithm, System.Configuration.Assemblies.AssemblyHashAlgorithm)) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Assert.Equal(New Byte() {&HA2, &H32, &H3F, &HD, &HF4, &HB8, &HED, &H5A, &H1B, &H7B, &HBE, &H14, &H4F, &HEC, &HBF, &H88, &H23, &H61, &HEB, &H40, &HF7, &HF9, &H46, &HEF, &H68, &H3B, &H70, &H29, &HCF, &H12, &H5, &H35}, reader.GetBlobBytes(file1.HashValue)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal(New Byte() {&HCC, &HAE, &HA0, &HB4, &H9E, &HAE, &H28, &HE0, &HA3, &H46, &HE9, &HCF, &HF3, &HEF, &HEA, &HF7, &H1D, &HDE, &H62, &H8F, &HD6, &HF4, &H87, &H76, &H1A, &HC3, &H6F, &HAD, &H10, &H1C, &H10, &HAC}, reader.GetBlobBytes(file2.HashValue)) Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)) End Sub) compilation = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA384)> class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={MscorlibRef_v4_0_30316_17626, hash_module}) CompileAndVerify(compilation, verify:=Verification.Fails, manifestResources:=hash_resources, validator:=Sub(peAssembly) Dim reader = peAssembly.ManifestModule.GetMetadataReader() Dim assembly As AssemblyDefinition = reader.GetAssemblyDefinition() Assert.Equal(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA384, CType(assembly.HashAlgorithm, System.Configuration.Assemblies.AssemblyHashAlgorithm)) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Assert.Equal(New Byte() {&HB6, &H35, &H9B, &HBE, &H82, &H89, &HFF, &H1, &H22, &H8B, &H56, &H5E, &H9B, &H15, &H5D, &H10, &H68, &H83, &HF7, &H75, &H4E, &HA6, &H30, &HF7, &H8D, &H39, &H9A, &HB7, &HE8, &HB6, &H47, &H1F, &HF6, &HFD, &H1E, &H64, &H63, &H6B, &HE7, &HF4, &HBE, &HA7, &H21, &HED, &HFC, &H82, &H38, &H95}, reader.GetBlobBytes(file1.HashValue)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal(New Byte() {&H45, &H5, &H2E, &H90, &H9B, &H61, &HA3, &HF8, &H60, &HD2, &H86, &HCB, &H10, &H33, &HC9, &H86, &H68, &HA5, &HEE, &H4A, &HCF, &H21, &H10, &HA9, &H8F, &H14, &H62, &H8D, &H3E, &H7D, &HFD, &H7E, &HE6, &H23, &H6F, &H2D, &HBA, &H4, &HE7, &H13, &HE4, &H5E, &H8C, &HEB, &H80, &H68, &HA3, &H17}, reader.GetBlobBytes(file2.HashValue)) Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)) End Sub) compilation = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA512)> class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={MscorlibRef_v4_0_30316_17626, hash_module}) CompileAndVerify(compilation, verify:=Verification.Fails, manifestResources:=hash_resources, validator:=Sub(peAssembly) Dim reader = peAssembly.ManifestModule.GetMetadataReader() Dim assembly As AssemblyDefinition = reader.GetAssemblyDefinition() Assert.Equal(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA512, CType(assembly.HashAlgorithm, System.Configuration.Assemblies.AssemblyHashAlgorithm)) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Assert.Equal(New Byte() {&H5F, &H4D, &H7E, &H63, &HC9, &H87, &HD9, &HEB, &H4F, &H5C, &HFD, &H96, &H3F, &H25, &H58, &H74, &H86, &HDF, &H97, &H75, &H93, &HEE, &HC2, &H5F, &HFD, &H8A, &H40, &H5C, &H92, &H5E, &HB5, &H7, &HD6, &H12, &HE9, &H21, &H55, &HCE, &HD7, &HE5, &H15, &HF5, &HBA, &HBC, &H1B, &H31, &HAD, &H3C, &H5E, &HE0, &H91, &H98, &HC2, &HE0, &H96, &HBB, &HAD, &HD, &H4E, &HF4, &H91, &H53, &H3D, &H84}, reader.GetBlobBytes(file1.HashValue)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal(New Byte() {&H79, &HFE, &H97, &HAB, &H8, &H8E, &HDF, &H74, &HC2, &HEF, &H84, &HBB, &HFC, &H74, &HAC, &H60, &H18, &H6E, &H1A, &HD2, &HC5, &H94, &HE0, &HDA, &HE0, &H45, &H33, &H43, &H99, &HF0, &HF3, &HF1, &H72, &H5, &H4B, &HF, &H37, &H50, &HC5, &HD9, &HCE, &H29, &H82, &H4C, &HF7, &HE6, &H94, &H5F, &HE5, &H7, &H2B, &H4A, &H18, &H9, &H56, &HC9, &H52, &H69, &H7D, &HC4, &H48, &H63, &H70, &HF2}, reader.GetBlobBytes(file2.HashValue)) Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)) End Sub) Dim hash_module_Comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)> public class Test end class ]]></file> </compilation>, options:=TestOptions.ReleaseModule) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={hash_module_Comp.EmitToImageReference()}) CompileAndVerify(compilation, validator:=Sub(peAssembly) Dim metadataReader = peAssembly.ManifestModule.GetMetadataReader() Dim assembly As AssemblyDefinition = metadataReader.GetAssemblyDefinition() Assert.Equal(AssemblyHashAlgorithm.MD5, assembly.HashAlgorithm) Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)) End Sub) compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345UI)> class Program Sub M() End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll) ' no error reported if we don't need to hash compilation.VerifyEmitDiagnostics() compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345UI)> class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={hash_module}) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC37215: Cryptographic failure while creating hashes. </expected>) compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345UI)> class Program end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream(), manifestResources:=hash_resources).Diagnostics, <expected> BC37215: Cryptographic failure while creating hashes. </expected>) Dim comp = CreateVisualBasicCompilation("AlgorithmIdAttribute", <![CDATA[<Assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)>]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) VerifyAssemblyTable(comp, Sub(r) Assert.Equal(AssemblyHashAlgorithm.MD5, r.HashAlgorithm) End Sub) ' comp = CreateVisualBasicCompilation("AlgorithmIdAttribute1", <![CDATA[<Assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.None)>]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) VerifyAssemblyTable(comp, Sub(r) Assert.Equal(AssemblyHashAlgorithm.None, r.HashAlgorithm) End Sub) ' comp = CreateVisualBasicCompilation("AlgorithmIdAttribute2", <![CDATA[<Assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345UI)>]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) VerifyAssemblyTable(comp, Sub(r) Assert.Equal(12345, CInt(r.HashAlgorithm))) End Sub <Fact()> Public Sub AssemblyFlagsAttribute() Dim comp = CreateVisualBasicCompilation("AssemblyFlagsAttribute", <![CDATA[ Imports System.Reflection <Assembly: AssemblyFlags(AssemblyNameFlags.EnableJITcompileOptimizer Or AssemblyNameFlags.Retargetable)>]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) VerifyAssemblyTable(comp, Sub(r) Assert.Equal(AssemblyFlags.DisableJitCompileOptimizer Or AssemblyFlags.Retargetable, r.Flags) End Sub) End Sub <Fact, WorkItem(546635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546635")> Public Sub AssemblyFlagsAttribute02() Dim comp = CreateVisualBasicCompilation("AssemblyFlagsAttribute02", <![CDATA[<Assembly: System.Reflection.AssemblyFlags(12345)>]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) ' Both native & Roslyn PEVerifier fail: [MD]: Error: Invalid Assembly flags (0x3038). [token:0x20000001] VerifyAssemblyTable(comp, Sub(r) Assert.Equal(12345 - 1, CInt(r.Flags)) End Sub) comp.VerifyDiagnostics( Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "Assembly: System.Reflection.AssemblyFlags(12345)").WithArguments("Public Overloads Sub New(assemblyFlags As Integer)", "This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202")) End Sub <Fact> Public Sub AssemblyFlagsAttribute03() Dim comp = CreateVisualBasicCompilation("AssemblyFlagsAttribute02", <![CDATA[<Assembly: System.Reflection.AssemblyFlags(12345UI)>]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) ' Both native & Roslyn PEVerifier fail: [MD]: Error: Invalid Assembly flags (0x3038). [token:0x20000001] VerifyAssemblyTable(comp, Sub(r) Assert.Equal(12345 - 1, CInt(r.Flags)) End Sub) comp.VerifyDiagnostics( Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "Assembly: System.Reflection.AssemblyFlags(12345UI)").WithArguments("Public Overloads Sub New(flags As UInteger)", "This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202")) End Sub #Region "Metadata Verifier (TODO: consolidate with others)" Friend Sub VerifyAssemblyTable(comp As VisualBasicCompilation, verifier As Action(Of AssemblyDefinition), Optional strData As String = Nothing) Dim stream = New MemoryStream() Assert.True(comp.Emit(stream).Success) Using mt = ModuleMetadata.CreateFromImage(stream.ToImmutable()) Dim metadataReader = mt.Module.GetMetadataReader() Dim row As AssemblyDefinition = metadataReader.GetAssemblyDefinition() If verifier IsNot Nothing Then verifier(row) End If ' tmp If strData IsNot Nothing Then Assert.Equal(strData, metadataReader.GetString(row.Culture)) End If End Using End Sub #End Region #Region "NetModule Assembly attribute tests" #Region "Helpers" Private Shared ReadOnly s_defaultNetModuleSourceHeader As String = <![CDATA[ Imports System Imports System.Reflection Imports System.Security.Permissions <Assembly: AssemblyTitle("AssemblyTitle")> <Assembly: FileIOPermission(SecurityAction.RequestOptional)> <Assembly: UserDefinedAssemblyAttrNoAllowMultiple("UserDefinedAssemblyAttrNoAllowMultiple")> <Assembly: UserDefinedAssemblyAttrAllowMultiple("UserDefinedAssemblyAttrAllowMultiple")> ]]>.Value Private Shared ReadOnly s_defaultNetModuleSourceBody As String = <![CDATA[ Public Class NetModuleClass End Class <AttributeUsage(AttributeTargets.Assembly, AllowMultiple := False)> Public Class UserDefinedAssemblyAttrNoAllowMultipleAttribute Inherits Attribute Public Property Text() As String Public Property Text2() As String Public Sub New(text1 As String) Text = text1 End Sub Public Sub New(text1 As Integer) Text = text1.ToString() End Sub End Class <AttributeUsage(AttributeTargets.Assembly, AllowMultiple := True)> Public Class UserDefinedAssemblyAttrAllowMultipleAttribute Inherits Attribute Public Property Text() As String Public Property Text2() As String Public Sub New(text1 As String) Text = text1 End Sub Public Sub New(text1 As Integer) Text = text1.ToString() End Sub End Class ]]>.Value Private Function GetNetModuleWithAssemblyAttributesRef(Optional netModuleSourceHeader As String = Nothing, Optional netModuleSourceBody As String = Nothing, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional nameSuffix As String = "") As MetadataReference Return GetNetModuleWithAssemblyAttributes(netModuleSourceHeader, netModuleSourceBody, references, nameSuffix).GetReference() End Function Private Function GetNetModuleWithAssemblyAttributes(Optional netModuleSourceHeader As String = Nothing, Optional netModuleSourceBody As String = Nothing, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional nameSuffix As String = "") As ModuleMetadata Dim netmoduleSource As String = If(netModuleSourceHeader, s_defaultNetModuleSourceHeader) & If(netModuleSourceBody, s_defaultNetModuleSourceBody) Dim netmoduleCompilation = CreateCompilationWithMscorlib40({netmoduleSource}, references:=references, options:=TestOptions.ReleaseModule, assemblyName:="NetModuleWithAssemblyAttributes" & nameSuffix) Dim diagnostics = netmoduleCompilation.GetDiagnostics() Dim bytes = netmoduleCompilation.EmitToArray() Return ModuleMetadata.CreateFromImage(bytes) End Function Private Shared Sub TestDuplicateAssemblyAttributesNotEmitted(assembly As AssemblySymbol, expectedSrcAttrCount As Integer, expectedDuplicateAttrCount As Integer, attrTypeName As String) ' SOURCE ATTRIBUTES Dim allSrcAttrs = assembly.GetAttributes() Dim srcAttrs = allSrcAttrs.Where(Function(a) a.AttributeClass.Name.Equals(attrTypeName)).AsImmutable() Assert.Equal(expectedSrcAttrCount, srcAttrs.Length) ' EMITTED ATTRIBUTES Dim compilation = assembly.DeclaringCompilation compilation.GetDiagnostics() compilation.EmbeddedSymbolManager.MarkAllDeferredSymbolsAsReferenced(compilation) ' We should get only unique netmodule/assembly attributes here, duplicate ones should not be emitted. Dim expectedEmittedAttrsCount As Integer = expectedSrcAttrCount - expectedDuplicateAttrCount Dim allEmittedAttrs = DirectCast(assembly, SourceAssemblySymbol). GetAssemblyCustomAttributesToEmit(New ModuleCompilationState, emittingRefAssembly:=False, emittingAssemblyAttributesInNetModule:=False). Cast(Of VisualBasicAttributeData)() Dim emittedAttrs = allEmittedAttrs.Where(Function(a) a.AttributeClass.Name.Equals(attrTypeName)).AsImmutable() Assert.Equal(expectedEmittedAttrsCount, emittedAttrs.Length) Dim uniqueAttributes = New HashSet(Of VisualBasicAttributeData)(comparer:=CommonAttributeDataComparer.Instance) For Each attr In emittedAttrs Assert.True(uniqueAttributes.Add(attr)) Next End Sub #End Region <Fact()> Public Sub AssemblyAttributesFromNetModule() Dim consoleappSource = <compilation> <file name="a.vb"> <![CDATA[ Class Program Private Shared Sub Main(args As String()) End Sub End Class ]]> </file> </compilation> Dim netModuleWithAssemblyAttributes = GetNetModuleWithAssemblyAttributes() Dim metadata As PEModule = netModuleWithAssemblyAttributes.Module Dim metadataReader = metadata.GetMetadataReader() Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)) Assert.Equal(18, metadataReader.CustomAttributes.Count) Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count) Dim token As EntityHandle = metadata.GetTypeRef(metadata.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM") Assert.False(token.IsNil) 'could the type ref be located? If not then the attribute's not there. Dim consoleappCompilation = CreateCompilationWithMscorlib40AndReferences(consoleappSource, {netModuleWithAssemblyAttributes.GetReference()}) Assert.NotNull(consoleappCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHere")) Assert.NotNull(consoleappCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHereM")) Dim diagnostics = consoleappCompilation.GetDiagnostics() Dim attrs = consoleappCompilation.Assembly.GetAttributes() Assert.Equal(4, attrs.Length) For Each a In attrs Select Case a.AttributeClass.Name Case "AssemblyTitleAttribute" Assert.Equal("System.Reflection.AssemblyTitleAttribute(""AssemblyTitle"")", a.ToString()) Exit Select Case "FileIOPermissionAttribute" Assert.Equal("System.Security.Permissions.FileIOPermissionAttribute(System.Security.Permissions.SecurityAction.RequestOptional)", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrNoAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")", a.ToString()) Exit Select Case Else Assert.Equal("Unexpected Attr", a.AttributeClass.Name) Exit Select End Select Next metadata = AssemblyMetadata.CreateFromImage(consoleappCompilation.EmitToArray()).GetAssembly.ManifestModule metadataReader = metadata.GetMetadataReader() Assert.Equal(1, metadataReader.GetTableRowCount(TableIndex.ModuleRef)) Assert.Equal(3, metadataReader.GetTableRowCount(TableIndex.ExportedType)) Assert.Equal(6, metadataReader.CustomAttributes.Count) Assert.Equal(1, metadataReader.DeclarativeSecurityAttributes.Count) token = metadata.GetTypeRef(metadata.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM") Assert.True(token.IsNil) 'could the type ref be located? If not then the attribute's not there. consoleappCompilation = CreateCompilationWithMscorlib40AndReferences(consoleappSource, {netModuleWithAssemblyAttributes.GetReference()}, TestOptions.ReleaseModule) Assert.Equal(0, consoleappCompilation.Assembly.GetAttributes().Length) Dim modRef = DirectCast(consoleappCompilation.EmitToImageReference(), MetadataImageReference) metadata = ModuleMetadata.CreateFromImage(consoleappCompilation.EmitToArray()).Module metadataReader = metadata.GetMetadataReader() Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ModuleRef)) Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)) Assert.Equal(0, metadataReader.CustomAttributes.Count) Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count) token = metadata.GetTypeRef(metadata.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM") Assert.True(token.IsNil) 'could the type ref be located? If not then the attribute's not there. End Sub <Fact()> <WorkItem(10550, "https://github.com/dotnet/roslyn/issues/10550")> Public Sub AssemblyAttributesFromNetModule_WithoutAssemblyAttributesGoHereTypes() Dim netmoduleSource = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: UserDefinedAssemblyAttrNoAllowMultiple("UserDefinedAssemblyAttrNoAllowMultiple")> <Assembly: UserDefinedAssemblyAttrAllowMultiple("UserDefinedAssemblyAttrAllowMultiple")> Public Class NetModuleClass End Class <AttributeUsage(AttributeTargets.Assembly, AllowMultiple := False)> Public Class UserDefinedAssemblyAttrNoAllowMultipleAttribute Inherits Attribute Public Sub New(text1 As String) End Sub End Class <AttributeUsage(AttributeTargets.Assembly, AllowMultiple := True)> Public Class UserDefinedAssemblyAttrAllowMultipleAttribute Inherits Attribute Public Sub New(text1 As String) End Sub End Class ]]> </file> </compilation> Dim consoleappSource = <compilation> <file name="a.vb"> <![CDATA[ Class Program Private Shared Sub Main(args As String()) End Sub End Class ]]> </file> </compilation> Dim netmoduleCompilation = CreateEmptyCompilationWithReferences(netmoduleSource, references:={MinCorlibRef}, options:=TestOptions.ReleaseModule) Assert.Null(netmoduleCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHere")) Assert.Null(netmoduleCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHereM")) Dim bytes = netmoduleCompilation.EmitToArray() Dim netModuleWithAssemblyAttributes = ModuleMetadata.CreateFromImage(bytes) Dim metadata As PEModule = netModuleWithAssemblyAttributes.Module Dim metadataReader = metadata.GetMetadataReader() Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)) Assert.Equal(4, metadataReader.CustomAttributes.Count) Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count) Dim token As EntityHandle = metadata.GetTypeRef(metadata.GetAssemblyRef("mincorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM") Assert.False(token.IsNil) 'could the type ref be located? If not then the attribute's not there. Dim consoleappCompilation = CreateEmptyCompilationWithReferences(consoleappSource, {MinCorlibRef, netModuleWithAssemblyAttributes.GetReference()}) Assert.Null(consoleappCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHere")) Assert.Null(consoleappCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHereM")) consoleappCompilation.GetDiagnostics().Verify() Dim attrs = consoleappCompilation.Assembly.GetAttributes() Assert.Equal(2, attrs.Length) For Each a In attrs Select Case a.AttributeClass.Name Case "UserDefinedAssemblyAttrNoAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")", a.ToString()) Exit Select Case Else Assert.Equal("Unexpected Attr", a.AttributeClass.Name) Exit Select End Select Next metadata = AssemblyMetadata.CreateFromImage(consoleappCompilation.EmitToArray()).GetAssembly.ManifestModule metadataReader = metadata.GetMetadataReader() Assert.Equal(1, metadataReader.GetTableRowCount(TableIndex.ModuleRef)) Assert.Equal(3, metadataReader.GetTableRowCount(TableIndex.ExportedType)) Assert.Equal(2, metadataReader.CustomAttributes.Count) Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count) token = metadata.GetTypeRef(metadata.GetAssemblyRef("mincorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM") Assert.True(token.IsNil) 'could the type ref be located? If not then the attribute's not there. consoleappCompilation = CreateEmptyCompilationWithReferences(consoleappSource, {MinCorlibRef, netModuleWithAssemblyAttributes.GetReference()}, TestOptions.ReleaseModule) Assert.Equal(0, consoleappCompilation.Assembly.GetAttributes().Length) Dim modRef = DirectCast(consoleappCompilation.EmitToImageReference(), MetadataImageReference) metadata = ModuleMetadata.CreateFromImage(consoleappCompilation.EmitToArray()).Module metadataReader = metadata.GetMetadataReader() Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ModuleRef)) Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)) Assert.Equal(0, metadataReader.CustomAttributes.Count) Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count) token = metadata.GetTypeRef(metadata.GetAssemblyRef("mincorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM") Assert.True(token.IsNil) 'could the type ref be located? If not then the attribute's not there. End Sub <Fact()> Public Sub AssemblyAttributesFromNetModuleDropIdentical() Dim consoleappSource = <compilation> <file name="a.vb"> <![CDATA[ <Assembly: UserDefinedAssemblyAttrNoAllowMultiple("UserDefinedAssemblyAttrNoAllowMultiple")> <Assembly: UserDefinedAssemblyAttrAllowMultiple("UserDefinedAssemblyAttrAllowMultiple")> Class Program Private Shared Sub Main(args As String()) End Sub End Class ]]> </file> </compilation> Dim consoleappCompilation = CreateCompilationWithMscorlib40AndReferences(consoleappSource, {GetNetModuleWithAssemblyAttributesRef()}) Dim diagnostics = consoleappCompilation.GetDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(consoleappCompilation.Assembly, expectedSrcAttrCount:=2, expectedDuplicateAttrCount:=1, attrTypeName:="UserDefinedAssemblyAttrAllowMultipleAttribute") TestDuplicateAssemblyAttributesNotEmitted(consoleappCompilation.Assembly, expectedSrcAttrCount:=2, expectedDuplicateAttrCount:=1, attrTypeName:="UserDefinedAssemblyAttrNoAllowMultipleAttribute") Dim attrs = consoleappCompilation.Assembly.GetAttributes() For Each a In attrs Select Case a.AttributeClass.Name Case "AssemblyTitleAttribute" Assert.Equal("System.Reflection.AssemblyTitleAttribute(""AssemblyTitle"")", a.ToString()) Exit Select Case "FileIOPermissionAttribute" Assert.Equal("System.Security.Permissions.FileIOPermissionAttribute(System.Security.Permissions.SecurityAction.RequestOptional)", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrNoAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")", a.ToString()) Exit Select Case Else Assert.Equal("Unexpected Attr", a.AttributeClass.Name) Exit Select End Select Next End Sub <Fact()> Public Sub AssemblyAttributesFromNetModuleDropSpecial() Dim consoleappSource = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Reflection <Assembly: AssemblyTitle("AssemblyTitle (from source)")> Class Program Private Shared Sub Main(args As String()) End Sub End Class ]]> </file> </compilation> Dim consoleappCompilation = CreateCompilationWithMscorlib40AndReferences(consoleappSource, {GetNetModuleWithAssemblyAttributesRef()}) Dim diagnostics = consoleappCompilation.GetDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(consoleappCompilation.Assembly, expectedSrcAttrCount:=2, expectedDuplicateAttrCount:=1, attrTypeName:="AssemblyTitleAttribute") Dim attrs = DirectCast(consoleappCompilation.Assembly, SourceAssemblySymbol). GetAssemblyCustomAttributesToEmit(New ModuleCompilationState, emittingRefAssembly:=False, emittingAssemblyAttributesInNetModule:=False). Cast(Of VisualBasicAttributeData)() For Each a In attrs Select Case a.AttributeClass.Name Case "AssemblyTitleAttribute" Assert.Equal("System.Reflection.AssemblyTitleAttribute(""AssemblyTitle (from source)"")", a.ToString()) Exit Select Case "FileIOPermissionAttribute" Assert.Equal("System.Security.Permissions.FileIOPermissionAttribute(System.Security.Permissions.SecurityAction.RequestOptional)", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrNoAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")", a.ToString()) Exit Select Case "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute" ' synthesized attributes Exit Select Case Else Assert.Equal("Unexpected Attr", a.AttributeClass.Name) Exit Select End Select Next End Sub <Fact()> Public Sub AssemblyAttributesFromNetModuleAddMulti() Dim consoleappSource = <compilation> <file name="a.vb"> <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultiple("UserDefinedAssemblyAttrAllowMultiple (from source)")> Class Program Private Shared Sub Main(args As String()) End Sub End Class ]]> </file> </compilation> Dim consoleappCompilation = CreateCompilationWithMscorlib40AndReferences(consoleappSource, {GetNetModuleWithAssemblyAttributesRef()}) Dim diagnostics = consoleappCompilation.GetDiagnostics() Dim attrs = consoleappCompilation.Assembly.GetAttributes() Assert.Equal(5, attrs.Length) For Each a In attrs Select Case a.AttributeClass.Name Case "AssemblyTitleAttribute" Assert.Equal("System.Reflection.AssemblyTitleAttribute(""AssemblyTitle"")", a.ToString()) Exit Select Case "FileIOPermissionAttribute" Assert.Equal("System.Security.Permissions.FileIOPermissionAttribute(System.Security.Permissions.SecurityAction.RequestOptional)", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrNoAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrAllowMultipleAttribute" Assert.[True](("UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")" = a.ToString()) OrElse ("UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple (from source)"")" = a.ToString()), "Unexpected attribute construction") Exit Select Case Else Assert.Equal("Unexpected Attr", a.AttributeClass.Name) Exit Select End Select Next End Sub <Fact(), WorkItem(546963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546963")> Public Sub AssemblyAttributesFromNetModuleBadMulti() Dim source As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrNoAllowMultiple("UserDefinedAssemblyAttrNoAllowMultiple (from source)")> ]]>.Value Dim netmodule1Ref = GetNetModuleWithAssemblyAttributesRef() Dim comp = CreateCompilationWithMscorlib40({source}, references:={netmodule1Ref}, options:=TestOptions.ReleaseDll) ' error BC36978: Attribute 'UserDefinedAssemblyAttrNoAllowMultipleAttribute' in 'NetModuleWithAssemblyAttributes.netmodule' cannot be applied multiple times. comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsageInNetModule2).WithArguments("UserDefinedAssemblyAttrNoAllowMultipleAttribute", "NetModuleWithAssemblyAttributes.netmodule")) Dim attrs = comp.Assembly.GetAttributes() ' even duplicates are preserved in source. Assert.Equal(5, attrs.Length) ' Build NetModule comp = CreateCompilationWithMscorlib40({source}, references:={netmodule1Ref}, options:=TestOptions.ReleaseModule) comp.VerifyDiagnostics() Dim netmodule2Ref = comp.EmitToImageReference() attrs = comp.Assembly.GetAttributes() Assert.Equal(1, attrs.Length) comp = CreateCompilationWithMscorlib40({""}, references:={netmodule1Ref, netmodule2Ref}, options:=TestOptions.ReleaseDll) ' error BC36978: Attribute 'UserDefinedAssemblyAttrNoAllowMultipleAttribute' in 'NetModuleWithAssemblyAttributes.netmodule' cannot be applied multiple times. comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsageInNetModule2).WithArguments("UserDefinedAssemblyAttrNoAllowMultipleAttribute", "NetModuleWithAssemblyAttributes.netmodule")) attrs = comp.Assembly.GetAttributes() ' even duplicates are preserved in source. Assert.Equal(5, attrs.Length) End Sub <Fact(), WorkItem(546963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546963")> Public Sub InternalsVisibleToAttributeDropIdentical() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices <Assembly: InternalsVisibleTo("Assembly2")> <Assembly: InternalsVisibleTo("Assembly2")> ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source, OutputKind.DynamicallyLinkedLibrary) CompileAndVerify(comp) TestDuplicateAssemblyAttributesNotEmitted(comp.Assembly, expectedSrcAttrCount:=2, expectedDuplicateAttrCount:=1, attrTypeName:="InternalsVisibleToAttribute") End Sub <Fact(), WorkItem(546963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546963")> Public Sub AssemblyAttributesFromSourceDropIdentical() Dim source = <compilation> <file name="a.vb"> <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str2", Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str1", Text := "str1")> ' unique ]]> </file> </compilation> Dim netmoduleRef = GetNetModuleWithAssemblyAttributesRef() Dim comp = CreateCompilationWithMscorlib40AndReferences(source, references:={netmoduleRef}) Dim diagnostics = comp.GetDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(comp.Assembly, expectedSrcAttrCount:=16, expectedDuplicateAttrCount:=5, attrTypeName:="UserDefinedAssemblyAttrAllowMultipleAttribute") End Sub <Fact(), WorkItem(546963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546963")> Public Sub AssemblyAttributesFromSourceDropIdentical_02() Dim source1 As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrNoAllowMultipleAttribute(0)> ' unique ]]>.Value Dim source2 As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrNoAllowMultipleAttribute(0)> ' duplicate ignored, no error because identical ]]>.Value Dim defaultHeaderString As String = <![CDATA[ Imports System ]]>.Value Dim defsRef As MetadataReference = CreateCompilationWithMscorlib40({defaultHeaderString & s_defaultNetModuleSourceBody}, references:=Nothing, options:=TestOptions.ReleaseDll).ToMetadataReference() Dim netmodule1Ref As MetadataReference = GetNetModuleWithAssemblyAttributesRef(source2, "", references:={defsRef}, nameSuffix:="1") Dim comp = CreateCompilationWithMscorlib40({source1}, references:={defsRef, netmodule1Ref}, options:=TestOptions.ReleaseDll) ' duplicate ignored, no error because identical comp.VerifyDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(comp.Assembly, expectedSrcAttrCount:=2, expectedDuplicateAttrCount:=1, attrTypeName:="UserDefinedAssemblyAttrNoAllowMultipleAttribute") Dim netmodule2Ref As MetadataReference = GetNetModuleWithAssemblyAttributesRef(source1, "", references:={defsRef}, nameSuffix:="2") comp = CreateCompilationWithMscorlib40({""}, references:={defsRef, netmodule1Ref, netmodule2Ref}, options:=TestOptions.ReleaseDll) ' duplicate ignored, no error because identical comp.VerifyDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(comp.Assembly, expectedSrcAttrCount:=2, expectedDuplicateAttrCount:=1, attrTypeName:="UserDefinedAssemblyAttrNoAllowMultipleAttribute") End Sub <Fact(), WorkItem(546963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546963")> Public Sub AssemblyAttributesFromNetModuleDropIdentical_01() ' Duplicate ignored attributes in netmodule Dim netmoduleAttributes As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str2", Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str1", Text := "str1")> ' unique ]]>.Value Dim netmoduleRef = GetNetModuleWithAssemblyAttributesRef(s_defaultNetModuleSourceHeader & netmoduleAttributes, s_defaultNetModuleSourceBody) Dim comp = CreateCompilationWithMscorlib40({""}, references:={netmoduleRef}, options:=TestOptions.ReleaseDll) Dim diagnostics = comp.GetDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(comp.Assembly, expectedSrcAttrCount:=16, expectedDuplicateAttrCount:=5, attrTypeName:="UserDefinedAssemblyAttrAllowMultipleAttribute") End Sub <Fact(), WorkItem(546963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546963")> Public Sub AssemblyAttributesFromNetModuleDropIdentical_02() ' Duplicate ignored attributes in netmodules Dim netmodule1Attributes As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str2", Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str1", Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' unique ]]>.Value Dim netmodule2Attributes As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' duplicate ]]>.Value Dim netmodule3Attributes As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' duplicate ]]>.Value Dim defaultImportsString As String = <![CDATA[ Imports System ]]>.Value Dim defsRef As MetadataReference = CreateCompilationWithMscorlib40({defaultImportsString & s_defaultNetModuleSourceBody}, references:=Nothing, options:=TestOptions.ReleaseDll).ToMetadataReference() Dim netmodule0Ref = GetNetModuleWithAssemblyAttributesRef(s_defaultNetModuleSourceHeader, "", references:={defsRef}) Dim netmodule1Ref = GetNetModuleWithAssemblyAttributesRef(netmodule1Attributes, "", references:={defsRef}) Dim netmodule2Ref = GetNetModuleWithAssemblyAttributesRef(netmodule2Attributes, "", references:={defsRef}) Dim netmodule3Ref = GetNetModuleWithAssemblyAttributesRef(netmodule3Attributes, "", references:={defsRef}) Dim comp = CreateCompilationWithMscorlib40({""}, references:={defsRef, netmodule0Ref, netmodule1Ref, netmodule2Ref, netmodule3Ref}, options:=TestOptions.ReleaseDll) Dim diagnostics = comp.GetDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(comp.Assembly, expectedSrcAttrCount:=17, expectedDuplicateAttrCount:=6, attrTypeName:="UserDefinedAssemblyAttrAllowMultipleAttribute") End Sub <Fact(), WorkItem(546963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546963")> Public Sub AssemblyAttributesFromSourceAndNetModuleDropIdentical_01() ' All duplicate ignored attributes in netmodule Dim netmoduleAttributes As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' duplicate ]]>.Value Dim sourceAttributes As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str2", Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str1", Text := "str1")> ' unique ]]>.Value Dim netmoduleRef = GetNetModuleWithAssemblyAttributesRef(s_defaultNetModuleSourceHeader & netmoduleAttributes, s_defaultNetModuleSourceBody) Dim comp = CreateCompilationWithMscorlib40({sourceAttributes}, references:={netmoduleRef}, options:=TestOptions.ReleaseDll) Dim diagnostics = comp.GetDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(comp.Assembly, expectedSrcAttrCount:=16, expectedDuplicateAttrCount:=5, attrTypeName:="UserDefinedAssemblyAttrAllowMultipleAttribute") End Sub <Fact(), WorkItem(546963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546963")> Public Sub AssemblyAttributesFromSourceAndNetModuleDropIdentical_02() ' Duplicate ignored attributes in netmodule & source Dim netmoduleAttributes As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' duplicate ]]>.Value Dim sourceAttributes As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str2", Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str1", Text := "str1")> ' unique ]]>.Value Dim netmoduleRef = GetNetModuleWithAssemblyAttributesRef(s_defaultNetModuleSourceHeader & netmoduleAttributes, s_defaultNetModuleSourceBody) Dim comp = CreateCompilationWithMscorlib40({sourceAttributes}, references:={netmoduleRef}, options:=TestOptions.ReleaseDll) Dim diagnostics = comp.GetDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(comp.Assembly, expectedSrcAttrCount:=21, expectedDuplicateAttrCount:=10, attrTypeName:="UserDefinedAssemblyAttrAllowMultipleAttribute") End Sub #End Region <Fact, WorkItem(545527, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545527")> Public Sub CompilationRelaxationsAndRuntimeCompatibility_MultiModule() Dim moduleSrc = <compilation> <file><![CDATA[ Imports System.Runtime.CompilerServices <Assembly:CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)> <Assembly:RuntimeCompatibilityAttribute(WrapNonExceptionThrows:=False)> ]]> </file> </compilation> Dim [module] = CreateCompilationWithMscorlib40(moduleSrc, options:=TestOptions.ReleaseModule) Dim assemblySrc = <compilation> <file> Public Class C End Class </file> </compilation> Dim assembly = CreateCompilationWithMscorlib40(assemblySrc, references:={[module].EmitToImageReference()}) CompileAndVerify(assembly, symbolValidator:= Sub(moduleSymbol) Dim attrs = moduleSymbol.ContainingAssembly.GetAttributes().Select(Function(a) a.ToString()).ToArray() AssertEx.SetEqual({ "System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)", "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows:=False)", "System.Runtime.CompilerServices.CompilationRelaxationsAttribute(System.Runtime.CompilerServices.CompilationRelaxations.NoStringInterning)" }, attrs) End Sub) End Sub <Fact, WorkItem(546460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546460")> Public Sub RuntimeCompatibilityAttribute_False() ' VB emits catch(Exception) even for an empty catch, so it can never catch non-Exception objects. Dim source = <compilation> <file><![CDATA[ Imports System.Runtime.CompilerServices <Assembly:RuntimeCompatibilityAttribute(WrapNonExceptionThrows:=False)> Class C Public Shared Sub Main() Try Catch e As System.Exception Catch End Try End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40AndVBRuntime(source).AssertTheseDiagnostics( <errors> BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ~~~~~ </errors>) End Sub <Fact, WorkItem(530585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530585")> Public Sub Bug16465() Dim modSource = <![CDATA[ Imports System.Configuration.Assemblies Imports System.Reflection <assembly: AssemblyAlgorithmId(AssemblyHashAlgorithm.SHA1)> <assembly: AssemblyCulture("en-US")> <assembly: AssemblyDelaySign(true)> <assembly: AssemblyFlags(AssemblyNameFlags.EnableJITcompileOptimizer Or AssemblyNameFlags.Retargetable Or AssemblyNameFlags.EnableJITcompileTracking)> <assembly: AssemblyVersion("1.2.3.4")> <assembly: AssemblyFileVersion("4.3.2.1")> <assembly: AssemblyTitle("HELLO")> <assembly: AssemblyDescription("World")> <assembly: AssemblyCompany("MS")> <assembly: AssemblyProduct("Roslyn")> <assembly: AssemblyInformationalVersion("Info")> <assembly: AssemblyCopyright("Roslyn")> <assembly: AssemblyTrademark("Roslyn")> class Program1 Shared Sub Main() End Sub End Class ]]> Dim source = <compilation> <file><![CDATA[ Class C End Class ]]> </file> </compilation> Dim appCompilation = CreateCompilationWithMscorlib40AndReferences(source, {GetNetModuleWithAssemblyAttributesRef(modSource.Value, "")}) Dim m = DirectCast(appCompilation.Assembly.Modules(1), PEModuleSymbol) Dim metadata = m.Module Dim metadataReader = metadata.GetMetadataReader() Dim token As EntityHandle = metadata.GetTypeRef(metadata.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHere") Assert.False(token.IsNil()) 'could the type ref be located? If not then the attribute's not there. Dim attributes = m.GetCustomAttributesForToken(token) Dim builder = New System.Text.StringBuilder() For Each attr In attributes builder.AppendLine(attr.ToString()) Next Dim expectedStr = <![CDATA[ System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA1) System.Reflection.AssemblyCultureAttribute("en-US") System.Reflection.AssemblyDelaySignAttribute(True) System.Reflection.AssemblyFlagsAttribute(System.Reflection.AssemblyNameFlags.None Or System.Reflection.AssemblyNameFlags.EnableJITcompileOptimizer Or System.Reflection.AssemblyNameFlags.EnableJITcompileTracking Or System.Reflection.AssemblyNameFlags.Retargetable) System.Reflection.AssemblyVersionAttribute("1.2.3.4") System.Reflection.AssemblyFileVersionAttribute("4.3.2.1") System.Reflection.AssemblyTitleAttribute("HELLO") System.Reflection.AssemblyDescriptionAttribute("World") System.Reflection.AssemblyCompanyAttribute("MS") System.Reflection.AssemblyProductAttribute("Roslyn") System.Reflection.AssemblyInformationalVersionAttribute("Info") System.Reflection.AssemblyCopyrightAttribute("Roslyn") System.Reflection.AssemblyTrademarkAttribute("Roslyn") ]]>.Value.Trim() expectedStr = CompilationUtils.FilterString(expectedStr) Dim actualStr = CompilationUtils.FilterString(builder.ToString().Trim()) Assert.True(expectedStr.Equals(actualStr), AssertEx.GetAssertMessage(expectedStr, actualStr)) End Sub <Fact, WorkItem(530579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530579")> Public Sub Bug530579_1() Dim mod1Source = <compilation name="M1"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module1")> ]]></file> </compilation> Dim mod2Source = <compilation name="M2"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module1")> ]]></file> </compilation> Dim source = <compilation name="M3"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module1")> ]]> </file> </compilation> Dim compMod1 = CreateCompilationWithMscorlib40(mod1Source, options:=TestOptions.ReleaseModule) Dim compMod2 = CreateCompilationWithMscorlib40(mod2Source, options:=TestOptions.ReleaseModule) Dim appCompilation = CreateCompilationWithMscorlib40AndReferences(source, {compMod1.EmitToImageReference(), compMod2.EmitToImageReference()}, options:=TestOptions.ReleaseDll) Assert.Equal(3, appCompilation.Assembly.Modules.Length) CompileAndVerify(appCompilation, symbolValidator:=Sub(m As ModuleSymbol) Dim list As New ArrayBuilder(Of VisualBasicAttributeData) GetAssemblyDescriptionAttributes(m.ContainingAssembly, list) Assert.Equal(1, list.Count) Assert.Equal("System.Reflection.AssemblyDescriptionAttribute(""Module1"")", list(0).ToString()) End Sub).VerifyDiagnostics() End Sub Private Shared Sub GetAssemblyDescriptionAttributes(assembly As AssemblySymbol, list As ArrayBuilder(Of VisualBasicAttributeData)) For Each attrData In assembly.GetAttributes() If attrData.IsTargetAttribute(assembly, AttributeDescription.AssemblyDescriptionAttribute) Then list.Add(attrData) End If Next End Sub <Fact, WorkItem(530579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530579")> Public Sub Bug530579_2() Dim mod1Source = <compilation name="M1"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module1")> ]]></file> </compilation> Dim mod2Source = <compilation name="M2"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module2")> ]]></file> </compilation> Dim source = <compilation name="M3"> <file><![CDATA[ ]]> </file> </compilation> Dim compMod1 = CreateCompilationWithMscorlib40(mod1Source, options:=TestOptions.ReleaseModule) Dim compMod2 = CreateCompilationWithMscorlib40(mod2Source, options:=TestOptions.ReleaseModule) Dim appCompilation = CreateCompilationWithMscorlib40AndReferences(source, {compMod1.EmitToImageReference(), compMod2.EmitToImageReference()}, TestOptions.ReleaseDll) Assert.Equal(3, appCompilation.Assembly.Modules.Length) AssertTheseDiagnostics(appCompilation, <expected> BC42370: Attribute 'AssemblyDescriptionAttribute' from module 'M1.netmodule' will be ignored in favor of the instance appearing in source. </expected>) CompileAndVerify(appCompilation, symbolValidator:=Sub(m As ModuleSymbol) Dim list As New ArrayBuilder(Of VisualBasicAttributeData) GetAssemblyDescriptionAttributes(m.ContainingAssembly, list) Assert.Equal(1, list.Count) Assert.Equal("System.Reflection.AssemblyDescriptionAttribute(""Module2"")", list(0).ToString()) End Sub) End Sub <Fact, WorkItem(530579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530579")> Public Sub Bug530579_3() Dim mod1Source = <compilation name="M1"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module1")> ]]></file> </compilation> Dim mod2Source = <compilation name="M2"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module2")> ]]></file> </compilation> Dim source = <compilation name="M3"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module3")> ]]> </file> </compilation> Dim compMod1 = CreateCompilationWithMscorlib40(mod1Source, options:=TestOptions.ReleaseModule) Dim compMod2 = CreateCompilationWithMscorlib40(mod2Source, options:=TestOptions.ReleaseModule) Dim appCompilation = CreateCompilationWithMscorlib40AndReferences(source, {compMod1.EmitToImageReference(), compMod2.EmitToImageReference()}, TestOptions.ReleaseDll) Assert.Equal(3, appCompilation.Assembly.Modules.Length) AssertTheseDiagnostics(appCompilation, <expected> BC42370: Attribute 'AssemblyDescriptionAttribute' from module 'M1.netmodule' will be ignored in favor of the instance appearing in source. BC42370: Attribute 'AssemblyDescriptionAttribute' from module 'M2.netmodule' will be ignored in favor of the instance appearing in source. </expected>) CompileAndVerify(appCompilation, symbolValidator:=Sub(m As ModuleSymbol) Dim list As New ArrayBuilder(Of VisualBasicAttributeData) GetAssemblyDescriptionAttributes(m.ContainingAssembly, list) Assert.Equal(1, list.Count) Assert.Equal("System.Reflection.AssemblyDescriptionAttribute(""Module3"")", list(0).ToString()) End Sub) End Sub <Fact, WorkItem(530579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530579")> Public Sub Bug530579_4() Dim mod1Source = <compilation name="M1"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module1")> ]]></file> </compilation> Dim mod2Source = <compilation name="M2"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module2")> ]]></file> </compilation> Dim source = <compilation name="M3"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module1")> ]]> </file> </compilation> Dim compMod1 = CreateCompilationWithMscorlib40(mod1Source, options:=TestOptions.ReleaseModule) Dim compMod2 = CreateCompilationWithMscorlib40(mod2Source, options:=TestOptions.ReleaseModule) Dim appCompilation = CreateCompilationWithMscorlib40AndReferences(source, {compMod1.EmitToImageReference(), compMod2.EmitToImageReference()}, TestOptions.ReleaseDll) Assert.Equal(3, appCompilation.Assembly.Modules.Length) AssertTheseDiagnostics(appCompilation, <expected> BC42370: Attribute 'AssemblyDescriptionAttribute' from module 'M2.netmodule' will be ignored in favor of the instance appearing in source. </expected>) CompileAndVerify(appCompilation, symbolValidator:=Sub(m As ModuleSymbol) Dim list As New ArrayBuilder(Of VisualBasicAttributeData) GetAssemblyDescriptionAttributes(m.ContainingAssembly, list) Assert.Equal(1, list.Count) Assert.Equal("System.Reflection.AssemblyDescriptionAttribute(""Module1"")", list(0).ToString()) End Sub) End Sub End Class
' Licensed to the .NET Foundation under one or more 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.IO Imports System.Reflection Imports System.Reflection.Metadata Imports System.Reflection.Metadata.Ecma335 Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.Utilities Public Class AssemblyAttributeTests Inherits BasicTestBase <Fact> Public Sub VersionAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("1.2.3.4")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal(New Version(1, 2, 3, 4), other.Assembly.Identity.Version) End Sub <Fact, WorkItem(543708, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543708")> Public Sub VersionAttribute_FourParts() Dim comp As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("1.22.333.4444")> Public Class C End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) VerifyAssemblyTable(comp, Sub(r) Assert.Equal(New Version(1, 22, 333, 4444), r.Version) End Sub) End Sub <Fact> Public Sub VersionAttribute_TwoParts() Dim comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("1.2")> Public Class C End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) VerifyAssemblyTable(comp, Sub(r) Assert.Equal(1, r.Version.Major) Assert.Equal(2, r.Version.Minor) Assert.Equal(0, r.Version.Build) Assert.Equal(0, r.Version.Revision) End Sub) End Sub <Fact> Public Sub VersionAttribute_WildCard() Dim now = Date.Now Dim days = 0, seconds = 0 VersionTestHelpers.GetDefaultVersion(now, days, seconds) Dim comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("10101.0.*")> Public Class C End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCurrentLocalTime(now)) VerifyAssemblyTable(comp, Sub(r) Assert.Equal(10101, r.Version.Major) Assert.Equal(0, r.Version.Minor) Assert.Equal(days, r.Version.Build) Assert.Equal(seconds, r.Version.Revision) End Sub) End Sub <Fact> Public Sub VersionAttribute_Overflow() Dim comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("10101.0.*")> Public Class C End Class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll.WithCurrentLocalTime(#2300/1/1#)) VerifyAssemblyTable(comp, Sub(r) Assert.Equal(10101, r.Version.Major) Assert.Equal(0, r.Version.Minor) Assert.Equal(65535, r.Version.Build) Assert.Equal(0, r.Version.Revision) End Sub) End Sub <Fact, WorkItem(545948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545948")> Public Sub VersionAttributeErr() Dim comp As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("1.*")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) CompilationUtils.AssertTheseDiagnostics(comp, <error><![CDATA[ BC36962: The specified version string does not conform to the required format - major[.minor[.build|*[.revision|*]]] <Assembly: System.Reflection.AssemblyVersion("1.*")> ~~~~~ ]]></error>) ' --------------------------------------------- comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyVersion("-1")> Public Class C End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) CompilationUtils.AssertTheseDiagnostics(comp, <error><![CDATA[ BC36962: The specified version string does not conform to the required format - major[.minor[.build|*[.revision|*]]] <Assembly: System.Reflection.AssemblyVersion("-1")> ~~~~ ]]></error>) End Sub <Fact, WorkItem(545948, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545948")> Public Sub SatelliteContractVersionAttributeErr() Dim comp As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[<Assembly: System.Resources.SatelliteContractVersionAttribute("1.2.3.A")>]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC36976: The specified version string does not conform to the recommended format - major.minor.build.revision <Assembly: System.Resources.SatelliteContractVersionAttribute("1.2.3.A")> ~~~~~~~~~ ]]></expected>) comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[<Assembly: System.Resources.SatelliteContractVersionAttribute("1.2.*")>]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) CompilationUtils.AssertTheseDiagnostics(comp, <expected><![CDATA[ BC36976: The specified version string does not conform to the recommended format - major.minor.build.revision <Assembly: System.Resources.SatelliteContractVersionAttribute("1.2.*")> ~~~~~~~ ]]></expected>) End Sub <Fact> Public Sub FileVersionAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyFileVersion("1.2.3.4")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("1.2.3.4", DirectCast(other.Assembly, SourceAssemblySymbol).FileVersion) End Sub <Fact> Public Sub FileVersionAttribute_MaxValue() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyFileVersion("65535.65535.65535.65535")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("65535.65535.65535.65535", DirectCast(other.Assembly, SourceAssemblySymbol).FileVersion) End Sub <Fact> Public Sub FileVersionAttribute_MissingParts() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyFileVersion("1.2")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("1.2", DirectCast(other.Assembly, SourceAssemblySymbol).FileVersion) End Sub <Fact> Public Sub FileVersionAttributeWrn_Wildcard() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyFileVersion("1.2.*")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) CompilationUtils.AssertTheseDiagnostics(other, <error><![CDATA[ BC42366: The specified version string does not conform to the recommended format - major.minor.build.revision <Assembly: System.Reflection.AssemblyFileVersion("1.2.*")> ~~~~~~~ ]]></error>) End Sub <Fact> Public Sub FileVersionAttributeWrn_OutOfRange() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyFileVersion("1.65536")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) CompilationUtils.AssertTheseDiagnostics(other, <error><![CDATA[ BC42366: The specified version string does not conform to the recommended format - major.minor.build.revision <Assembly: System.Reflection.AssemblyFileVersion("1.65536")> ~~~~~~~~~ ]]></error>) End Sub <Fact> Public Sub TitleAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyTitle("One Hundred Years Of Solitude")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("One Hundred Years Of Solitude", DirectCast(other.Assembly, SourceAssemblySymbol).Title) Assert.Equal(False, DirectCast(other.Assembly, SourceAssemblySymbol).MightContainNoPiaLocalTypes()) End Sub <Fact> Public Sub TitleAttributeNothing() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyTitle(Nothing)> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Null(DirectCast(other.Assembly, SourceAssemblySymbol).Title) End Sub <Fact> Public Sub DescriptionAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyDescription("A classic of magical realist literature")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("A classic of magical realist literature", DirectCast(other.Assembly, SourceAssemblySymbol).Description) End Sub <Fact> Public Sub CultureAttribute() Dim src = <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCulture("pt-BR")> Public Class C Shared Sub Main() End Sub End Class ]]> </file> </compilation> Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40(src, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("pt-BR", other.Assembly.Identity.CultureName) End Sub <Fact> Public Sub CultureAttribute02() Dim comp As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCulture("")> ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) VerifyAssemblyTable(comp, Sub(r) Assert.True(r.Culture.IsNil)) comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCulture(Nothing)> ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) VerifyAssemblyTable(comp, Sub(r) Assert.True(r.Culture.IsNil)) comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCulture("ja-JP")> ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) VerifyAssemblyTable(comp, Nothing, strData:="ja-JP") End Sub <Fact> Public Sub CultureAttribute03() Dim comp As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCulture("")> Public Class C Shared Sub Main() End Sub End Class ]]> </file> </compilation>, OutputKind.ConsoleApplication) VerifyAssemblyTable(comp, Sub(r) Assert.True(r.Culture.IsNil)) comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCulture(Nothing)> Public Class C Shared Sub Main() End Sub End Class ]]> </file> </compilation>, OutputKind.ConsoleApplication) VerifyAssemblyTable(comp, Sub(r) Assert.True(r.Culture.IsNil)) End Sub <Fact> Public Sub CultureAttributeNul() Dim comp As VisualBasicCompilation = CreateCompilationWithMscorlib40AndVBRuntime( <compilation> <file name="a.vb"><![CDATA[ Imports Microsoft.VisualBasic <Assembly: System.Reflection.AssemblyCulture(vbNullChar)> ]]> </file> </compilation>, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) CompilationUtils.AssertTheseDiagnostics(comp, <error><![CDATA[ BC36982: Assembly culture strings may not contain embedded NUL characters. <Assembly: System.Reflection.AssemblyCulture(vbNullChar)> ~~~~~~~~~~ ]]></error>) End Sub <Fact, WorkItem(545951, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545951")> Public Sub CultureAttributeErr() Dim src = <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCulture("pt-BR")> Public Class C Shared Sub Main() End Sub End Class ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(src, OutputKind.ConsoleApplication) CompilationUtils.AssertTheseDiagnostics(comp, <error><![CDATA[ BC36977: Executables cannot be satellite assemblies; culture should always be empty <Assembly: System.Reflection.AssemblyCulture("pt-BR")> ~~~~~~~ ]]></error>) End Sub <Fact> <WorkItem(5866, "https://github.com/dotnet/roslyn/issues/5866")> Public Sub CultureAttributeMismatch() Dim neutral As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="neutral"> <file name="a.vb"><![CDATA[ public class neutral end class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll) Dim neutralRef = New VisualBasicCompilationReference(neutral) Dim en_UK As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="en_UK"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCultureAttribute("en-UK")> public class en_UK end class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll) Dim en_UKRef = New VisualBasicCompilationReference(en_UK) Dim en_us As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation name="en_us"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCultureAttribute("en-us")> public class en_us end class ]]> </file> </compilation>, options:=TestOptions.ReleaseDll) Dim en_usRef = New VisualBasicCompilationReference(en_us) Dim compilation As VisualBasicCompilation compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCultureAttribute("en-US")> public class en_US Sub M(x as en_UK) End Sub end class ]]> </file> </compilation>, {en_UKRef, neutralRef}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC42371: Referenced assembly 'en_UK, Version=0.0.0.0, Culture=en-UK, PublicKeyToken=null' has different culture setting of 'en-UK'. </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseModule) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> </expected>) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> </file> </compilation>, {compilation.EmitToImageReference()}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC42371: Referenced assembly 'en_UK, Version=0.0.0.0, Culture=en-UK, PublicKeyToken=null' has different culture setting of 'en-UK'. </expected>) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="CultureAttributeMismatch1"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCultureAttribute("en-US")> public class Test Sub M(x as en_us) End Sub end class ]]> </file> </compilation>, {en_usRef}, TestOptions.ReleaseDll) CompileAndVerify(compilation).VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.ReleaseModule) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> </expected>) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="CultureAttributeMismatch2"> <file name="a.vb"> </file> </compilation>, {compilation.EmitToImageReference()}, TestOptions.ReleaseDll) CompileAndVerify(compilation, dependencies:={New ModuleData(en_usRef.Compilation.Assembly.Identity, OutputKind.DynamicallyLinkedLibrary, en_usRef.Compilation.EmitToArray(), ImmutableArray(Of Byte).Empty, False)}). VerifyDiagnostics() compilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="CultureAttributeMismatch3"> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCultureAttribute("en-US")> public class en_US Sub M(x as neutral) End Sub end class ]]> </file> </compilation>, {en_UKRef, neutralRef}, TestOptions.ReleaseDll) CompileAndVerify(compilation).VerifyDiagnostics() compilation = compilation.WithOptions(TestOptions.ReleaseModule) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> </expected>) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation name="CultureAttributeMismatch4"> <file name="a.vb"> </file> </compilation>, {compilation.EmitToImageReference()}, TestOptions.ReleaseDll) CompileAndVerify(compilation, dependencies:={New ModuleData(en_UKRef.Compilation.Assembly.Identity, OutputKind.DynamicallyLinkedLibrary, en_UKRef.Compilation.EmitToArray(), ImmutableArray(Of Byte).Empty, False), New ModuleData(neutralRef.Compilation.Assembly.Identity, OutputKind.DynamicallyLinkedLibrary, neutralRef.Compilation.EmitToArray(), ImmutableArray(Of Byte).Empty, False)}, sourceSymbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(1, m.GetReferencedAssemblySymbols().Length) Dim naturalRef = m.ContainingAssembly.Modules(1).GetReferencedAssemblySymbols(1) Assert.True(naturalRef.IsMissing) Assert.Equal("neutral, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", naturalRef.ToTestDisplayString()) End Sub, symbolValidator:=Sub(m As ModuleSymbol) Assert.Equal(2, m.GetReferencedAssemblySymbols().Length) Assert.Equal("neutral, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", m.GetReferencedAssemblySymbols()(1).ToTestDisplayString()) End Sub). VerifyDiagnostics() compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ public class neutral Sub M(x as en_UK) End Sub end class ]]> </file> </compilation>, {en_UKRef}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC42371: Referenced assembly 'en_UK, Version=0.0.0.0, Culture=en-UK, PublicKeyToken=null' has different culture setting of 'en-UK'. </expected>) compilation = compilation.WithOptions(TestOptions.ReleaseModule) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> </expected>) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"> </file> </compilation>, {compilation.EmitToImageReference()}, TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC42371: Referenced assembly 'en_UK, Version=0.0.0.0, Culture=en-UK, PublicKeyToken=null' has different culture setting of 'en-UK'. </expected>) End Sub <Fact> Public Sub CompanyAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCompany("MossBrain")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("MossBrain", DirectCast(other.Assembly, SourceAssemblySymbol).Company) other = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[<Assembly: System.Reflection.AssemblyCompany("微软")>]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("微软", DirectCast(other.Assembly, SourceAssemblySymbol).Company) End Sub <Fact> Public Sub ProductAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyProduct("Sound Cannon")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("Sound Cannon", DirectCast(other.Assembly, SourceAssemblySymbol).Product) End Sub <Fact> Public Sub CopyrightAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyCopyright("مايكروسوفت")> Public Structure S End Structure ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("مايكروسوفت", DirectCast(other.Assembly, SourceAssemblySymbol).Copyright) End Sub <Fact> Public Sub TrademarkAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyTrademark("circle r")> Interface IGoo End Interface ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) Assert.Empty(other.GetDiagnostics()) Assert.Equal("circle r", DirectCast(other.Assembly, SourceAssemblySymbol).Trademark) End Sub <Fact> Public Sub InformationalVersionAttribute() Dim other As VisualBasicCompilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <Assembly: System.Reflection.AssemblyInformationalVersion("1.2.3garbage")> Public Class C Friend Sub Goo() End Sub End Class ]]> </file> </compilation>, OutputKind.DynamicallyLinkedLibrary) other.VerifyEmitDiagnostics() Assert.Equal("1.2.3garbage", DirectCast(other.Assembly, SourceAssemblySymbol).InformationalVersion) End Sub <Fact(), WorkItem(529922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529922")> Public Sub AlgorithmIdAttribute() Dim hash_module = TestReferences.SymbolsTests.netModule.hash_module Dim hash_resources = {New ResourceDescription("hash_resource", "snKey.snk", Function() New MemoryStream(TestResources.General.snKey, writable:=False), True)} Dim compilation As VisualBasicCompilation compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={hash_module}) CompileAndVerify(compilation, manifestResources:=hash_resources, validator:=Sub(peAssembly) Dim reader = peAssembly.ManifestModule.GetMetadataReader() Dim assembly As AssemblyDefinition = reader.GetAssemblyDefinition() Assert.Equal(AssemblyHashAlgorithm.Sha1, assembly.HashAlgorithm) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Assert.Equal(New Byte() {&H6C, &H9C, &H3E, &HDA, &H60, &HF, &H81, &H93, &H4A, &HC1, &HD, &H41, &HB3, &HE9, &HB2, &HB7, &H2D, &HEE, &H59, &HA8}, reader.GetBlobBytes(file1.HashValue)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal(New Byte() {&H7F, &H28, &HEA, &HD1, &HF4, &HA1, &H7C, &HB8, &HC, &H14, &HC0, &H2E, &H8C, &HFF, &H10, &HEC, &HB3, &HC2, &HA5, &H1D}, reader.GetBlobBytes(file2.HashValue)) Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)) End Sub) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.None)> class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={hash_module}) CompileAndVerify(compilation, manifestResources:=hash_resources, validator:=Sub(peAssembly) Dim reader = peAssembly.ManifestModule.GetMetadataReader() Dim assembly As AssemblyDefinition = reader.GetAssemblyDefinition() Assert.Equal(AssemblyHashAlgorithm.None, assembly.HashAlgorithm) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Assert.Equal(New Byte() {&H6C, &H9C, &H3E, &HDA, &H60, &HF, &H81, &H93, &H4A, &HC1, &HD, &H41, &HB3, &HE9, &HB2, &HB7, &H2D, &HEE, &H59, &HA8}, reader.GetBlobBytes(file1.HashValue)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal(New Byte() {&H7F, &H28, &HEA, &HD1, &HF4, &HA1, &H7C, &HB8, &HC, &H14, &HC0, &H2E, &H8C, &HFF, &H10, &HEC, &HB3, &HC2, &HA5, &H1D}, reader.GetBlobBytes(file2.HashValue)) Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)) End Sub) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(CUInt(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5))> class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={hash_module}) CompileAndVerify(compilation, manifestResources:=hash_resources, validator:=Sub(peAssembly) Dim reader = peAssembly.ManifestModule.GetMetadataReader() Dim assembly As AssemblyDefinition = reader.GetAssemblyDefinition() Assert.Equal(AssemblyHashAlgorithm.MD5, assembly.HashAlgorithm) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Assert.Equal(New Byte() {&H24, &H22, &H3, &HC3, &H94, &HD5, &HC2, &HD9, &H99, &HB3, &H6D, &H59, &HB2, &HCA, &H23, &HBC}, reader.GetBlobBytes(file1.HashValue)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal(New Byte() {&H8D, &HFE, &HBF, &H49, &H8D, &H62, &H2A, &H88, &H89, &HD1, &HE, &H0, &H9E, &H29, &H72, &HF1}, reader.GetBlobBytes(file2.HashValue)) Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)) End Sub) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA1)> class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={hash_module}) CompileAndVerify(compilation, manifestResources:=hash_resources, validator:=Sub(peAssembly) Dim reader = peAssembly.ManifestModule.GetMetadataReader() Dim assembly As AssemblyDefinition = reader.GetAssemblyDefinition() Assert.Equal(AssemblyHashAlgorithm.Sha1, assembly.HashAlgorithm) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Assert.Equal(New Byte() {&H6C, &H9C, &H3E, &HDA, &H60, &HF, &H81, &H93, &H4A, &HC1, &HD, &H41, &HB3, &HE9, &HB2, &HB7, &H2D, &HEE, &H59, &HA8}, reader.GetBlobBytes(file1.HashValue)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal(New Byte() {&H7F, &H28, &HEA, &HD1, &HF4, &HA1, &H7C, &HB8, &HC, &H14, &HC0, &H2E, &H8C, &HFF, &H10, &HEC, &HB3, &HC2, &HA5, &H1D}, reader.GetBlobBytes(file2.HashValue)) Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)) End Sub) compilation = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA256)> class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={MscorlibRef_v4_0_30316_17626, hash_module}) CompileAndVerify(compilation, verify:=Verification.Fails, manifestResources:=hash_resources, validator:=Sub(peAssembly) Dim reader = peAssembly.ManifestModule.GetMetadataReader() Dim assembly As AssemblyDefinition = reader.GetAssemblyDefinition() Assert.Equal(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA256, CType(assembly.HashAlgorithm, System.Configuration.Assemblies.AssemblyHashAlgorithm)) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Assert.Equal(New Byte() {&HA2, &H32, &H3F, &HD, &HF4, &HB8, &HED, &H5A, &H1B, &H7B, &HBE, &H14, &H4F, &HEC, &HBF, &H88, &H23, &H61, &HEB, &H40, &HF7, &HF9, &H46, &HEF, &H68, &H3B, &H70, &H29, &HCF, &H12, &H5, &H35}, reader.GetBlobBytes(file1.HashValue)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal(New Byte() {&HCC, &HAE, &HA0, &HB4, &H9E, &HAE, &H28, &HE0, &HA3, &H46, &HE9, &HCF, &HF3, &HEF, &HEA, &HF7, &H1D, &HDE, &H62, &H8F, &HD6, &HF4, &H87, &H76, &H1A, &HC3, &H6F, &HAD, &H10, &H1C, &H10, &HAC}, reader.GetBlobBytes(file2.HashValue)) Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)) End Sub) compilation = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA384)> class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={MscorlibRef_v4_0_30316_17626, hash_module}) CompileAndVerify(compilation, verify:=Verification.Fails, manifestResources:=hash_resources, validator:=Sub(peAssembly) Dim reader = peAssembly.ManifestModule.GetMetadataReader() Dim assembly As AssemblyDefinition = reader.GetAssemblyDefinition() Assert.Equal(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA384, CType(assembly.HashAlgorithm, System.Configuration.Assemblies.AssemblyHashAlgorithm)) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Assert.Equal(New Byte() {&HB6, &H35, &H9B, &HBE, &H82, &H89, &HFF, &H1, &H22, &H8B, &H56, &H5E, &H9B, &H15, &H5D, &H10, &H68, &H83, &HF7, &H75, &H4E, &HA6, &H30, &HF7, &H8D, &H39, &H9A, &HB7, &HE8, &HB6, &H47, &H1F, &HF6, &HFD, &H1E, &H64, &H63, &H6B, &HE7, &HF4, &HBE, &HA7, &H21, &HED, &HFC, &H82, &H38, &H95}, reader.GetBlobBytes(file1.HashValue)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal(New Byte() {&H45, &H5, &H2E, &H90, &H9B, &H61, &HA3, &HF8, &H60, &HD2, &H86, &HCB, &H10, &H33, &HC9, &H86, &H68, &HA5, &HEE, &H4A, &HCF, &H21, &H10, &HA9, &H8F, &H14, &H62, &H8D, &H3E, &H7D, &HFD, &H7E, &HE6, &H23, &H6F, &H2D, &HBA, &H4, &HE7, &H13, &HE4, &H5E, &H8C, &HEB, &H80, &H68, &HA3, &H17}, reader.GetBlobBytes(file2.HashValue)) Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)) End Sub) compilation = CreateEmptyCompilationWithReferences( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA512)> class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={MscorlibRef_v4_0_30316_17626, hash_module}) CompileAndVerify(compilation, verify:=Verification.Fails, manifestResources:=hash_resources, validator:=Sub(peAssembly) Dim reader = peAssembly.ManifestModule.GetMetadataReader() Dim assembly As AssemblyDefinition = reader.GetAssemblyDefinition() Assert.Equal(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA512, CType(assembly.HashAlgorithm, System.Configuration.Assemblies.AssemblyHashAlgorithm)) Dim file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)) Assert.Equal(New Byte() {&H5F, &H4D, &H7E, &H63, &HC9, &H87, &HD9, &HEB, &H4F, &H5C, &HFD, &H96, &H3F, &H25, &H58, &H74, &H86, &HDF, &H97, &H75, &H93, &HEE, &HC2, &H5F, &HFD, &H8A, &H40, &H5C, &H92, &H5E, &HB5, &H7, &HD6, &H12, &HE9, &H21, &H55, &HCE, &HD7, &HE5, &H15, &HF5, &HBA, &HBC, &H1B, &H31, &HAD, &H3C, &H5E, &HE0, &H91, &H98, &HC2, &HE0, &H96, &HBB, &HAD, &HD, &H4E, &HF4, &H91, &H53, &H3D, &H84}, reader.GetBlobBytes(file1.HashValue)) Dim file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)) Assert.Equal(New Byte() {&H79, &HFE, &H97, &HAB, &H8, &H8E, &HDF, &H74, &HC2, &HEF, &H84, &HBB, &HFC, &H74, &HAC, &H60, &H18, &H6E, &H1A, &HD2, &HC5, &H94, &HE0, &HDA, &HE0, &H45, &H33, &H43, &H99, &HF0, &HF3, &HF1, &H72, &H5, &H4B, &HF, &H37, &H50, &HC5, &HD9, &HCE, &H29, &H82, &H4C, &HF7, &HE6, &H94, &H5F, &HE5, &H7, &H2B, &H4A, &H18, &H9, &H56, &HC9, &H52, &H69, &H7D, &HC4, &H48, &H63, &H70, &HF2}, reader.GetBlobBytes(file2.HashValue)) Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)) End Sub) Dim hash_module_Comp = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)> public class Test end class ]]></file> </compilation>, options:=TestOptions.ReleaseModule) compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={hash_module_Comp.EmitToImageReference()}) CompileAndVerify(compilation, validator:=Sub(peAssembly) Dim metadataReader = peAssembly.ManifestModule.GetMetadataReader() Dim assembly As AssemblyDefinition = metadataReader.GetAssemblyDefinition() Assert.Equal(AssemblyHashAlgorithm.MD5, assembly.HashAlgorithm) Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)) End Sub) compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345UI)> class Program Sub M() End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll) ' no error reported if we don't need to hash compilation.VerifyEmitDiagnostics() compilation = CreateCompilationWithMscorlib40AndReferences( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345UI)> class Program Sub M(x As Test) End Sub end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll, references:={hash_module}) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream()).Diagnostics, <expected> BC37215: Cryptographic failure while creating hashes. </expected>) compilation = CreateCompilationWithMscorlib40( <compilation> <file name="a.vb"><![CDATA[ <assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345UI)> class Program end class ]]></file> </compilation>, options:=TestOptions.ReleaseDll) AssertTheseDiagnostics(compilation.Emit(New System.IO.MemoryStream(), manifestResources:=hash_resources).Diagnostics, <expected> BC37215: Cryptographic failure while creating hashes. </expected>) Dim comp = CreateVisualBasicCompilation("AlgorithmIdAttribute", <![CDATA[<Assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)>]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) VerifyAssemblyTable(comp, Sub(r) Assert.Equal(AssemblyHashAlgorithm.MD5, r.HashAlgorithm) End Sub) ' comp = CreateVisualBasicCompilation("AlgorithmIdAttribute1", <![CDATA[<Assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.None)>]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) VerifyAssemblyTable(comp, Sub(r) Assert.Equal(AssemblyHashAlgorithm.None, r.HashAlgorithm) End Sub) ' comp = CreateVisualBasicCompilation("AlgorithmIdAttribute2", <![CDATA[<Assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345UI)>]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) VerifyAssemblyTable(comp, Sub(r) Assert.Equal(12345, CInt(r.HashAlgorithm))) End Sub <Fact()> Public Sub AssemblyFlagsAttribute() Dim comp = CreateVisualBasicCompilation("AssemblyFlagsAttribute", <![CDATA[ Imports System.Reflection <Assembly: AssemblyFlags(AssemblyNameFlags.EnableJITcompileOptimizer Or AssemblyNameFlags.Retargetable)>]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) VerifyAssemblyTable(comp, Sub(r) Assert.Equal(AssemblyFlags.DisableJitCompileOptimizer Or AssemblyFlags.Retargetable, r.Flags) End Sub) End Sub <Fact, WorkItem(546635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546635")> Public Sub AssemblyFlagsAttribute02() Dim comp = CreateVisualBasicCompilation("AssemblyFlagsAttribute02", <![CDATA[<Assembly: System.Reflection.AssemblyFlags(12345)>]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) ' Both native & Roslyn PEVerifier fail: [MD]: Error: Invalid Assembly flags (0x3038). [token:0x20000001] VerifyAssemblyTable(comp, Sub(r) Assert.Equal(12345 - 1, CInt(r.Flags)) End Sub) comp.VerifyDiagnostics( Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "Assembly: System.Reflection.AssemblyFlags(12345)").WithArguments("Public Overloads Sub New(assemblyFlags As Integer)", "This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202")) End Sub <Fact> Public Sub AssemblyFlagsAttribute03() Dim comp = CreateVisualBasicCompilation("AssemblyFlagsAttribute02", <![CDATA[<Assembly: System.Reflection.AssemblyFlags(12345UI)>]]>, compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)) ' Both native & Roslyn PEVerifier fail: [MD]: Error: Invalid Assembly flags (0x3038). [token:0x20000001] VerifyAssemblyTable(comp, Sub(r) Assert.Equal(12345 - 1, CInt(r.Flags)) End Sub) comp.VerifyDiagnostics( Diagnostic(ERRID.WRN_UseOfObsoleteSymbol2, "Assembly: System.Reflection.AssemblyFlags(12345UI)").WithArguments("Public Overloads Sub New(flags As UInteger)", "This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202")) End Sub #Region "Metadata Verifier (TODO: consolidate with others)" Friend Sub VerifyAssemblyTable(comp As VisualBasicCompilation, verifier As Action(Of AssemblyDefinition), Optional strData As String = Nothing) Dim stream = New MemoryStream() Assert.True(comp.Emit(stream).Success) Using mt = ModuleMetadata.CreateFromImage(stream.ToImmutable()) Dim metadataReader = mt.Module.GetMetadataReader() Dim row As AssemblyDefinition = metadataReader.GetAssemblyDefinition() If verifier IsNot Nothing Then verifier(row) End If ' tmp If strData IsNot Nothing Then Assert.Equal(strData, metadataReader.GetString(row.Culture)) End If End Using End Sub #End Region #Region "NetModule Assembly attribute tests" #Region "Helpers" Private Shared ReadOnly s_defaultNetModuleSourceHeader As String = <![CDATA[ Imports System Imports System.Reflection Imports System.Security.Permissions <Assembly: AssemblyTitle("AssemblyTitle")> <Assembly: FileIOPermission(SecurityAction.RequestOptional)> <Assembly: UserDefinedAssemblyAttrNoAllowMultiple("UserDefinedAssemblyAttrNoAllowMultiple")> <Assembly: UserDefinedAssemblyAttrAllowMultiple("UserDefinedAssemblyAttrAllowMultiple")> ]]>.Value Private Shared ReadOnly s_defaultNetModuleSourceBody As String = <![CDATA[ Public Class NetModuleClass End Class <AttributeUsage(AttributeTargets.Assembly, AllowMultiple := False)> Public Class UserDefinedAssemblyAttrNoAllowMultipleAttribute Inherits Attribute Public Property Text() As String Public Property Text2() As String Public Sub New(text1 As String) Text = text1 End Sub Public Sub New(text1 As Integer) Text = text1.ToString() End Sub End Class <AttributeUsage(AttributeTargets.Assembly, AllowMultiple := True)> Public Class UserDefinedAssemblyAttrAllowMultipleAttribute Inherits Attribute Public Property Text() As String Public Property Text2() As String Public Sub New(text1 As String) Text = text1 End Sub Public Sub New(text1 As Integer) Text = text1.ToString() End Sub End Class ]]>.Value Private Function GetNetModuleWithAssemblyAttributesRef(Optional netModuleSourceHeader As String = Nothing, Optional netModuleSourceBody As String = Nothing, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional nameSuffix As String = "") As MetadataReference Return GetNetModuleWithAssemblyAttributes(netModuleSourceHeader, netModuleSourceBody, references, nameSuffix).GetReference() End Function Private Function GetNetModuleWithAssemblyAttributes(Optional netModuleSourceHeader As String = Nothing, Optional netModuleSourceBody As String = Nothing, Optional references As IEnumerable(Of MetadataReference) = Nothing, Optional nameSuffix As String = "") As ModuleMetadata Dim netmoduleSource As String = If(netModuleSourceHeader, s_defaultNetModuleSourceHeader) & If(netModuleSourceBody, s_defaultNetModuleSourceBody) Dim netmoduleCompilation = CreateCompilationWithMscorlib40({netmoduleSource}, references:=references, options:=TestOptions.ReleaseModule, assemblyName:="NetModuleWithAssemblyAttributes" & nameSuffix) Dim diagnostics = netmoduleCompilation.GetDiagnostics() Dim bytes = netmoduleCompilation.EmitToArray() Return ModuleMetadata.CreateFromImage(bytes) End Function Private Shared Sub TestDuplicateAssemblyAttributesNotEmitted(assembly As AssemblySymbol, expectedSrcAttrCount As Integer, expectedDuplicateAttrCount As Integer, attrTypeName As String) ' SOURCE ATTRIBUTES Dim allSrcAttrs = assembly.GetAttributes() Dim srcAttrs = allSrcAttrs.Where(Function(a) a.AttributeClass.Name.Equals(attrTypeName)).AsImmutable() Assert.Equal(expectedSrcAttrCount, srcAttrs.Length) ' EMITTED ATTRIBUTES Dim compilation = assembly.DeclaringCompilation compilation.GetDiagnostics() compilation.EmbeddedSymbolManager.MarkAllDeferredSymbolsAsReferenced(compilation) ' We should get only unique netmodule/assembly attributes here, duplicate ones should not be emitted. Dim expectedEmittedAttrsCount As Integer = expectedSrcAttrCount - expectedDuplicateAttrCount Dim allEmittedAttrs = DirectCast(assembly, SourceAssemblySymbol). GetAssemblyCustomAttributesToEmit(New ModuleCompilationState, emittingRefAssembly:=False, emittingAssemblyAttributesInNetModule:=False). Cast(Of VisualBasicAttributeData)() Dim emittedAttrs = allEmittedAttrs.Where(Function(a) a.AttributeClass.Name.Equals(attrTypeName)).AsImmutable() Assert.Equal(expectedEmittedAttrsCount, emittedAttrs.Length) Dim uniqueAttributes = New HashSet(Of VisualBasicAttributeData)(comparer:=CommonAttributeDataComparer.Instance) For Each attr In emittedAttrs Assert.True(uniqueAttributes.Add(attr)) Next End Sub #End Region <Fact()> Public Sub AssemblyAttributesFromNetModule() Dim consoleappSource = <compilation> <file name="a.vb"> <![CDATA[ Class Program Private Shared Sub Main(args As String()) End Sub End Class ]]> </file> </compilation> Dim netModuleWithAssemblyAttributes = GetNetModuleWithAssemblyAttributes() Dim metadata As PEModule = netModuleWithAssemblyAttributes.Module Dim metadataReader = metadata.GetMetadataReader() Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)) Assert.Equal(18, metadataReader.CustomAttributes.Count) Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count) Dim token As EntityHandle = metadata.GetTypeRef(metadata.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM") Assert.False(token.IsNil) 'could the type ref be located? If not then the attribute's not there. Dim consoleappCompilation = CreateCompilationWithMscorlib40AndReferences(consoleappSource, {netModuleWithAssemblyAttributes.GetReference()}) Assert.NotNull(consoleappCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHere")) Assert.NotNull(consoleappCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHereM")) Dim diagnostics = consoleappCompilation.GetDiagnostics() Dim attrs = consoleappCompilation.Assembly.GetAttributes() Assert.Equal(4, attrs.Length) For Each a In attrs Select Case a.AttributeClass.Name Case "AssemblyTitleAttribute" Assert.Equal("System.Reflection.AssemblyTitleAttribute(""AssemblyTitle"")", a.ToString()) Exit Select Case "FileIOPermissionAttribute" Assert.Equal("System.Security.Permissions.FileIOPermissionAttribute(System.Security.Permissions.SecurityAction.RequestOptional)", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrNoAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")", a.ToString()) Exit Select Case Else Assert.Equal("Unexpected Attr", a.AttributeClass.Name) Exit Select End Select Next metadata = AssemblyMetadata.CreateFromImage(consoleappCompilation.EmitToArray()).GetAssembly.ManifestModule metadataReader = metadata.GetMetadataReader() Assert.Equal(1, metadataReader.GetTableRowCount(TableIndex.ModuleRef)) Assert.Equal(3, metadataReader.GetTableRowCount(TableIndex.ExportedType)) Assert.Equal(6, metadataReader.CustomAttributes.Count) Assert.Equal(1, metadataReader.DeclarativeSecurityAttributes.Count) token = metadata.GetTypeRef(metadata.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM") Assert.True(token.IsNil) 'could the type ref be located? If not then the attribute's not there. consoleappCompilation = CreateCompilationWithMscorlib40AndReferences(consoleappSource, {netModuleWithAssemblyAttributes.GetReference()}, TestOptions.ReleaseModule) Assert.Equal(0, consoleappCompilation.Assembly.GetAttributes().Length) Dim modRef = DirectCast(consoleappCompilation.EmitToImageReference(), MetadataImageReference) metadata = ModuleMetadata.CreateFromImage(consoleappCompilation.EmitToArray()).Module metadataReader = metadata.GetMetadataReader() Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ModuleRef)) Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)) Assert.Equal(0, metadataReader.CustomAttributes.Count) Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count) token = metadata.GetTypeRef(metadata.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM") Assert.True(token.IsNil) 'could the type ref be located? If not then the attribute's not there. End Sub <Fact()> <WorkItem(10550, "https://github.com/dotnet/roslyn/issues/10550")> Public Sub AssemblyAttributesFromNetModule_WithoutAssemblyAttributesGoHereTypes() Dim netmoduleSource = <compilation> <file name="a.vb"> <![CDATA[ Imports System <Assembly: UserDefinedAssemblyAttrNoAllowMultiple("UserDefinedAssemblyAttrNoAllowMultiple")> <Assembly: UserDefinedAssemblyAttrAllowMultiple("UserDefinedAssemblyAttrAllowMultiple")> Public Class NetModuleClass End Class <AttributeUsage(AttributeTargets.Assembly, AllowMultiple := False)> Public Class UserDefinedAssemblyAttrNoAllowMultipleAttribute Inherits Attribute Public Sub New(text1 As String) End Sub End Class <AttributeUsage(AttributeTargets.Assembly, AllowMultiple := True)> Public Class UserDefinedAssemblyAttrAllowMultipleAttribute Inherits Attribute Public Sub New(text1 As String) End Sub End Class ]]> </file> </compilation> Dim consoleappSource = <compilation> <file name="a.vb"> <![CDATA[ Class Program Private Shared Sub Main(args As String()) End Sub End Class ]]> </file> </compilation> Dim netmoduleCompilation = CreateEmptyCompilationWithReferences(netmoduleSource, references:={MinCorlibRef}, options:=TestOptions.ReleaseModule) Assert.Null(netmoduleCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHere")) Assert.Null(netmoduleCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHereM")) Dim bytes = netmoduleCompilation.EmitToArray() Dim netModuleWithAssemblyAttributes = ModuleMetadata.CreateFromImage(bytes) Dim metadata As PEModule = netModuleWithAssemblyAttributes.Module Dim metadataReader = metadata.GetMetadataReader() Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)) Assert.Equal(4, metadataReader.CustomAttributes.Count) Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count) Dim token As EntityHandle = metadata.GetTypeRef(metadata.GetAssemblyRef("mincorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM") Assert.False(token.IsNil) 'could the type ref be located? If not then the attribute's not there. Dim consoleappCompilation = CreateEmptyCompilationWithReferences(consoleappSource, {MinCorlibRef, netModuleWithAssemblyAttributes.GetReference()}) Assert.Null(consoleappCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHere")) Assert.Null(consoleappCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHereM")) consoleappCompilation.GetDiagnostics().Verify() Dim attrs = consoleappCompilation.Assembly.GetAttributes() Assert.Equal(2, attrs.Length) For Each a In attrs Select Case a.AttributeClass.Name Case "UserDefinedAssemblyAttrNoAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")", a.ToString()) Exit Select Case Else Assert.Equal("Unexpected Attr", a.AttributeClass.Name) Exit Select End Select Next metadata = AssemblyMetadata.CreateFromImage(consoleappCompilation.EmitToArray()).GetAssembly.ManifestModule metadataReader = metadata.GetMetadataReader() Assert.Equal(1, metadataReader.GetTableRowCount(TableIndex.ModuleRef)) Assert.Equal(3, metadataReader.GetTableRowCount(TableIndex.ExportedType)) Assert.Equal(2, metadataReader.CustomAttributes.Count) Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count) token = metadata.GetTypeRef(metadata.GetAssemblyRef("mincorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM") Assert.True(token.IsNil) 'could the type ref be located? If not then the attribute's not there. consoleappCompilation = CreateEmptyCompilationWithReferences(consoleappSource, {MinCorlibRef, netModuleWithAssemblyAttributes.GetReference()}, TestOptions.ReleaseModule) Assert.Equal(0, consoleappCompilation.Assembly.GetAttributes().Length) Dim modRef = DirectCast(consoleappCompilation.EmitToImageReference(), MetadataImageReference) metadata = ModuleMetadata.CreateFromImage(consoleappCompilation.EmitToArray()).Module metadataReader = metadata.GetMetadataReader() Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ModuleRef)) Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)) Assert.Equal(0, metadataReader.CustomAttributes.Count) Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count) token = metadata.GetTypeRef(metadata.GetAssemblyRef("mincorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM") Assert.True(token.IsNil) 'could the type ref be located? If not then the attribute's not there. End Sub <Fact()> Public Sub AssemblyAttributesFromNetModuleDropIdentical() Dim consoleappSource = <compilation> <file name="a.vb"> <![CDATA[ <Assembly: UserDefinedAssemblyAttrNoAllowMultiple("UserDefinedAssemblyAttrNoAllowMultiple")> <Assembly: UserDefinedAssemblyAttrAllowMultiple("UserDefinedAssemblyAttrAllowMultiple")> Class Program Private Shared Sub Main(args As String()) End Sub End Class ]]> </file> </compilation> Dim consoleappCompilation = CreateCompilationWithMscorlib40AndReferences(consoleappSource, {GetNetModuleWithAssemblyAttributesRef()}) Dim diagnostics = consoleappCompilation.GetDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(consoleappCompilation.Assembly, expectedSrcAttrCount:=2, expectedDuplicateAttrCount:=1, attrTypeName:="UserDefinedAssemblyAttrAllowMultipleAttribute") TestDuplicateAssemblyAttributesNotEmitted(consoleappCompilation.Assembly, expectedSrcAttrCount:=2, expectedDuplicateAttrCount:=1, attrTypeName:="UserDefinedAssemblyAttrNoAllowMultipleAttribute") Dim attrs = consoleappCompilation.Assembly.GetAttributes() For Each a In attrs Select Case a.AttributeClass.Name Case "AssemblyTitleAttribute" Assert.Equal("System.Reflection.AssemblyTitleAttribute(""AssemblyTitle"")", a.ToString()) Exit Select Case "FileIOPermissionAttribute" Assert.Equal("System.Security.Permissions.FileIOPermissionAttribute(System.Security.Permissions.SecurityAction.RequestOptional)", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrNoAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")", a.ToString()) Exit Select Case Else Assert.Equal("Unexpected Attr", a.AttributeClass.Name) Exit Select End Select Next End Sub <Fact()> Public Sub AssemblyAttributesFromNetModuleDropSpecial() Dim consoleappSource = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Reflection <Assembly: AssemblyTitle("AssemblyTitle (from source)")> Class Program Private Shared Sub Main(args As String()) End Sub End Class ]]> </file> </compilation> Dim consoleappCompilation = CreateCompilationWithMscorlib40AndReferences(consoleappSource, {GetNetModuleWithAssemblyAttributesRef()}) Dim diagnostics = consoleappCompilation.GetDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(consoleappCompilation.Assembly, expectedSrcAttrCount:=2, expectedDuplicateAttrCount:=1, attrTypeName:="AssemblyTitleAttribute") Dim attrs = DirectCast(consoleappCompilation.Assembly, SourceAssemblySymbol). GetAssemblyCustomAttributesToEmit(New ModuleCompilationState, emittingRefAssembly:=False, emittingAssemblyAttributesInNetModule:=False). Cast(Of VisualBasicAttributeData)() For Each a In attrs Select Case a.AttributeClass.Name Case "AssemblyTitleAttribute" Assert.Equal("System.Reflection.AssemblyTitleAttribute(""AssemblyTitle (from source)"")", a.ToString()) Exit Select Case "FileIOPermissionAttribute" Assert.Equal("System.Security.Permissions.FileIOPermissionAttribute(System.Security.Permissions.SecurityAction.RequestOptional)", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrNoAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")", a.ToString()) Exit Select Case "CompilationRelaxationsAttribute", "RuntimeCompatibilityAttribute", "DebuggableAttribute" ' synthesized attributes Exit Select Case Else Assert.Equal("Unexpected Attr", a.AttributeClass.Name) Exit Select End Select Next End Sub <Fact()> Public Sub AssemblyAttributesFromNetModuleAddMulti() Dim consoleappSource = <compilation> <file name="a.vb"> <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultiple("UserDefinedAssemblyAttrAllowMultiple (from source)")> Class Program Private Shared Sub Main(args As String()) End Sub End Class ]]> </file> </compilation> Dim consoleappCompilation = CreateCompilationWithMscorlib40AndReferences(consoleappSource, {GetNetModuleWithAssemblyAttributesRef()}) Dim diagnostics = consoleappCompilation.GetDiagnostics() Dim attrs = consoleappCompilation.Assembly.GetAttributes() Assert.Equal(5, attrs.Length) For Each a In attrs Select Case a.AttributeClass.Name Case "AssemblyTitleAttribute" Assert.Equal("System.Reflection.AssemblyTitleAttribute(""AssemblyTitle"")", a.ToString()) Exit Select Case "FileIOPermissionAttribute" Assert.Equal("System.Security.Permissions.FileIOPermissionAttribute(System.Security.Permissions.SecurityAction.RequestOptional)", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrNoAllowMultipleAttribute" Assert.Equal("UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()) Exit Select Case "UserDefinedAssemblyAttrAllowMultipleAttribute" Assert.[True](("UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")" = a.ToString()) OrElse ("UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple (from source)"")" = a.ToString()), "Unexpected attribute construction") Exit Select Case Else Assert.Equal("Unexpected Attr", a.AttributeClass.Name) Exit Select End Select Next End Sub <Fact(), WorkItem(546963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546963")> Public Sub AssemblyAttributesFromNetModuleBadMulti() Dim source As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrNoAllowMultiple("UserDefinedAssemblyAttrNoAllowMultiple (from source)")> ]]>.Value Dim netmodule1Ref = GetNetModuleWithAssemblyAttributesRef() Dim comp = CreateCompilationWithMscorlib40({source}, references:={netmodule1Ref}, options:=TestOptions.ReleaseDll) ' error BC36978: Attribute 'UserDefinedAssemblyAttrNoAllowMultipleAttribute' in 'NetModuleWithAssemblyAttributes.netmodule' cannot be applied multiple times. comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsageInNetModule2).WithArguments("UserDefinedAssemblyAttrNoAllowMultipleAttribute", "NetModuleWithAssemblyAttributes.netmodule")) Dim attrs = comp.Assembly.GetAttributes() ' even duplicates are preserved in source. Assert.Equal(5, attrs.Length) ' Build NetModule comp = CreateCompilationWithMscorlib40({source}, references:={netmodule1Ref}, options:=TestOptions.ReleaseModule) comp.VerifyDiagnostics() Dim netmodule2Ref = comp.EmitToImageReference() attrs = comp.Assembly.GetAttributes() Assert.Equal(1, attrs.Length) comp = CreateCompilationWithMscorlib40({""}, references:={netmodule1Ref, netmodule2Ref}, options:=TestOptions.ReleaseDll) ' error BC36978: Attribute 'UserDefinedAssemblyAttrNoAllowMultipleAttribute' in 'NetModuleWithAssemblyAttributes.netmodule' cannot be applied multiple times. comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_InvalidMultipleAttributeUsageInNetModule2).WithArguments("UserDefinedAssemblyAttrNoAllowMultipleAttribute", "NetModuleWithAssemblyAttributes.netmodule")) attrs = comp.Assembly.GetAttributes() ' even duplicates are preserved in source. Assert.Equal(5, attrs.Length) End Sub <Fact(), WorkItem(546963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546963")> Public Sub InternalsVisibleToAttributeDropIdentical() Dim source = <compilation> <file name="a.vb"> <![CDATA[ Imports System.Runtime.CompilerServices <Assembly: InternalsVisibleTo("Assembly2")> <Assembly: InternalsVisibleTo("Assembly2")> ]]> </file> </compilation> Dim comp = CreateCompilationWithMscorlib40(source, OutputKind.DynamicallyLinkedLibrary) CompileAndVerify(comp) TestDuplicateAssemblyAttributesNotEmitted(comp.Assembly, expectedSrcAttrCount:=2, expectedDuplicateAttrCount:=1, attrTypeName:="InternalsVisibleToAttribute") End Sub <Fact(), WorkItem(546963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546963")> Public Sub AssemblyAttributesFromSourceDropIdentical() Dim source = <compilation> <file name="a.vb"> <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str2", Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str1", Text := "str1")> ' unique ]]> </file> </compilation> Dim netmoduleRef = GetNetModuleWithAssemblyAttributesRef() Dim comp = CreateCompilationWithMscorlib40AndReferences(source, references:={netmoduleRef}) Dim diagnostics = comp.GetDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(comp.Assembly, expectedSrcAttrCount:=16, expectedDuplicateAttrCount:=5, attrTypeName:="UserDefinedAssemblyAttrAllowMultipleAttribute") End Sub <Fact(), WorkItem(546963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546963")> Public Sub AssemblyAttributesFromSourceDropIdentical_02() Dim source1 As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrNoAllowMultipleAttribute(0)> ' unique ]]>.Value Dim source2 As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrNoAllowMultipleAttribute(0)> ' duplicate ignored, no error because identical ]]>.Value Dim defaultHeaderString As String = <![CDATA[ Imports System ]]>.Value Dim defsRef As MetadataReference = CreateCompilationWithMscorlib40({defaultHeaderString & s_defaultNetModuleSourceBody}, references:=Nothing, options:=TestOptions.ReleaseDll).ToMetadataReference() Dim netmodule1Ref As MetadataReference = GetNetModuleWithAssemblyAttributesRef(source2, "", references:={defsRef}, nameSuffix:="1") Dim comp = CreateCompilationWithMscorlib40({source1}, references:={defsRef, netmodule1Ref}, options:=TestOptions.ReleaseDll) ' duplicate ignored, no error because identical comp.VerifyDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(comp.Assembly, expectedSrcAttrCount:=2, expectedDuplicateAttrCount:=1, attrTypeName:="UserDefinedAssemblyAttrNoAllowMultipleAttribute") Dim netmodule2Ref As MetadataReference = GetNetModuleWithAssemblyAttributesRef(source1, "", references:={defsRef}, nameSuffix:="2") comp = CreateCompilationWithMscorlib40({""}, references:={defsRef, netmodule1Ref, netmodule2Ref}, options:=TestOptions.ReleaseDll) ' duplicate ignored, no error because identical comp.VerifyDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(comp.Assembly, expectedSrcAttrCount:=2, expectedDuplicateAttrCount:=1, attrTypeName:="UserDefinedAssemblyAttrNoAllowMultipleAttribute") End Sub <Fact(), WorkItem(546963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546963")> Public Sub AssemblyAttributesFromNetModuleDropIdentical_01() ' Duplicate ignored attributes in netmodule Dim netmoduleAttributes As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str2", Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str1", Text := "str1")> ' unique ]]>.Value Dim netmoduleRef = GetNetModuleWithAssemblyAttributesRef(s_defaultNetModuleSourceHeader & netmoduleAttributes, s_defaultNetModuleSourceBody) Dim comp = CreateCompilationWithMscorlib40({""}, references:={netmoduleRef}, options:=TestOptions.ReleaseDll) Dim diagnostics = comp.GetDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(comp.Assembly, expectedSrcAttrCount:=16, expectedDuplicateAttrCount:=5, attrTypeName:="UserDefinedAssemblyAttrAllowMultipleAttribute") End Sub <Fact(), WorkItem(546963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546963")> Public Sub AssemblyAttributesFromNetModuleDropIdentical_02() ' Duplicate ignored attributes in netmodules Dim netmodule1Attributes As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str2", Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str1", Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' unique ]]>.Value Dim netmodule2Attributes As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' duplicate ]]>.Value Dim netmodule3Attributes As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' duplicate ]]>.Value Dim defaultImportsString As String = <![CDATA[ Imports System ]]>.Value Dim defsRef As MetadataReference = CreateCompilationWithMscorlib40({defaultImportsString & s_defaultNetModuleSourceBody}, references:=Nothing, options:=TestOptions.ReleaseDll).ToMetadataReference() Dim netmodule0Ref = GetNetModuleWithAssemblyAttributesRef(s_defaultNetModuleSourceHeader, "", references:={defsRef}) Dim netmodule1Ref = GetNetModuleWithAssemblyAttributesRef(netmodule1Attributes, "", references:={defsRef}) Dim netmodule2Ref = GetNetModuleWithAssemblyAttributesRef(netmodule2Attributes, "", references:={defsRef}) Dim netmodule3Ref = GetNetModuleWithAssemblyAttributesRef(netmodule3Attributes, "", references:={defsRef}) Dim comp = CreateCompilationWithMscorlib40({""}, references:={defsRef, netmodule0Ref, netmodule1Ref, netmodule2Ref, netmodule3Ref}, options:=TestOptions.ReleaseDll) Dim diagnostics = comp.GetDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(comp.Assembly, expectedSrcAttrCount:=17, expectedDuplicateAttrCount:=6, attrTypeName:="UserDefinedAssemblyAttrAllowMultipleAttribute") End Sub <Fact(), WorkItem(546963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546963")> Public Sub AssemblyAttributesFromSourceAndNetModuleDropIdentical_01() ' All duplicate ignored attributes in netmodule Dim netmoduleAttributes As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' duplicate ]]>.Value Dim sourceAttributes As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str2", Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str1", Text := "str1")> ' unique ]]>.Value Dim netmoduleRef = GetNetModuleWithAssemblyAttributesRef(s_defaultNetModuleSourceHeader & netmoduleAttributes, s_defaultNetModuleSourceBody) Dim comp = CreateCompilationWithMscorlib40({sourceAttributes}, references:={netmoduleRef}, options:=TestOptions.ReleaseDll) Dim diagnostics = comp.GetDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(comp.Assembly, expectedSrcAttrCount:=16, expectedDuplicateAttrCount:=5, attrTypeName:="UserDefinedAssemblyAttrAllowMultipleAttribute") End Sub <Fact(), WorkItem(546963, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546963")> Public Sub AssemblyAttributesFromSourceAndNetModuleDropIdentical_02() ' Duplicate ignored attributes in netmodule & source Dim netmoduleAttributes As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' duplicate ]]>.Value Dim sourceAttributes As String = <![CDATA[ <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute("str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str2")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str2", Text := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' unique <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text := "str1", Text2 := "str1")> ' duplicate <Assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 := "str1", Text := "str1")> ' unique ]]>.Value Dim netmoduleRef = GetNetModuleWithAssemblyAttributesRef(s_defaultNetModuleSourceHeader & netmoduleAttributes, s_defaultNetModuleSourceBody) Dim comp = CreateCompilationWithMscorlib40({sourceAttributes}, references:={netmoduleRef}, options:=TestOptions.ReleaseDll) Dim diagnostics = comp.GetDiagnostics() TestDuplicateAssemblyAttributesNotEmitted(comp.Assembly, expectedSrcAttrCount:=21, expectedDuplicateAttrCount:=10, attrTypeName:="UserDefinedAssemblyAttrAllowMultipleAttribute") End Sub #End Region <Fact, WorkItem(545527, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545527")> Public Sub CompilationRelaxationsAndRuntimeCompatibility_MultiModule() Dim moduleSrc = <compilation> <file><![CDATA[ Imports System.Runtime.CompilerServices <Assembly:CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)> <Assembly:RuntimeCompatibilityAttribute(WrapNonExceptionThrows:=False)> ]]> </file> </compilation> Dim [module] = CreateCompilationWithMscorlib40(moduleSrc, options:=TestOptions.ReleaseModule) Dim assemblySrc = <compilation> <file> Public Class C End Class </file> </compilation> Dim assembly = CreateCompilationWithMscorlib40(assemblySrc, references:={[module].EmitToImageReference()}) CompileAndVerify(assembly, symbolValidator:= Sub(moduleSymbol) Dim attrs = moduleSymbol.ContainingAssembly.GetAttributes().Select(Function(a) a.ToString()).ToArray() AssertEx.SetEqual({ "System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)", "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows:=False)", "System.Runtime.CompilerServices.CompilationRelaxationsAttribute(System.Runtime.CompilerServices.CompilationRelaxations.NoStringInterning)" }, attrs) End Sub) End Sub <Fact, WorkItem(546460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546460")> Public Sub RuntimeCompatibilityAttribute_False() ' VB emits catch(Exception) even for an empty catch, so it can never catch non-Exception objects. Dim source = <compilation> <file><![CDATA[ Imports System.Runtime.CompilerServices <Assembly:RuntimeCompatibilityAttribute(WrapNonExceptionThrows:=False)> Class C Public Shared Sub Main() Try Catch e As System.Exception Catch End Try End Sub End Class ]]> </file> </compilation> CreateCompilationWithMscorlib40AndVBRuntime(source).AssertTheseDiagnostics( <errors> BC42031: 'Catch' block never reached; 'Exception' handled above in the same Try statement. Catch ~~~~~ </errors>) End Sub <Fact, WorkItem(530585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530585")> Public Sub Bug16465() Dim modSource = <![CDATA[ Imports System.Configuration.Assemblies Imports System.Reflection <assembly: AssemblyAlgorithmId(AssemblyHashAlgorithm.SHA1)> <assembly: AssemblyCulture("en-US")> <assembly: AssemblyDelaySign(true)> <assembly: AssemblyFlags(AssemblyNameFlags.EnableJITcompileOptimizer Or AssemblyNameFlags.Retargetable Or AssemblyNameFlags.EnableJITcompileTracking)> <assembly: AssemblyVersion("1.2.3.4")> <assembly: AssemblyFileVersion("4.3.2.1")> <assembly: AssemblyTitle("HELLO")> <assembly: AssemblyDescription("World")> <assembly: AssemblyCompany("MS")> <assembly: AssemblyProduct("Roslyn")> <assembly: AssemblyInformationalVersion("Info")> <assembly: AssemblyCopyright("Roslyn")> <assembly: AssemblyTrademark("Roslyn")> class Program1 Shared Sub Main() End Sub End Class ]]> Dim source = <compilation> <file><![CDATA[ Class C End Class ]]> </file> </compilation> Dim appCompilation = CreateCompilationWithMscorlib40AndReferences(source, {GetNetModuleWithAssemblyAttributesRef(modSource.Value, "")}) Dim m = DirectCast(appCompilation.Assembly.Modules(1), PEModuleSymbol) Dim metadata = m.Module Dim metadataReader = metadata.GetMetadataReader() Dim token As EntityHandle = metadata.GetTypeRef(metadata.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHere") Assert.False(token.IsNil()) 'could the type ref be located? If not then the attribute's not there. Dim attributes = m.GetCustomAttributesForToken(token) Dim builder = New System.Text.StringBuilder() For Each attr In attributes builder.AppendLine(attr.ToString()) Next Dim expectedStr = <![CDATA[ System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA1) System.Reflection.AssemblyCultureAttribute("en-US") System.Reflection.AssemblyDelaySignAttribute(True) System.Reflection.AssemblyFlagsAttribute(System.Reflection.AssemblyNameFlags.None Or System.Reflection.AssemblyNameFlags.EnableJITcompileOptimizer Or System.Reflection.AssemblyNameFlags.EnableJITcompileTracking Or System.Reflection.AssemblyNameFlags.Retargetable) System.Reflection.AssemblyVersionAttribute("1.2.3.4") System.Reflection.AssemblyFileVersionAttribute("4.3.2.1") System.Reflection.AssemblyTitleAttribute("HELLO") System.Reflection.AssemblyDescriptionAttribute("World") System.Reflection.AssemblyCompanyAttribute("MS") System.Reflection.AssemblyProductAttribute("Roslyn") System.Reflection.AssemblyInformationalVersionAttribute("Info") System.Reflection.AssemblyCopyrightAttribute("Roslyn") System.Reflection.AssemblyTrademarkAttribute("Roslyn") ]]>.Value.Trim() expectedStr = CompilationUtils.FilterString(expectedStr) Dim actualStr = CompilationUtils.FilterString(builder.ToString().Trim()) Assert.True(expectedStr.Equals(actualStr), AssertEx.GetAssertMessage(expectedStr, actualStr)) End Sub <Fact, WorkItem(530579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530579")> Public Sub Bug530579_1() Dim mod1Source = <compilation name="M1"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module1")> ]]></file> </compilation> Dim mod2Source = <compilation name="M2"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module1")> ]]></file> </compilation> Dim source = <compilation name="M3"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module1")> ]]> </file> </compilation> Dim compMod1 = CreateCompilationWithMscorlib40(mod1Source, options:=TestOptions.ReleaseModule) Dim compMod2 = CreateCompilationWithMscorlib40(mod2Source, options:=TestOptions.ReleaseModule) Dim appCompilation = CreateCompilationWithMscorlib40AndReferences(source, {compMod1.EmitToImageReference(), compMod2.EmitToImageReference()}, options:=TestOptions.ReleaseDll) Assert.Equal(3, appCompilation.Assembly.Modules.Length) CompileAndVerify(appCompilation, symbolValidator:=Sub(m As ModuleSymbol) Dim list As New ArrayBuilder(Of VisualBasicAttributeData) GetAssemblyDescriptionAttributes(m.ContainingAssembly, list) Assert.Equal(1, list.Count) Assert.Equal("System.Reflection.AssemblyDescriptionAttribute(""Module1"")", list(0).ToString()) End Sub).VerifyDiagnostics() End Sub Private Shared Sub GetAssemblyDescriptionAttributes(assembly As AssemblySymbol, list As ArrayBuilder(Of VisualBasicAttributeData)) For Each attrData In assembly.GetAttributes() If attrData.IsTargetAttribute(assembly, AttributeDescription.AssemblyDescriptionAttribute) Then list.Add(attrData) End If Next End Sub <Fact, WorkItem(530579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530579")> Public Sub Bug530579_2() Dim mod1Source = <compilation name="M1"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module1")> ]]></file> </compilation> Dim mod2Source = <compilation name="M2"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module2")> ]]></file> </compilation> Dim source = <compilation name="M3"> <file><![CDATA[ ]]> </file> </compilation> Dim compMod1 = CreateCompilationWithMscorlib40(mod1Source, options:=TestOptions.ReleaseModule) Dim compMod2 = CreateCompilationWithMscorlib40(mod2Source, options:=TestOptions.ReleaseModule) Dim appCompilation = CreateCompilationWithMscorlib40AndReferences(source, {compMod1.EmitToImageReference(), compMod2.EmitToImageReference()}, TestOptions.ReleaseDll) Assert.Equal(3, appCompilation.Assembly.Modules.Length) AssertTheseDiagnostics(appCompilation, <expected> BC42370: Attribute 'AssemblyDescriptionAttribute' from module 'M1.netmodule' will be ignored in favor of the instance appearing in source. </expected>) CompileAndVerify(appCompilation, symbolValidator:=Sub(m As ModuleSymbol) Dim list As New ArrayBuilder(Of VisualBasicAttributeData) GetAssemblyDescriptionAttributes(m.ContainingAssembly, list) Assert.Equal(1, list.Count) Assert.Equal("System.Reflection.AssemblyDescriptionAttribute(""Module2"")", list(0).ToString()) End Sub) End Sub <Fact, WorkItem(530579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530579")> Public Sub Bug530579_3() Dim mod1Source = <compilation name="M1"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module1")> ]]></file> </compilation> Dim mod2Source = <compilation name="M2"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module2")> ]]></file> </compilation> Dim source = <compilation name="M3"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module3")> ]]> </file> </compilation> Dim compMod1 = CreateCompilationWithMscorlib40(mod1Source, options:=TestOptions.ReleaseModule) Dim compMod2 = CreateCompilationWithMscorlib40(mod2Source, options:=TestOptions.ReleaseModule) Dim appCompilation = CreateCompilationWithMscorlib40AndReferences(source, {compMod1.EmitToImageReference(), compMod2.EmitToImageReference()}, TestOptions.ReleaseDll) Assert.Equal(3, appCompilation.Assembly.Modules.Length) AssertTheseDiagnostics(appCompilation, <expected> BC42370: Attribute 'AssemblyDescriptionAttribute' from module 'M1.netmodule' will be ignored in favor of the instance appearing in source. BC42370: Attribute 'AssemblyDescriptionAttribute' from module 'M2.netmodule' will be ignored in favor of the instance appearing in source. </expected>) CompileAndVerify(appCompilation, symbolValidator:=Sub(m As ModuleSymbol) Dim list As New ArrayBuilder(Of VisualBasicAttributeData) GetAssemblyDescriptionAttributes(m.ContainingAssembly, list) Assert.Equal(1, list.Count) Assert.Equal("System.Reflection.AssemblyDescriptionAttribute(""Module3"")", list(0).ToString()) End Sub) End Sub <Fact, WorkItem(530579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530579")> Public Sub Bug530579_4() Dim mod1Source = <compilation name="M1"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module1")> ]]></file> </compilation> Dim mod2Source = <compilation name="M2"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module2")> ]]></file> </compilation> Dim source = <compilation name="M3"> <file><![CDATA[ <Assembly:System.Reflection.AssemblyDescriptionAttribute("Module1")> ]]> </file> </compilation> Dim compMod1 = CreateCompilationWithMscorlib40(mod1Source, options:=TestOptions.ReleaseModule) Dim compMod2 = CreateCompilationWithMscorlib40(mod2Source, options:=TestOptions.ReleaseModule) Dim appCompilation = CreateCompilationWithMscorlib40AndReferences(source, {compMod1.EmitToImageReference(), compMod2.EmitToImageReference()}, TestOptions.ReleaseDll) Assert.Equal(3, appCompilation.Assembly.Modules.Length) AssertTheseDiagnostics(appCompilation, <expected> BC42370: Attribute 'AssemblyDescriptionAttribute' from module 'M2.netmodule' will be ignored in favor of the instance appearing in source. </expected>) CompileAndVerify(appCompilation, symbolValidator:=Sub(m As ModuleSymbol) Dim list As New ArrayBuilder(Of VisualBasicAttributeData) GetAssemblyDescriptionAttributes(m.ContainingAssembly, list) Assert.Equal(1, list.Count) Assert.Equal("System.Reflection.AssemblyDescriptionAttribute(""Module1"")", list(0).ToString()) End Sub) End Sub End Class
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Compilers/Core/MSBuildTaskTests/TestUtilities/MockEngine.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; using System.Text; using Microsoft.Build.Framework; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { internal sealed class MockEngine : IBuildEngine { private StringBuilder _log = new StringBuilder(); public MessageImportance MinimumMessageImportance = MessageImportance.Low; internal string Log { set { _log = new StringBuilder(value); } get { return _log.ToString(); } } public void LogErrorEvent(BuildErrorEventArgs eventArgs) { _log.Append("ERROR "); _log.Append(eventArgs.Code); _log.Append(": "); _log.Append(eventArgs.Message); _log.AppendLine(); } public void LogWarningEvent(BuildWarningEventArgs eventArgs) { _log.Append("WARNING "); _log.Append(eventArgs.Code); _log.Append(": "); _log.Append(eventArgs.Message); _log.AppendLine(); } public void LogCustomEvent(CustomBuildEventArgs eventArgs) { _log.AppendLine(eventArgs.Message); } public void LogMessageEvent(BuildMessageEventArgs eventArgs) { _log.AppendLine(eventArgs.Message); } public string ProjectFileOfTaskNode => ""; public int ColumnNumberOfTaskNode => 0; public int LineNumberOfTaskNode => 0; public bool ContinueOnError => true; public bool BuildProjectFile(string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs) => throw new NotImplementedException(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Text; using Microsoft.Build.Framework; namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests { internal sealed class MockEngine : IBuildEngine { private StringBuilder _log = new StringBuilder(); public MessageImportance MinimumMessageImportance = MessageImportance.Low; internal string Log { set { _log = new StringBuilder(value); } get { return _log.ToString(); } } public void LogErrorEvent(BuildErrorEventArgs eventArgs) { _log.Append("ERROR "); _log.Append(eventArgs.Code); _log.Append(": "); _log.Append(eventArgs.Message); _log.AppendLine(); } public void LogWarningEvent(BuildWarningEventArgs eventArgs) { _log.Append("WARNING "); _log.Append(eventArgs.Code); _log.Append(": "); _log.Append(eventArgs.Message); _log.AppendLine(); } public void LogCustomEvent(CustomBuildEventArgs eventArgs) { _log.AppendLine(eventArgs.Message); } public void LogMessageEvent(BuildMessageEventArgs eventArgs) { _log.AppendLine(eventArgs.Message); } public string ProjectFileOfTaskNode => ""; public int ColumnNumberOfTaskNode => 0; public int LineNumberOfTaskNode => 0; public bool ContinueOnError => true; public bool BuildProjectFile(string projectFileName, string[] targetNames, IDictionary globalProperties, IDictionary targetOutputs) => throw new NotImplementedException(); } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/VisualStudio/Core/Def/Implementation/TableDataSource/DiagnosticTableControlEventProcessorProvider.AggregateDiagnosticTableControlEventProcessor.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.VisualStudio.Shell.TableControl; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { internal partial class DiagnosticTableControlEventProcessorProvider { private class AggregateDiagnosticTableControlEventProcessor : EventProcessor { private readonly ImmutableArray<EventProcessor> _additionalEventProcessors; public AggregateDiagnosticTableControlEventProcessor(params EventProcessor[] additionalEventProcessors) => _additionalEventProcessors = additionalEventProcessors.ToImmutableArray(); public override void PostprocessSelectionChanged(TableSelectionChangedEventArgs e) { base.PostprocessSelectionChanged(e); foreach (var processor in _additionalEventProcessors) { processor.PostprocessSelectionChanged(e); } } } } }
// Licensed to the .NET Foundation under one or more 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.VisualStudio.Shell.TableControl; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { internal partial class DiagnosticTableControlEventProcessorProvider { private class AggregateDiagnosticTableControlEventProcessor : EventProcessor { private readonly ImmutableArray<EventProcessor> _additionalEventProcessors; public AggregateDiagnosticTableControlEventProcessor(params EventProcessor[] additionalEventProcessors) => _additionalEventProcessors = additionalEventProcessors.ToImmutableArray(); public override void PostprocessSelectionChanged(TableSelectionChangedEventArgs e) { base.PostprocessSelectionChanged(e); foreach (var processor in _additionalEventProcessors) { processor.PostprocessSelectionChanged(e); } } } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/CSharp/Portable/Organizing/Organizers/OperatorDeclarationOrganizer.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 System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Organizing.Organizers; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { [ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared] internal class OperatorDeclarationOrganizer : AbstractSyntaxNodeOrganizer<OperatorDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public OperatorDeclarationOrganizer() { } protected override OperatorDeclarationSyntax Organize( OperatorDeclarationSyntax syntax, CancellationToken cancellationToken) { return syntax.Update(syntax.AttributeLists, ModifiersOrganizer.Organize(syntax.Modifiers), syntax.ReturnType, syntax.OperatorKeyword, syntax.OperatorToken, syntax.ParameterList, syntax.Body, syntax.SemicolonToken); } } }
// Licensed to the .NET Foundation under one or more 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 System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Organizing.Organizers; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { [ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared] internal class OperatorDeclarationOrganizer : AbstractSyntaxNodeOrganizer<OperatorDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public OperatorDeclarationOrganizer() { } protected override OperatorDeclarationSyntax Organize( OperatorDeclarationSyntax syntax, CancellationToken cancellationToken) { return syntax.Update(syntax.AttributeLists, ModifiersOrganizer.Organize(syntax.Modifiers), syntax.ReturnType, syntax.OperatorKeyword, syntax.OperatorToken, syntax.ParameterList, syntax.Body, syntax.SemicolonToken); } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Compilers/VisualBasic/Portable/Emit/PEModuleBuilder.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.Concurrent Imports System.Collections.Immutable Imports System.Reflection.PortableExecutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Emit Partial Friend MustInherit Class PEModuleBuilder Inherits PEModuleBuilder(Of VisualBasicCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, SyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState) ' Not many methods should end up here. Private ReadOnly _disableJITOptimization As ConcurrentDictionary(Of MethodSymbol, Boolean) = New ConcurrentDictionary(Of MethodSymbol, Boolean)(ReferenceEqualityComparer.Instance) ' Gives the name of this module (may not reflect the name of the underlying symbol). ' See Assembly.MetadataName. Private ReadOnly _metadataName As String Private _lazyExportedTypes As ImmutableArray(Of Cci.ExportedType) Private ReadOnly _lazyNumberOfTypesFromOtherModules As Integer Private _lazyTranslatedImports As ImmutableArray(Of Cci.UsedNamespaceOrType) Private _lazyDefaultNamespace As String Friend Sub New(sourceModule As SourceModuleSymbol, emitOptions As EmitOptions, outputKind As OutputKind, serializationProperties As Cci.ModulePropertiesForSerialization, manifestResources As IEnumerable(Of ResourceDescription)) MyBase.New(sourceModule.ContainingSourceAssembly.DeclaringCompilation, sourceModule, serializationProperties, manifestResources, outputKind, emitOptions, New ModuleCompilationState()) Dim specifiedName = sourceModule.MetadataName _metadataName = If(specifiedName <> CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName, specifiedName, If(emitOptions.OutputNameOverride, specifiedName)) m_AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, Me) If sourceModule.AnyReferencedAssembliesAreLinked Then _embeddedTypesManagerOpt = New NoPia.EmbeddedTypesManager(Me) End If End Sub ''' <summary> ''' True if conditional calls may be omitted when the required preprocessor symbols are not defined. ''' </summary> ''' <remarks> ''' Only false in debugger scenarios (where calls should never be omitted). ''' </remarks> Friend MustOverride ReadOnly Property AllowOmissionOfConditionalCalls As Boolean Public Overrides ReadOnly Property Name As String Get Return _metadataName End Get End Property Friend NotOverridable Overrides ReadOnly Property ModuleName As String Get Return _metadataName End Get End Property Friend NotOverridable Overrides ReadOnly Property CorLibrary As AssemblySymbol Get Return SourceModule.ContainingSourceAssembly.CorLibrary End Get End Property Public NotOverridable Overrides ReadOnly Property GenerateVisualBasicStylePdb As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property LinkedAssembliesDebugInfo As IEnumerable(Of String) Get ' NOTE: Dev12 does not seem to emit anything but the name (i.e. no version, token, etc). ' See Builder::WriteNoPiaPdbList Return SourceModule.ReferencedAssemblySymbols.Where(Function(a) a.IsLinked).Select(Function(a) a.Name) End Get End Property Public NotOverridable Overrides Function GetImports() As ImmutableArray(Of Cci.UsedNamespaceOrType) ' Imports should have been translated in code gen phase. Debug.Assert(Not _lazyTranslatedImports.IsDefault) Return _lazyTranslatedImports End Function Public Sub TranslateImports(diagnostics As DiagnosticBag) If _lazyTranslatedImports.IsDefault Then ImmutableInterlocked.InterlockedInitialize( _lazyTranslatedImports, NamespaceScopeBuilder.BuildNamespaceScope(Me, SourceModule.XmlNamespaces, SourceModule.AliasImports, SourceModule.MemberImports, diagnostics)) End If End Sub Public NotOverridable Overrides ReadOnly Property DefaultNamespace As String Get If _lazyDefaultNamespace IsNot Nothing Then Return _lazyDefaultNamespace End If Dim rootNamespace = SourceModule.RootNamespace If rootNamespace.IsGlobalNamespace Then Return String.Empty End If _lazyDefaultNamespace = rootNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) Return _lazyDefaultNamespace End Get End Property Protected NotOverridable Overrides Iterator Function GetAssemblyReferencesFromAddedModules(diagnostics As DiagnosticBag) As IEnumerable(Of Cci.IAssemblyReference) Dim modules As ImmutableArray(Of ModuleSymbol) = SourceModule.ContainingAssembly.Modules For i As Integer = 1 To modules.Length - 1 For Each aRef As AssemblySymbol In modules(i).GetReferencedAssemblySymbols() Yield Translate(aRef, diagnostics) Next Next End Function Private Sub ValidateReferencedAssembly(assembly As AssemblySymbol, asmRef As AssemblyReference, diagnostics As DiagnosticBag) Dim asmIdentity As AssemblyIdentity = SourceModule.ContainingAssembly.Identity Dim refIdentity As AssemblyIdentity = asmRef.Identity If asmIdentity.IsStrongName AndAlso Not refIdentity.IsStrongName AndAlso asmRef.Identity.ContentType <> Reflection.AssemblyContentType.WindowsRuntime Then ' Dev12 reported error, we have changed it to a warning to allow referencing libraries ' built for platforms that don't support strong names. diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton) End If If OutputKind <> OutputKind.NetModule AndAlso Not String.IsNullOrEmpty(refIdentity.CultureName) AndAlso Not String.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase) Then diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton) End If Dim refMachine = assembly.Machine ' If other assembly is agnostic, this is always safe ' Also, if no mscorlib was specified for back compat we add a reference to mscorlib ' that resolves to the current framework directory. If the compiler Is 64-bit ' this Is a 64-bit mscorlib, which will produce a warning if /platform:x86 Is ' specified.A reference to the default mscorlib should always succeed without ' warning so we ignore it here. If assembly IsNot assembly.CorLibrary AndAlso Not (refMachine = Machine.I386 AndAlso Not assembly.Bit32Required) Then Dim machine = SourceModule.Machine If Not (machine = Machine.I386 AndAlso Not SourceModule.Bit32Required) AndAlso machine <> refMachine Then ' Different machine types, and neither is agnostic diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton) End If End If If _embeddedTypesManagerOpt IsNot Nothing AndAlso _embeddedTypesManagerOpt.IsFrozen Then _embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics) End If End Sub Friend NotOverridable Overrides Function SynthesizeAttribute(attributeConstructor As WellKnownMember) As Cci.ICustomAttribute Return Me.Compilation.TrySynthesizeAttribute(attributeConstructor) End Function Public NotOverridable Overrides Function GetSourceAssemblyAttributes(isRefAssembly As Boolean) As IEnumerable(Of Cci.ICustomAttribute) Return SourceModule.ContainingSourceAssembly.GetAssemblyCustomAttributesToEmit(Me.CompilationState, isRefAssembly, emittingAssemblyAttributesInNetModule:=OutputKind.IsNetModule()) End Function Public NotOverridable Overrides Function GetSourceAssemblySecurityAttributes() As IEnumerable(Of Cci.SecurityAttribute) Return SourceModule.ContainingSourceAssembly.GetSecurityAttributes() End Function Public NotOverridable Overrides Function GetSourceModuleAttributes() As IEnumerable(Of Cci.ICustomAttribute) Return SourceModule.GetCustomAttributesToEmit(Me.CompilationState) End Function Public NotOverridable Overrides Function GetSymbolToLocationMap() As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation) Dim result As New MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation)() Dim namespacesAndTypesToProcess As New Stack(Of NamespaceOrTypeSymbol)() namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace) Dim location As Location = Nothing While namespacesAndTypesToProcess.Count > 0 Dim symbol As NamespaceOrTypeSymbol = namespacesAndTypesToProcess.Pop() Select Case symbol.Kind Case SymbolKind.Namespace location = GetSmallestSourceLocationOrNull(symbol) ' filtering out synthesized symbols not having real source ' locations such as anonymous types, my types, etc... If location IsNot Nothing Then For Each member In symbol.GetMembers() Select Case member.Kind Case SymbolKind.Namespace, SymbolKind.NamedType namespacesAndTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol)) Case Else Throw ExceptionUtilities.UnexpectedValue(member.Kind) End Select Next End If Case SymbolKind.NamedType location = GetSmallestSourceLocationOrNull(symbol) If location IsNot Nothing Then ' add this named type location AddSymbolLocation(result, location, DirectCast(symbol.GetCciAdapter(), Cci.IDefinition)) For Each member In symbol.GetMembers() Select Case member.Kind Case SymbolKind.NamedType namespacesAndTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol)) Case SymbolKind.Method Dim method = DirectCast(member, MethodSymbol) If method.IsDefaultValueTypeConstructor() OrElse method.IsPartialWithoutImplementation Then Exit Select End If AddSymbolLocation(result, member) Case SymbolKind.Property, SymbolKind.Field AddSymbolLocation(result, member) Case SymbolKind.Event AddSymbolLocation(result, member) Dim AssociatedField = (DirectCast(member, EventSymbol)).AssociatedField If AssociatedField IsNot Nothing Then ' event backing fields do not show up in GetMembers AddSymbolLocation(result, AssociatedField) End If Case Else Throw ExceptionUtilities.UnexpectedValue(member.Kind) End Select Next End If Case Else Throw ExceptionUtilities.UnexpectedValue(symbol.Kind) End Select End While Return result End Function Private Sub AddSymbolLocation(result As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation), symbol As Symbol) Dim location As Location = GetSmallestSourceLocationOrNull(symbol) If location IsNot Nothing Then AddSymbolLocation(result, location, DirectCast(symbol.GetCciAdapter(), Cci.IDefinition)) End If End Sub Private Sub AddSymbolLocation(result As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation), location As Location, definition As Cci.IDefinition) Dim span As FileLinePositionSpan = location.GetLineSpan() Dim doc As Cci.DebugSourceDocument = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath:=location.SourceTree.FilePath) If (doc IsNot Nothing) Then result.Add(doc, New Cci.DefinitionWithLocation( definition, span.StartLinePosition.Line, span.StartLinePosition.Character, span.EndLinePosition.Line, span.EndLinePosition.Character)) End If End Sub Private Function GetSmallestSourceLocationOrNull(symbol As Symbol) As Location Dim compilation As VisualBasicCompilation = symbol.DeclaringCompilation Debug.Assert(Me.Compilation Is compilation, "How did we get symbol from different compilation?") Dim result As Location = Nothing For Each loc In symbol.Locations If loc.IsInSource AndAlso (result Is Nothing OrElse compilation.CompareSourceLocations(result, loc) > 0) Then result = loc End If Next Return result End Function ''' <summary> ''' Ignore accessibility when resolving well-known type ''' members, in particular for generic type arguments ''' (e.g.: binding to internal types in the EE). ''' </summary> Friend Overridable ReadOnly Property IgnoreAccessibility As Boolean Get Return False End Get End Property Friend Overridable Function TryCreateVariableSlotAllocator(method As MethodSymbol, topLevelMethod As MethodSymbol, diagnostics As DiagnosticBag) As VariableSlotAllocator Return Nothing End Function Friend Overridable Function GetPreviousAnonymousTypes() As ImmutableArray(Of AnonymousTypeKey) Return ImmutableArray(Of AnonymousTypeKey).Empty End Function Friend Overridable Function GetNextAnonymousTypeIndex(fromDelegates As Boolean) As Integer Return 0 End Function Friend Overridable Function TryGetAnonymousTypeName(template As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean Debug.Assert(Compilation Is template.DeclaringCompilation) name = Nothing index = -1 Return False End Function Public NotOverridable Overrides Function GetAnonymousTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) If context.MetadataOnly Then Return SpecializedCollections.EmptyEnumerable(Of Cci.INamespaceTypeDefinition) End If #If DEBUG Then Return SourceModule.ContainingSourceAssembly.DeclaringCompilation.AnonymousTypeManager.AllCreatedTemplates.Select(Function(t) t.GetCciAdapter()) #Else Return SourceModule.ContainingSourceAssembly.DeclaringCompilation.AnonymousTypeManager.AllCreatedTemplates #End If End Function Public Overrides Iterator Function GetTopLevelSourceTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) Dim embeddedSymbolManager As EmbeddedSymbolManager = SourceModule.ContainingSourceAssembly.DeclaringCompilation.EmbeddedSymbolManager Dim stack As New Stack(Of NamespaceOrTypeSymbol)() stack.Push(SourceModule.GlobalNamespace) Do Dim sym As NamespaceOrTypeSymbol = stack.Pop() If sym.Kind = SymbolKind.NamedType Then Debug.Assert(sym Is sym.OriginalDefinition) Debug.Assert(sym.ContainingType Is Nothing) ' Skip unreferenced embedded types. If Not sym.IsEmbedded OrElse embeddedSymbolManager.IsSymbolReferenced(sym) Then Yield DirectCast(sym, NamedTypeSymbol).GetCciAdapter() End If Else Debug.Assert(sym.Kind = SymbolKind.Namespace) Dim members As ImmutableArray(Of Symbol) = sym.GetMembers() For i As Integer = members.Length - 1 To 0 Step -1 Dim namespaceOrType As NamespaceOrTypeSymbol = TryCast(members(i), NamespaceOrTypeSymbol) If namespaceOrType IsNot Nothing Then stack.Push(namespaceOrType) End If Next End If Loop While stack.Count > 0 End Function Public NotOverridable Overrides Function GetExportedTypes(diagnostics As DiagnosticBag) As ImmutableArray(Of Cci.ExportedType) Debug.Assert(HaveDeterminedTopLevelTypes) If _lazyExportedTypes.IsDefault Then _lazyExportedTypes = CalculateExportedTypes() If _lazyExportedTypes.Length > 0 Then ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics) End If End If Return _lazyExportedTypes End Function ''' <summary> ''' Builds an array of public type symbols defined in netmodules included in the compilation ''' And type forwarders defined in this compilation Or any included netmodule (in this order). ''' </summary> Private Function CalculateExportedTypes() As ImmutableArray(Of Cci.ExportedType) Dim builder = ArrayBuilder(Of Cci.ExportedType).GetInstance() Dim sourceAssembly As SourceAssemblySymbol = SourceModule.ContainingSourceAssembly If Not OutputKind.IsNetModule() Then Dim modules = sourceAssembly.Modules For i As Integer = 1 To modules.Length - 1 'NOTE: skipping modules(0) GetExportedTypes(modules(i).GlobalNamespace, -1, builder) Next End If Debug.Assert(OutputKind.IsNetModule() = sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule()) GetForwardedTypes(sourceAssembly, builder) Return builder.ToImmutableAndFree() End Function ''' <summary> ''' Returns a set of top-level forwarded types ''' </summary> Friend Shared Function GetForwardedTypes(sourceAssembly As SourceAssemblySymbol, builderOpt As ArrayBuilder(Of Cci.ExportedType)) As HashSet(Of NamedTypeSymbol) Dim seenTopLevelForwardedTypes = New HashSet(Of NamedTypeSymbol)() GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builderOpt) If Not sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule() Then GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builderOpt) End If Return seenTopLevelForwardedTypes End Function Private Sub ReportExportedTypeNameCollisions(exportedTypes As ImmutableArray(Of Cci.ExportedType), diagnostics As DiagnosticBag) Dim sourceAssembly As SourceAssemblySymbol = SourceModule.ContainingSourceAssembly Dim exportedNamesMap = New Dictionary(Of String, NamedTypeSymbol)() For Each exportedType In _lazyExportedTypes Dim typeReference As Cci.ITypeReference = exportedType.Type Dim type = DirectCast(typeReference.GetInternalSymbol(), NamedTypeSymbol) Debug.Assert(type.IsDefinition) If type.ContainingType IsNot Nothing Then Continue For End If ' exported types are not emitted in EnC deltas (hence generation 0): Dim fullEmittedName As String = MetadataHelpers.BuildQualifiedName( DirectCast(typeReference, Cci.INamespaceTypeReference).NamespaceName, Cci.MetadataWriter.GetMangledName(DirectCast(typeReference, Cci.INamedTypeReference), generation:=0)) ' First check against types declared in the primary module If ContainsTopLevelType(fullEmittedName) Then If type.ContainingAssembly Is sourceAssembly Then diagnostics.Add(ERRID.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, type, type.ContainingModule) Else diagnostics.Add(ERRID.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type)) End If Continue For End If Dim contender As NamedTypeSymbol = Nothing ' Now check against other exported types If exportedNamesMap.TryGetValue(fullEmittedName, contender) Then If type.ContainingAssembly Is sourceAssembly Then ' all exported types precede forwarded types, therefore contender cannot be a forwarded type. Debug.Assert(contender.ContainingAssembly Is sourceAssembly) diagnostics.Add(ERRID.ERR_ExportedTypesConflict, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type), CustomSymbolDisplayFormatter.DefaultErrorFormat(type.ContainingModule), CustomSymbolDisplayFormatter.DefaultErrorFormat(contender), CustomSymbolDisplayFormatter.DefaultErrorFormat(contender.ContainingModule)) ElseIf contender.ContainingAssembly Is sourceAssembly Then ' Forwarded type conflicts with exported type diagnostics.Add(ERRID.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type), type.ContainingAssembly, CustomSymbolDisplayFormatter.DefaultErrorFormat(contender), CustomSymbolDisplayFormatter.DefaultErrorFormat(contender.ContainingModule)) Else ' Forwarded type conflicts with another forwarded type diagnostics.Add(ERRID.ERR_ForwardedTypesConflict, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type), type.ContainingAssembly, CustomSymbolDisplayFormatter.DefaultErrorFormat(contender), contender.ContainingAssembly) End If Continue For End If exportedNamesMap.Add(fullEmittedName, type) Next End Sub Private Overloads Sub GetExportedTypes(symbol As NamespaceOrTypeSymbol, parentIndex As Integer, builder As ArrayBuilder(Of Cci.ExportedType)) Dim index As Integer If symbol.Kind = SymbolKind.NamedType Then If symbol.DeclaredAccessibility <> Accessibility.Public Then Return End If Debug.Assert(symbol.IsDefinition) index = builder.Count builder.Add(New Cci.ExportedType(DirectCast(symbol, NamedTypeSymbol).GetCciAdapter(), parentIndex, isForwarder:=False)) Else index = -1 End If For Each member In symbol.GetMembers() Dim namespaceOrType = TryCast(member, NamespaceOrTypeSymbol) If namespaceOrType IsNot Nothing Then GetExportedTypes(namespaceOrType, index, builder) End If Next End Sub Private Shared Sub GetForwardedTypes( seenTopLevelTypes As HashSet(Of NamedTypeSymbol), wellKnownAttributeData As CommonAssemblyWellKnownAttributeData(Of NamedTypeSymbol), builderOpt As ArrayBuilder(Of Cci.ExportedType)) If wellKnownAttributeData?.ForwardedTypes?.Count > 0 Then ' (type, index of the parent exported type in builder, or -1 if the type is a top-level type) Dim stack = ArrayBuilder(Of (type As NamedTypeSymbol, parentIndex As Integer)).GetInstance() ' Hashset enumeration is not guaranteed to be deterministic. Emitting in the order of fully qualified names. Dim orderedForwardedTypes As IEnumerable(Of NamedTypeSymbol) = wellKnownAttributeData.ForwardedTypes If builderOpt IsNot Nothing Then orderedForwardedTypes = orderedForwardedTypes.OrderBy(Function(t) t.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)) End If For Each forwardedType As NamedTypeSymbol In orderedForwardedTypes Dim originalDefinition As NamedTypeSymbol = forwardedType.OriginalDefinition Debug.Assert(originalDefinition.ContainingType Is Nothing, "How did a nested type get forwarded?") ' De-dup the original definitions before emitting. If Not seenTopLevelTypes.Add(originalDefinition) Then Continue For End If If builderOpt IsNot Nothing Then ' Return all nested types. ' Note the order: depth first, children in reverse order (to match dev10, not a requirement). Debug.Assert(stack.Count = 0) stack.Push((originalDefinition, -1)) While stack.Count > 0 Dim entry = stack.Pop() ' In general, we don't want private types to appear in the ExportedTypes table. If entry.type.DeclaredAccessibility = Accessibility.Private Then ' NOTE: this will also exclude nested types of curr. Continue While End If ' NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection. Dim index = builderOpt.Count builderOpt.Add(New Cci.ExportedType(entry.type.GetCciAdapter(), entry.parentIndex, isForwarder:=True)) ' Iterate backwards so they get popped in forward order. Dim nested As ImmutableArray(Of NamedTypeSymbol) = entry.type.GetTypeMembers() ' Ordered. For i As Integer = nested.Length - 1 To 0 Step -1 stack.Push((nested(i), index)) Next End While End If Next stack.Free() End If End Sub Friend Iterator Function GetReferencedAssembliesUsedSoFar() As IEnumerable(Of AssemblySymbol) For Each assembly In SourceModule.GetReferencedAssemblySymbols() If Not assembly.IsLinked AndAlso Not assembly.IsMissing AndAlso m_AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(assembly) Then Yield assembly End If Next End Function Friend NotOverridable Overrides Function GetSpecialType(specialType As SpecialType, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As Cci.INamedTypeReference Return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics), needDeclaration:=True, syntaxNodeOpt:=syntaxNodeOpt, diagnostics:=diagnostics) End Function Private Function GetUntranslatedSpecialType(specialType As SpecialType, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As NamedTypeSymbol Dim typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType) Dim info = Binder.GetUseSiteInfoForSpecialType(typeSymbol) If info.DiagnosticInfo IsNot Nothing Then Binder.ReportDiagnostic(diagnostics, If(syntaxNodeOpt IsNot Nothing, syntaxNodeOpt.GetLocation(), NoLocation.Singleton), info.DiagnosticInfo) End If Return typeSymbol End Function Public NotOverridable Overrides Function GetInitArrayHelper() As Cci.IMethodReference Return DirectCast(Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle), MethodSymbol)?.GetCciAdapter() End Function Public NotOverridable Overrides Function IsPlatformType(typeRef As Cci.ITypeReference, platformType As Cci.PlatformType) As Boolean Dim namedType = TryCast(typeRef.GetInternalSymbol(), NamedTypeSymbol) If namedType IsNot Nothing Then If platformType = Cci.PlatformType.SystemType Then Return namedType Is Compilation.GetWellKnownType(WellKnownType.System_Type) End If Return namedType.SpecialType = CType(platformType, SpecialType) End If Return False End Function Protected NotOverridable Overrides Function GetCorLibraryReferenceToEmit(context As EmitContext) As Cci.IAssemblyReference Dim corLib = CorLibrary If Not corLib.IsMissing AndAlso Not corLib.IsLinked AndAlso corLib IsNot SourceModule.ContainingAssembly Then Return Translate(corLib, context.Diagnostics) End If Return Nothing End Function Friend NotOverridable Overrides Function GetSynthesizedNestedTypes(container As NamedTypeSymbol) As IEnumerable(Of Cci.INestedTypeDefinition) Return container.GetSynthesizedNestedTypes() End Function Public Overrides Iterator Function GetTypeToDebugDocumentMap(context As EmitContext) As IEnumerable(Of (Cci.ITypeDefinition, ImmutableArray(Of Cci.DebugSourceDocument))) Dim typesToProcess = ArrayBuilder(Of Cci.ITypeDefinition).GetInstance() Dim debugDocuments = ArrayBuilder(Of Cci.DebugSourceDocument).GetInstance() Dim methodDocumentList = PooledHashSet(Of Cci.DebugSourceDocument).GetInstance() Dim namespacesAndTopLevelTypesToProcess = ArrayBuilder(Of NamespaceOrTypeSymbol).GetInstance() namespacesAndTopLevelTypesToProcess.Push(SourceModule.GlobalNamespace) While namespacesAndTopLevelTypesToProcess.Count > 0 Dim symbol = namespacesAndTopLevelTypesToProcess.Pop() If symbol.Locations.Length = 0 Then Continue While End If Select Case symbol.Kind Case SymbolKind.Namespace Dim location = GetSmallestSourceLocationOrNull(symbol) ' filtering out synthesized symbols not having real source ' locations such as anonymous types, my types, etc... If location IsNot Nothing Then For Each member In symbol.GetMembers() Select Case member.Kind Case SymbolKind.Namespace, SymbolKind.NamedType namespacesAndTopLevelTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol)) Case Else Throw ExceptionUtilities.UnexpectedValue(member.Kind) End Select Next End If Case SymbolKind.NamedType ' We only process top level types in this method, and only return documents for types if there are no ' methods that would refer to the same document, either in the type or in any nested type. Debug.Assert(debugDocuments.Count = 0) Debug.Assert(methodDocumentList.Count = 0) Debug.Assert(typesToProcess.Count = 0) Dim typeDefinition = DirectCast(symbol.GetCciAdapter(), Cci.ITypeDefinition) typesToProcess.Push(typeDefinition) GetDocumentsForMethodsAndNestedTypes(methodDocumentList, typesToProcess, context) For Each loc In symbol.Locations If Not loc.IsInSource Then Continue For End If Dim span = loc.GetLineSpan() Dim debugDocument = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath:=Nothing) If debugDocument IsNot Nothing AndAlso Not methodDocumentList.Contains(debugDocument) Then debugDocuments.Add(debugDocument) End If Next If debugDocuments.Count > 0 Then Yield (typeDefinition, debugDocuments.ToImmutable()) End If debugDocuments.Clear() methodDocumentList.Clear() Case Else Throw ExceptionUtilities.UnexpectedValue(symbol.Kind) End Select End While namespacesAndTopLevelTypesToProcess.Free() debugDocuments.Free() methodDocumentList.Free() typesToProcess.Free() End Function Private Shared Sub GetDocumentsForMethodsAndNestedTypes(documentList As PooledHashSet(Of Cci.DebugSourceDocument), typesToProcess As ArrayBuilder(Of Cci.ITypeDefinition), context As EmitContext) While typesToProcess.Count > 0 Dim definition = typesToProcess.Pop() Dim typeMethods = definition.GetMethods(context) For Each method In typeMethods Dim body = method.GetBody(context) If body Is Nothing Then Continue For End If For Each point In body.SequencePoints documentList.Add(point.Document) Next Next Dim nestedTypes = definition.GetNestedTypes(context) For Each nestedTypeDefinition In nestedTypes typesToProcess.Push(nestedTypeDefinition) Next End While End Sub Public Sub SetDisableJITOptimization(methodSymbol As MethodSymbol) Debug.Assert(methodSymbol.ContainingModule Is Me.SourceModule AndAlso methodSymbol Is methodSymbol.OriginalDefinition) _disableJITOptimization.TryAdd(methodSymbol, True) End Sub Public Function JITOptimizationIsDisabled(methodSymbol As MethodSymbol) As Boolean Debug.Assert(methodSymbol.ContainingModule Is Me.SourceModule AndAlso methodSymbol Is methodSymbol.OriginalDefinition) Return _disableJITOptimization.ContainsKey(methodSymbol) End Function Protected NotOverridable Overrides Function CreatePrivateImplementationDetailsStaticConstructor(details As PrivateImplementationDetails, syntaxOpt As SyntaxNode, diagnostics As DiagnosticBag) As Cci.IMethodDefinition Return New SynthesizedPrivateImplementationDetailsSharedConstructor(SourceModule, details, GetUntranslatedSpecialType(SpecialType.System_Void, syntaxOpt, diagnostics)).GetCciAdapter() End Function Public Overrides Function GetAdditionalTopLevelTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) #If DEBUG Then Return GetAdditionalTopLevelTypes().Select(Function(t) t.GetCciAdapter()) #Else Return GetAdditionalTopLevelTypes() #End If End Function Public Overrides Function GetEmbeddedTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) #If DEBUG Then Return GetEmbeddedTypes(context.Diagnostics).Select(Function(t) t.GetCciAdapter()) #Else Return GetEmbeddedTypes(context.Diagnostics) #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.Concurrent Imports System.Collections.Immutable Imports System.Reflection.PortableExecutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Emit Partial Friend MustInherit Class PEModuleBuilder Inherits PEModuleBuilder(Of VisualBasicCompilation, SourceModuleSymbol, AssemblySymbol, TypeSymbol, NamedTypeSymbol, MethodSymbol, SyntaxNode, NoPia.EmbeddedTypesManager, ModuleCompilationState) ' Not many methods should end up here. Private ReadOnly _disableJITOptimization As ConcurrentDictionary(Of MethodSymbol, Boolean) = New ConcurrentDictionary(Of MethodSymbol, Boolean)(ReferenceEqualityComparer.Instance) ' Gives the name of this module (may not reflect the name of the underlying symbol). ' See Assembly.MetadataName. Private ReadOnly _metadataName As String Private _lazyExportedTypes As ImmutableArray(Of Cci.ExportedType) Private ReadOnly _lazyNumberOfTypesFromOtherModules As Integer Private _lazyTranslatedImports As ImmutableArray(Of Cci.UsedNamespaceOrType) Private _lazyDefaultNamespace As String Friend Sub New(sourceModule As SourceModuleSymbol, emitOptions As EmitOptions, outputKind As OutputKind, serializationProperties As Cci.ModulePropertiesForSerialization, manifestResources As IEnumerable(Of ResourceDescription)) MyBase.New(sourceModule.ContainingSourceAssembly.DeclaringCompilation, sourceModule, serializationProperties, manifestResources, outputKind, emitOptions, New ModuleCompilationState()) Dim specifiedName = sourceModule.MetadataName _metadataName = If(specifiedName <> CodeAnalysis.Compilation.UnspecifiedModuleAssemblyName, specifiedName, If(emitOptions.OutputNameOverride, specifiedName)) m_AssemblyOrModuleSymbolToModuleRefMap.Add(sourceModule, Me) If sourceModule.AnyReferencedAssembliesAreLinked Then _embeddedTypesManagerOpt = New NoPia.EmbeddedTypesManager(Me) End If End Sub ''' <summary> ''' True if conditional calls may be omitted when the required preprocessor symbols are not defined. ''' </summary> ''' <remarks> ''' Only false in debugger scenarios (where calls should never be omitted). ''' </remarks> Friend MustOverride ReadOnly Property AllowOmissionOfConditionalCalls As Boolean Public Overrides ReadOnly Property Name As String Get Return _metadataName End Get End Property Friend NotOverridable Overrides ReadOnly Property ModuleName As String Get Return _metadataName End Get End Property Friend NotOverridable Overrides ReadOnly Property CorLibrary As AssemblySymbol Get Return SourceModule.ContainingSourceAssembly.CorLibrary End Get End Property Public NotOverridable Overrides ReadOnly Property GenerateVisualBasicStylePdb As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property LinkedAssembliesDebugInfo As IEnumerable(Of String) Get ' NOTE: Dev12 does not seem to emit anything but the name (i.e. no version, token, etc). ' See Builder::WriteNoPiaPdbList Return SourceModule.ReferencedAssemblySymbols.Where(Function(a) a.IsLinked).Select(Function(a) a.Name) End Get End Property Public NotOverridable Overrides Function GetImports() As ImmutableArray(Of Cci.UsedNamespaceOrType) ' Imports should have been translated in code gen phase. Debug.Assert(Not _lazyTranslatedImports.IsDefault) Return _lazyTranslatedImports End Function Public Sub TranslateImports(diagnostics As DiagnosticBag) If _lazyTranslatedImports.IsDefault Then ImmutableInterlocked.InterlockedInitialize( _lazyTranslatedImports, NamespaceScopeBuilder.BuildNamespaceScope(Me, SourceModule.XmlNamespaces, SourceModule.AliasImports, SourceModule.MemberImports, diagnostics)) End If End Sub Public NotOverridable Overrides ReadOnly Property DefaultNamespace As String Get If _lazyDefaultNamespace IsNot Nothing Then Return _lazyDefaultNamespace End If Dim rootNamespace = SourceModule.RootNamespace If rootNamespace.IsGlobalNamespace Then Return String.Empty End If _lazyDefaultNamespace = rootNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) Return _lazyDefaultNamespace End Get End Property Protected NotOverridable Overrides Iterator Function GetAssemblyReferencesFromAddedModules(diagnostics As DiagnosticBag) As IEnumerable(Of Cci.IAssemblyReference) Dim modules As ImmutableArray(Of ModuleSymbol) = SourceModule.ContainingAssembly.Modules For i As Integer = 1 To modules.Length - 1 For Each aRef As AssemblySymbol In modules(i).GetReferencedAssemblySymbols() Yield Translate(aRef, diagnostics) Next Next End Function Private Sub ValidateReferencedAssembly(assembly As AssemblySymbol, asmRef As AssemblyReference, diagnostics As DiagnosticBag) Dim asmIdentity As AssemblyIdentity = SourceModule.ContainingAssembly.Identity Dim refIdentity As AssemblyIdentity = asmRef.Identity If asmIdentity.IsStrongName AndAlso Not refIdentity.IsStrongName AndAlso asmRef.Identity.ContentType <> Reflection.AssemblyContentType.WindowsRuntime Then ' Dev12 reported error, we have changed it to a warning to allow referencing libraries ' built for platforms that don't support strong names. diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_ReferencedAssemblyDoesNotHaveStrongName, assembly), NoLocation.Singleton) End If If OutputKind <> OutputKind.NetModule AndAlso Not String.IsNullOrEmpty(refIdentity.CultureName) AndAlso Not String.Equals(refIdentity.CultureName, asmIdentity.CultureName, StringComparison.OrdinalIgnoreCase) Then diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_RefCultureMismatch, assembly, refIdentity.CultureName), NoLocation.Singleton) End If Dim refMachine = assembly.Machine ' If other assembly is agnostic, this is always safe ' Also, if no mscorlib was specified for back compat we add a reference to mscorlib ' that resolves to the current framework directory. If the compiler Is 64-bit ' this Is a 64-bit mscorlib, which will produce a warning if /platform:x86 Is ' specified.A reference to the default mscorlib should always succeed without ' warning so we ignore it here. If assembly IsNot assembly.CorLibrary AndAlso Not (refMachine = Machine.I386 AndAlso Not assembly.Bit32Required) Then Dim machine = SourceModule.Machine If Not (machine = Machine.I386 AndAlso Not SourceModule.Bit32Required) AndAlso machine <> refMachine Then ' Different machine types, and neither is agnostic diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.WRN_ConflictingMachineAssembly, assembly), NoLocation.Singleton) End If End If If _embeddedTypesManagerOpt IsNot Nothing AndAlso _embeddedTypesManagerOpt.IsFrozen Then _embeddedTypesManagerOpt.ReportIndirectReferencesToLinkedAssemblies(assembly, diagnostics) End If End Sub Friend NotOverridable Overrides Function SynthesizeAttribute(attributeConstructor As WellKnownMember) As Cci.ICustomAttribute Return Me.Compilation.TrySynthesizeAttribute(attributeConstructor) End Function Public NotOverridable Overrides Function GetSourceAssemblyAttributes(isRefAssembly As Boolean) As IEnumerable(Of Cci.ICustomAttribute) Return SourceModule.ContainingSourceAssembly.GetAssemblyCustomAttributesToEmit(Me.CompilationState, isRefAssembly, emittingAssemblyAttributesInNetModule:=OutputKind.IsNetModule()) End Function Public NotOverridable Overrides Function GetSourceAssemblySecurityAttributes() As IEnumerable(Of Cci.SecurityAttribute) Return SourceModule.ContainingSourceAssembly.GetSecurityAttributes() End Function Public NotOverridable Overrides Function GetSourceModuleAttributes() As IEnumerable(Of Cci.ICustomAttribute) Return SourceModule.GetCustomAttributesToEmit(Me.CompilationState) End Function Public NotOverridable Overrides Function GetSymbolToLocationMap() As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation) Dim result As New MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation)() Dim namespacesAndTypesToProcess As New Stack(Of NamespaceOrTypeSymbol)() namespacesAndTypesToProcess.Push(SourceModule.GlobalNamespace) Dim location As Location = Nothing While namespacesAndTypesToProcess.Count > 0 Dim symbol As NamespaceOrTypeSymbol = namespacesAndTypesToProcess.Pop() Select Case symbol.Kind Case SymbolKind.Namespace location = GetSmallestSourceLocationOrNull(symbol) ' filtering out synthesized symbols not having real source ' locations such as anonymous types, my types, etc... If location IsNot Nothing Then For Each member In symbol.GetMembers() Select Case member.Kind Case SymbolKind.Namespace, SymbolKind.NamedType namespacesAndTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol)) Case Else Throw ExceptionUtilities.UnexpectedValue(member.Kind) End Select Next End If Case SymbolKind.NamedType location = GetSmallestSourceLocationOrNull(symbol) If location IsNot Nothing Then ' add this named type location AddSymbolLocation(result, location, DirectCast(symbol.GetCciAdapter(), Cci.IDefinition)) For Each member In symbol.GetMembers() Select Case member.Kind Case SymbolKind.NamedType namespacesAndTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol)) Case SymbolKind.Method Dim method = DirectCast(member, MethodSymbol) If method.IsDefaultValueTypeConstructor() OrElse method.IsPartialWithoutImplementation Then Exit Select End If AddSymbolLocation(result, member) Case SymbolKind.Property, SymbolKind.Field AddSymbolLocation(result, member) Case SymbolKind.Event AddSymbolLocation(result, member) Dim AssociatedField = (DirectCast(member, EventSymbol)).AssociatedField If AssociatedField IsNot Nothing Then ' event backing fields do not show up in GetMembers AddSymbolLocation(result, AssociatedField) End If Case Else Throw ExceptionUtilities.UnexpectedValue(member.Kind) End Select Next End If Case Else Throw ExceptionUtilities.UnexpectedValue(symbol.Kind) End Select End While Return result End Function Private Sub AddSymbolLocation(result As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation), symbol As Symbol) Dim location As Location = GetSmallestSourceLocationOrNull(symbol) If location IsNot Nothing Then AddSymbolLocation(result, location, DirectCast(symbol.GetCciAdapter(), Cci.IDefinition)) End If End Sub Private Sub AddSymbolLocation(result As MultiDictionary(Of Cci.DebugSourceDocument, Cci.DefinitionWithLocation), location As Location, definition As Cci.IDefinition) Dim span As FileLinePositionSpan = location.GetLineSpan() Dim doc As Cci.DebugSourceDocument = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath:=location.SourceTree.FilePath) If (doc IsNot Nothing) Then result.Add(doc, New Cci.DefinitionWithLocation( definition, span.StartLinePosition.Line, span.StartLinePosition.Character, span.EndLinePosition.Line, span.EndLinePosition.Character)) End If End Sub Private Function GetSmallestSourceLocationOrNull(symbol As Symbol) As Location Dim compilation As VisualBasicCompilation = symbol.DeclaringCompilation Debug.Assert(Me.Compilation Is compilation, "How did we get symbol from different compilation?") Dim result As Location = Nothing For Each loc In symbol.Locations If loc.IsInSource AndAlso (result Is Nothing OrElse compilation.CompareSourceLocations(result, loc) > 0) Then result = loc End If Next Return result End Function ''' <summary> ''' Ignore accessibility when resolving well-known type ''' members, in particular for generic type arguments ''' (e.g.: binding to internal types in the EE). ''' </summary> Friend Overridable ReadOnly Property IgnoreAccessibility As Boolean Get Return False End Get End Property Friend Overridable Function TryCreateVariableSlotAllocator(method As MethodSymbol, topLevelMethod As MethodSymbol, diagnostics As DiagnosticBag) As VariableSlotAllocator Return Nothing End Function Friend Overridable Function GetPreviousAnonymousTypes() As ImmutableArray(Of AnonymousTypeKey) Return ImmutableArray(Of AnonymousTypeKey).Empty End Function Friend Overridable Function GetNextAnonymousTypeIndex(fromDelegates As Boolean) As Integer Return 0 End Function Friend Overridable Function TryGetAnonymousTypeName(template As AnonymousTypeManager.AnonymousTypeOrDelegateTemplateSymbol, <Out> ByRef name As String, <Out> ByRef index As Integer) As Boolean Debug.Assert(Compilation Is template.DeclaringCompilation) name = Nothing index = -1 Return False End Function Public NotOverridable Overrides Function GetAnonymousTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) If context.MetadataOnly Then Return SpecializedCollections.EmptyEnumerable(Of Cci.INamespaceTypeDefinition) End If #If DEBUG Then Return SourceModule.ContainingSourceAssembly.DeclaringCompilation.AnonymousTypeManager.AllCreatedTemplates.Select(Function(t) t.GetCciAdapter()) #Else Return SourceModule.ContainingSourceAssembly.DeclaringCompilation.AnonymousTypeManager.AllCreatedTemplates #End If End Function Public Overrides Iterator Function GetTopLevelSourceTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) Dim embeddedSymbolManager As EmbeddedSymbolManager = SourceModule.ContainingSourceAssembly.DeclaringCompilation.EmbeddedSymbolManager Dim stack As New Stack(Of NamespaceOrTypeSymbol)() stack.Push(SourceModule.GlobalNamespace) Do Dim sym As NamespaceOrTypeSymbol = stack.Pop() If sym.Kind = SymbolKind.NamedType Then Debug.Assert(sym Is sym.OriginalDefinition) Debug.Assert(sym.ContainingType Is Nothing) ' Skip unreferenced embedded types. If Not sym.IsEmbedded OrElse embeddedSymbolManager.IsSymbolReferenced(sym) Then Yield DirectCast(sym, NamedTypeSymbol).GetCciAdapter() End If Else Debug.Assert(sym.Kind = SymbolKind.Namespace) Dim members As ImmutableArray(Of Symbol) = sym.GetMembers() For i As Integer = members.Length - 1 To 0 Step -1 Dim namespaceOrType As NamespaceOrTypeSymbol = TryCast(members(i), NamespaceOrTypeSymbol) If namespaceOrType IsNot Nothing Then stack.Push(namespaceOrType) End If Next End If Loop While stack.Count > 0 End Function Public NotOverridable Overrides Function GetExportedTypes(diagnostics As DiagnosticBag) As ImmutableArray(Of Cci.ExportedType) Debug.Assert(HaveDeterminedTopLevelTypes) If _lazyExportedTypes.IsDefault Then _lazyExportedTypes = CalculateExportedTypes() If _lazyExportedTypes.Length > 0 Then ReportExportedTypeNameCollisions(_lazyExportedTypes, diagnostics) End If End If Return _lazyExportedTypes End Function ''' <summary> ''' Builds an array of public type symbols defined in netmodules included in the compilation ''' And type forwarders defined in this compilation Or any included netmodule (in this order). ''' </summary> Private Function CalculateExportedTypes() As ImmutableArray(Of Cci.ExportedType) Dim builder = ArrayBuilder(Of Cci.ExportedType).GetInstance() Dim sourceAssembly As SourceAssemblySymbol = SourceModule.ContainingSourceAssembly If Not OutputKind.IsNetModule() Then Dim modules = sourceAssembly.Modules For i As Integer = 1 To modules.Length - 1 'NOTE: skipping modules(0) GetExportedTypes(modules(i).GlobalNamespace, -1, builder) Next End If Debug.Assert(OutputKind.IsNetModule() = sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule()) GetForwardedTypes(sourceAssembly, builder) Return builder.ToImmutableAndFree() End Function ''' <summary> ''' Returns a set of top-level forwarded types ''' </summary> Friend Shared Function GetForwardedTypes(sourceAssembly As SourceAssemblySymbol, builderOpt As ArrayBuilder(Of Cci.ExportedType)) As HashSet(Of NamedTypeSymbol) Dim seenTopLevelForwardedTypes = New HashSet(Of NamedTypeSymbol)() GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetSourceDecodedWellKnownAttributeData(), builderOpt) If Not sourceAssembly.DeclaringCompilation.Options.OutputKind.IsNetModule() Then GetForwardedTypes(seenTopLevelForwardedTypes, sourceAssembly.GetNetModuleDecodedWellKnownAttributeData(), builderOpt) End If Return seenTopLevelForwardedTypes End Function Private Sub ReportExportedTypeNameCollisions(exportedTypes As ImmutableArray(Of Cci.ExportedType), diagnostics As DiagnosticBag) Dim sourceAssembly As SourceAssemblySymbol = SourceModule.ContainingSourceAssembly Dim exportedNamesMap = New Dictionary(Of String, NamedTypeSymbol)() For Each exportedType In _lazyExportedTypes Dim typeReference As Cci.ITypeReference = exportedType.Type Dim type = DirectCast(typeReference.GetInternalSymbol(), NamedTypeSymbol) Debug.Assert(type.IsDefinition) If type.ContainingType IsNot Nothing Then Continue For End If ' exported types are not emitted in EnC deltas (hence generation 0): Dim fullEmittedName As String = MetadataHelpers.BuildQualifiedName( DirectCast(typeReference, Cci.INamespaceTypeReference).NamespaceName, Cci.MetadataWriter.GetMangledName(DirectCast(typeReference, Cci.INamedTypeReference), generation:=0)) ' First check against types declared in the primary module If ContainsTopLevelType(fullEmittedName) Then If type.ContainingAssembly Is sourceAssembly Then diagnostics.Add(ERRID.ERR_ExportedTypeConflictsWithDeclaration, NoLocation.Singleton, type, type.ContainingModule) Else diagnostics.Add(ERRID.ERR_ForwardedTypeConflictsWithDeclaration, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type)) End If Continue For End If Dim contender As NamedTypeSymbol = Nothing ' Now check against other exported types If exportedNamesMap.TryGetValue(fullEmittedName, contender) Then If type.ContainingAssembly Is sourceAssembly Then ' all exported types precede forwarded types, therefore contender cannot be a forwarded type. Debug.Assert(contender.ContainingAssembly Is sourceAssembly) diagnostics.Add(ERRID.ERR_ExportedTypesConflict, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type), CustomSymbolDisplayFormatter.DefaultErrorFormat(type.ContainingModule), CustomSymbolDisplayFormatter.DefaultErrorFormat(contender), CustomSymbolDisplayFormatter.DefaultErrorFormat(contender.ContainingModule)) ElseIf contender.ContainingAssembly Is sourceAssembly Then ' Forwarded type conflicts with exported type diagnostics.Add(ERRID.ERR_ForwardedTypeConflictsWithExportedType, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type), type.ContainingAssembly, CustomSymbolDisplayFormatter.DefaultErrorFormat(contender), CustomSymbolDisplayFormatter.DefaultErrorFormat(contender.ContainingModule)) Else ' Forwarded type conflicts with another forwarded type diagnostics.Add(ERRID.ERR_ForwardedTypesConflict, NoLocation.Singleton, CustomSymbolDisplayFormatter.DefaultErrorFormat(type), type.ContainingAssembly, CustomSymbolDisplayFormatter.DefaultErrorFormat(contender), contender.ContainingAssembly) End If Continue For End If exportedNamesMap.Add(fullEmittedName, type) Next End Sub Private Overloads Sub GetExportedTypes(symbol As NamespaceOrTypeSymbol, parentIndex As Integer, builder As ArrayBuilder(Of Cci.ExportedType)) Dim index As Integer If symbol.Kind = SymbolKind.NamedType Then If symbol.DeclaredAccessibility <> Accessibility.Public Then Return End If Debug.Assert(symbol.IsDefinition) index = builder.Count builder.Add(New Cci.ExportedType(DirectCast(symbol, NamedTypeSymbol).GetCciAdapter(), parentIndex, isForwarder:=False)) Else index = -1 End If For Each member In symbol.GetMembers() Dim namespaceOrType = TryCast(member, NamespaceOrTypeSymbol) If namespaceOrType IsNot Nothing Then GetExportedTypes(namespaceOrType, index, builder) End If Next End Sub Private Shared Sub GetForwardedTypes( seenTopLevelTypes As HashSet(Of NamedTypeSymbol), wellKnownAttributeData As CommonAssemblyWellKnownAttributeData(Of NamedTypeSymbol), builderOpt As ArrayBuilder(Of Cci.ExportedType)) If wellKnownAttributeData?.ForwardedTypes?.Count > 0 Then ' (type, index of the parent exported type in builder, or -1 if the type is a top-level type) Dim stack = ArrayBuilder(Of (type As NamedTypeSymbol, parentIndex As Integer)).GetInstance() ' Hashset enumeration is not guaranteed to be deterministic. Emitting in the order of fully qualified names. Dim orderedForwardedTypes As IEnumerable(Of NamedTypeSymbol) = wellKnownAttributeData.ForwardedTypes If builderOpt IsNot Nothing Then orderedForwardedTypes = orderedForwardedTypes.OrderBy(Function(t) t.OriginalDefinition.ToDisplayString(SymbolDisplayFormat.QualifiedNameArityFormat)) End If For Each forwardedType As NamedTypeSymbol In orderedForwardedTypes Dim originalDefinition As NamedTypeSymbol = forwardedType.OriginalDefinition Debug.Assert(originalDefinition.ContainingType Is Nothing, "How did a nested type get forwarded?") ' De-dup the original definitions before emitting. If Not seenTopLevelTypes.Add(originalDefinition) Then Continue For End If If builderOpt IsNot Nothing Then ' Return all nested types. ' Note the order: depth first, children in reverse order (to match dev10, not a requirement). Debug.Assert(stack.Count = 0) stack.Push((originalDefinition, -1)) While stack.Count > 0 Dim entry = stack.Pop() ' In general, we don't want private types to appear in the ExportedTypes table. If entry.type.DeclaredAccessibility = Accessibility.Private Then ' NOTE: this will also exclude nested types of curr. Continue While End If ' NOTE: not bothering to put nested types in seenTypes - the top-level type is adequate protection. Dim index = builderOpt.Count builderOpt.Add(New Cci.ExportedType(entry.type.GetCciAdapter(), entry.parentIndex, isForwarder:=True)) ' Iterate backwards so they get popped in forward order. Dim nested As ImmutableArray(Of NamedTypeSymbol) = entry.type.GetTypeMembers() ' Ordered. For i As Integer = nested.Length - 1 To 0 Step -1 stack.Push((nested(i), index)) Next End While End If Next stack.Free() End If End Sub Friend Iterator Function GetReferencedAssembliesUsedSoFar() As IEnumerable(Of AssemblySymbol) For Each assembly In SourceModule.GetReferencedAssemblySymbols() If Not assembly.IsLinked AndAlso Not assembly.IsMissing AndAlso m_AssemblyOrModuleSymbolToModuleRefMap.ContainsKey(assembly) Then Yield assembly End If Next End Function Friend NotOverridable Overrides Function GetSpecialType(specialType As SpecialType, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As Cci.INamedTypeReference Return Translate(GetUntranslatedSpecialType(specialType, syntaxNodeOpt, diagnostics), needDeclaration:=True, syntaxNodeOpt:=syntaxNodeOpt, diagnostics:=diagnostics) End Function Private Function GetUntranslatedSpecialType(specialType As SpecialType, syntaxNodeOpt As SyntaxNode, diagnostics As DiagnosticBag) As NamedTypeSymbol Dim typeSymbol = SourceModule.ContainingAssembly.GetSpecialType(specialType) Dim info = Binder.GetUseSiteInfoForSpecialType(typeSymbol) If info.DiagnosticInfo IsNot Nothing Then Binder.ReportDiagnostic(diagnostics, If(syntaxNodeOpt IsNot Nothing, syntaxNodeOpt.GetLocation(), NoLocation.Singleton), info.DiagnosticInfo) End If Return typeSymbol End Function Public NotOverridable Overrides Function GetInitArrayHelper() As Cci.IMethodReference Return DirectCast(Compilation.GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__InitializeArrayArrayRuntimeFieldHandle), MethodSymbol)?.GetCciAdapter() End Function Public NotOverridable Overrides Function IsPlatformType(typeRef As Cci.ITypeReference, platformType As Cci.PlatformType) As Boolean Dim namedType = TryCast(typeRef.GetInternalSymbol(), NamedTypeSymbol) If namedType IsNot Nothing Then If platformType = Cci.PlatformType.SystemType Then Return namedType Is Compilation.GetWellKnownType(WellKnownType.System_Type) End If Return namedType.SpecialType = CType(platformType, SpecialType) End If Return False End Function Protected NotOverridable Overrides Function GetCorLibraryReferenceToEmit(context As EmitContext) As Cci.IAssemblyReference Dim corLib = CorLibrary If Not corLib.IsMissing AndAlso Not corLib.IsLinked AndAlso corLib IsNot SourceModule.ContainingAssembly Then Return Translate(corLib, context.Diagnostics) End If Return Nothing End Function Friend NotOverridable Overrides Function GetSynthesizedNestedTypes(container As NamedTypeSymbol) As IEnumerable(Of Cci.INestedTypeDefinition) Return container.GetSynthesizedNestedTypes() End Function Public Overrides Iterator Function GetTypeToDebugDocumentMap(context As EmitContext) As IEnumerable(Of (Cci.ITypeDefinition, ImmutableArray(Of Cci.DebugSourceDocument))) Dim typesToProcess = ArrayBuilder(Of Cci.ITypeDefinition).GetInstance() Dim debugDocuments = ArrayBuilder(Of Cci.DebugSourceDocument).GetInstance() Dim methodDocumentList = PooledHashSet(Of Cci.DebugSourceDocument).GetInstance() Dim namespacesAndTopLevelTypesToProcess = ArrayBuilder(Of NamespaceOrTypeSymbol).GetInstance() namespacesAndTopLevelTypesToProcess.Push(SourceModule.GlobalNamespace) While namespacesAndTopLevelTypesToProcess.Count > 0 Dim symbol = namespacesAndTopLevelTypesToProcess.Pop() If symbol.Locations.Length = 0 Then Continue While End If Select Case symbol.Kind Case SymbolKind.Namespace Dim location = GetSmallestSourceLocationOrNull(symbol) ' filtering out synthesized symbols not having real source ' locations such as anonymous types, my types, etc... If location IsNot Nothing Then For Each member In symbol.GetMembers() Select Case member.Kind Case SymbolKind.Namespace, SymbolKind.NamedType namespacesAndTopLevelTypesToProcess.Push(DirectCast(member, NamespaceOrTypeSymbol)) Case Else Throw ExceptionUtilities.UnexpectedValue(member.Kind) End Select Next End If Case SymbolKind.NamedType ' We only process top level types in this method, and only return documents for types if there are no ' methods that would refer to the same document, either in the type or in any nested type. Debug.Assert(debugDocuments.Count = 0) Debug.Assert(methodDocumentList.Count = 0) Debug.Assert(typesToProcess.Count = 0) Dim typeDefinition = DirectCast(symbol.GetCciAdapter(), Cci.ITypeDefinition) typesToProcess.Push(typeDefinition) GetDocumentsForMethodsAndNestedTypes(methodDocumentList, typesToProcess, context) For Each loc In symbol.Locations If Not loc.IsInSource Then Continue For End If Dim span = loc.GetLineSpan() Dim debugDocument = DebugDocumentsBuilder.TryGetDebugDocument(span.Path, basePath:=Nothing) If debugDocument IsNot Nothing AndAlso Not methodDocumentList.Contains(debugDocument) Then debugDocuments.Add(debugDocument) End If Next If debugDocuments.Count > 0 Then Yield (typeDefinition, debugDocuments.ToImmutable()) End If debugDocuments.Clear() methodDocumentList.Clear() Case Else Throw ExceptionUtilities.UnexpectedValue(symbol.Kind) End Select End While namespacesAndTopLevelTypesToProcess.Free() debugDocuments.Free() methodDocumentList.Free() typesToProcess.Free() End Function Private Shared Sub GetDocumentsForMethodsAndNestedTypes(documentList As PooledHashSet(Of Cci.DebugSourceDocument), typesToProcess As ArrayBuilder(Of Cci.ITypeDefinition), context As EmitContext) While typesToProcess.Count > 0 Dim definition = typesToProcess.Pop() Dim typeMethods = definition.GetMethods(context) For Each method In typeMethods Dim body = method.GetBody(context) If body Is Nothing Then Continue For End If For Each point In body.SequencePoints documentList.Add(point.Document) Next Next Dim nestedTypes = definition.GetNestedTypes(context) For Each nestedTypeDefinition In nestedTypes typesToProcess.Push(nestedTypeDefinition) Next End While End Sub Public Sub SetDisableJITOptimization(methodSymbol As MethodSymbol) Debug.Assert(methodSymbol.ContainingModule Is Me.SourceModule AndAlso methodSymbol Is methodSymbol.OriginalDefinition) _disableJITOptimization.TryAdd(methodSymbol, True) End Sub Public Function JITOptimizationIsDisabled(methodSymbol As MethodSymbol) As Boolean Debug.Assert(methodSymbol.ContainingModule Is Me.SourceModule AndAlso methodSymbol Is methodSymbol.OriginalDefinition) Return _disableJITOptimization.ContainsKey(methodSymbol) End Function Protected NotOverridable Overrides Function CreatePrivateImplementationDetailsStaticConstructor(details As PrivateImplementationDetails, syntaxOpt As SyntaxNode, diagnostics As DiagnosticBag) As Cci.IMethodDefinition Return New SynthesizedPrivateImplementationDetailsSharedConstructor(SourceModule, details, GetUntranslatedSpecialType(SpecialType.System_Void, syntaxOpt, diagnostics)).GetCciAdapter() End Function Public Overrides Function GetAdditionalTopLevelTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) #If DEBUG Then Return GetAdditionalTopLevelTypes().Select(Function(t) t.GetCciAdapter()) #Else Return GetAdditionalTopLevelTypes() #End If End Function Public Overrides Function GetEmbeddedTypeDefinitions(context As EmitContext) As IEnumerable(Of Cci.INamespaceTypeDefinition) #If DEBUG Then Return GetEmbeddedTypes(context.Diagnostics).Select(Function(t) t.GetCciAdapter()) #Else Return GetEmbeddedTypes(context.Diagnostics) #End If End Function End Class End Namespace
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Compilers/CSharp/Portable/BoundTree/BoundDagTemp.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; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { #if DEBUG [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] #endif partial class BoundDagTemp { /// <summary> /// Does this dag temp represent the original input of the pattern-matching operation? /// </summary> public bool IsOriginalInput => this.Source is null; public static BoundDagTemp ForOriginalInput(SyntaxNode syntax, TypeSymbol type) => new BoundDagTemp(syntax, type, source: null, 0); public override bool Equals(object? obj) => obj is BoundDagTemp other && this.Equals(other); public bool Equals(BoundDagTemp other) { return this.Type.Equals(other.Type, TypeCompareKind.AllIgnoreOptions) && object.Equals(this.Source, other.Source) && this.Index == other.Index; } /// <summary> /// Check if this is equivalent to the <paramref name="other"/> node, ignoring the source. /// </summary> public bool IsEquivalentTo(BoundDagTemp other) { return this.Type.Equals(other.Type, TypeCompareKind.AllIgnoreOptions) && this.Index == other.Index; } public override int GetHashCode() { return Hash.Combine(this.Type.GetHashCode(), Hash.Combine(this.Source?.GetHashCode() ?? 0, this.Index)); } #if DEBUG internal new string GetDebuggerDisplay() { var name = Source?.Id switch { -1 => "<uninitialized>", // Note that we never expect to have a non-null source with id 0 // because id 0 is reserved for the original input. // However, we also don't want to assert in a debugger display method. 0 => "<error>", null => "t0", var id => $"t{id}" }; return $"{name}{(Source is BoundDagDeconstructEvaluation ? $".Item{(Index + 1).ToString()}" : "")}"; } #endif } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { #if DEBUG [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] #endif partial class BoundDagTemp { /// <summary> /// Does this dag temp represent the original input of the pattern-matching operation? /// </summary> public bool IsOriginalInput => this.Source is null; public static BoundDagTemp ForOriginalInput(SyntaxNode syntax, TypeSymbol type) => new BoundDagTemp(syntax, type, source: null, 0); public override bool Equals(object? obj) => obj is BoundDagTemp other && this.Equals(other); public bool Equals(BoundDagTemp other) { return this.Type.Equals(other.Type, TypeCompareKind.AllIgnoreOptions) && object.Equals(this.Source, other.Source) && this.Index == other.Index; } /// <summary> /// Check if this is equivalent to the <paramref name="other"/> node, ignoring the source. /// </summary> public bool IsEquivalentTo(BoundDagTemp other) { return this.Type.Equals(other.Type, TypeCompareKind.AllIgnoreOptions) && this.Index == other.Index; } public override int GetHashCode() { return Hash.Combine(this.Type.GetHashCode(), Hash.Combine(this.Source?.GetHashCode() ?? 0, this.Index)); } #if DEBUG internal new string GetDebuggerDisplay() { var name = Source?.Id switch { -1 => "<uninitialized>", // Note that we never expect to have a non-null source with id 0 // because id 0 is reserved for the original input. // However, we also don't want to assert in a debugger display method. 0 => "<error>", null => "t0", var id => $"t{id}" }; return $"{name}{(Source is BoundDagDeconstructEvaluation ? $".Item{(Index + 1).ToString()}" : "")}"; } #endif } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Analyzers/CSharp/Analyzers/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionDiagnosticAnalyzer.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.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.RemoveConfusingSuppression { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpRemoveConfusingSuppressionDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public CSharpRemoveConfusingSuppressionDiagnosticAnalyzer() : base(IDEDiagnosticIds.RemoveConfusingSuppressionForIsExpressionDiagnosticId, EnforceOnBuildValues.RemoveConfusingSuppressionForIsExpression, option: null, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Remove_unnecessary_suppression_operator), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources.Suppression_operator_has_no_effect_and_can_be_misinterpreted), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.IsExpression, SyntaxKind.IsPatternExpression); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var node = context.Node; var left = node switch { BinaryExpressionSyntax binary => binary.Left, IsPatternExpressionSyntax isPattern => isPattern.Expression, _ => throw ExceptionUtilities.UnexpectedValue(node), }; if (left.Kind() != SyntaxKind.SuppressNullableWarningExpression) return; context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, ((PostfixUnaryExpressionSyntax)left).OperatorToken.GetLocation(), ReportDiagnostic.Warn, ImmutableArray.Create(node.GetLocation()), properties: 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.Collections.Immutable; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.RemoveConfusingSuppression { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpRemoveConfusingSuppressionDiagnosticAnalyzer : AbstractBuiltInCodeStyleDiagnosticAnalyzer { public CSharpRemoveConfusingSuppressionDiagnosticAnalyzer() : base(IDEDiagnosticIds.RemoveConfusingSuppressionForIsExpressionDiagnosticId, EnforceOnBuildValues.RemoveConfusingSuppressionForIsExpression, option: null, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Remove_unnecessary_suppression_operator), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources.Suppression_operator_has_no_effect_and_can_be_misinterpreted), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources))) { } public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKind.IsExpression, SyntaxKind.IsPatternExpression); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var node = context.Node; var left = node switch { BinaryExpressionSyntax binary => binary.Left, IsPatternExpressionSyntax isPattern => isPattern.Expression, _ => throw ExceptionUtilities.UnexpectedValue(node), }; if (left.Kind() != SyntaxKind.SuppressNullableWarningExpression) return; context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, ((PostfixUnaryExpressionSyntax)left).OperatorToken.GetLocation(), ReportDiagnostic.Warn, ImmutableArray.Create(node.GetLocation()), properties: null)); } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Compilers/CSharp/Portable/Utilities/IValueSetFactory.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; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A value set factory, which can be used to create a value set instance. A given instance of <see cref="IValueSetFactory"/> /// supports only one type for the value sets it can produce. /// </summary> internal interface IValueSetFactory { /// <summary> /// Returns a value set that includes any values that satisfy the given relation when compared to the given value. /// </summary> IValueSet Related(BinaryOperatorKind relation, ConstantValue value); /// <summary> /// Returns true iff the values are related according to the given relation. /// </summary> bool Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right); /// <summary> /// Produce a random value set with the given expected size for testing. /// </summary> IValueSet Random(int expectedSize, Random random); /// <summary> /// Produce a random value for testing. /// </summary> ConstantValue RandomValue(Random random); /// <summary> /// The set containing all values of the type. /// </summary> IValueSet AllValues { get; } /// <summary> /// The empty set of values. /// </summary> IValueSet NoValues { get; } } /// <summary> /// A value set factory, which can be used to create a value set instance. Like <see cref="ValueSetFactory"/> but strongly /// typed to <typeparamref name="T"/>. /// </summary> internal interface IValueSetFactory<T> : IValueSetFactory { /// <summary> /// Returns a value set that includes any values that satisfy the given relation when compared to the given value. /// </summary> IValueSet<T> Related(BinaryOperatorKind relation, T value); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A value set factory, which can be used to create a value set instance. A given instance of <see cref="IValueSetFactory"/> /// supports only one type for the value sets it can produce. /// </summary> internal interface IValueSetFactory { /// <summary> /// Returns a value set that includes any values that satisfy the given relation when compared to the given value. /// </summary> IValueSet Related(BinaryOperatorKind relation, ConstantValue value); /// <summary> /// Returns true iff the values are related according to the given relation. /// </summary> bool Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right); /// <summary> /// Produce a random value set with the given expected size for testing. /// </summary> IValueSet Random(int expectedSize, Random random); /// <summary> /// Produce a random value for testing. /// </summary> ConstantValue RandomValue(Random random); /// <summary> /// The set containing all values of the type. /// </summary> IValueSet AllValues { get; } /// <summary> /// The empty set of values. /// </summary> IValueSet NoValues { get; } } /// <summary> /// A value set factory, which can be used to create a value set instance. Like <see cref="ValueSetFactory"/> but strongly /// typed to <typeparamref name="T"/>. /// </summary> internal interface IValueSetFactory<T> : IValueSetFactory { /// <summary> /// Returns a value set that includes any values that satisfy the given relation when compared to the given value. /// </summary> IValueSet<T> Related(BinaryOperatorKind relation, T value); } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/EditorFeatures/Test2/Extensions/ISymbolExtensionsTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.FindSymbols Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces <[UseExportProvider]> Public Class ISymbolExtensionsTests Inherits TestBase Private Shared Async Function TestIsAccessibleWithinAsync(workspaceDefinition As XElement, expectedVisible As Boolean) As Tasks.Task Using workspace = TestWorkspace.Create(workspaceDefinition) Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue) Dim cursorPosition = cursorDocument.CursorPosition.Value Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id) Dim semanticModel = Await document.GetSemanticModelAsync() Dim symbol = Await SymbolFinder.FindSymbolAtPositionAsync(document, cursorPosition) Dim namedTypeSymbol = semanticModel.GetEnclosingNamedType(cursorPosition, CancellationToken.None) Dim actualVisible = symbol.IsAccessibleWithin(namedTypeSymbol) Assert.Equal(expectedVisible, actualVisible) End Using End Function <Fact> Public Async Function TestIsAccessibleWithin_ProtectedInternal() As Task Dim workspace = <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document> public class Program { protected internal void M() { } } </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>CSharpAssembly</ProjectReference> <Document> class C { void M() { Program.$$M(); } } </Document> </Project> </Workspace> Await TestIsAccessibleWithinAsync(workspace, False) End Function <Fact> Public Async Function TestIsAccessibleWithin_ProtectedInternal_InternalsVisibleTo() As Task Dim workspace = <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("CSharpAssembly2")] public class Program { protected internal static int F; } </Document> </Project> <Project Language="C#" AssemblyName="CSharpAssembly2" CommonReferences="true"> <ProjectReference>CSharpAssembly</ProjectReference> <Document> class C { void M() { var f = Program.$$F; } } </Document> </Project> </Workspace> Await TestIsAccessibleWithinAsync(workspace, True) End Function <Fact> Public Async Function TestIsAccessibleWithin_ProtectedInternal_WrongInternalsVisibleTo() As Task Dim workspace = <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("NonExisting")] public class Program { protected internal static int F; } </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>CSharpAssembly</ProjectReference> <Document> class C { void M() { var f = Program.$$F; } } </Document> </Project> </Workspace> Await TestIsAccessibleWithinAsync(workspace, False) End Function <Fact> Public Async Function TestIsAccessibleWithin_PrivateInsideNestedType() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Outer { private static int field; class Inner { private int consumer = $$field; } } </Document> </Project> </Workspace> Await TestIsAccessibleWithinAsync(workspace, True) End Function <Fact> Public Async Function TestIsAccessibleWithin_ProtectedInsideNestedType() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Outer { protected static int field; class Inner { private int consumer = $$field; } } </Document> </Project> </Workspace> Await TestIsAccessibleWithinAsync(workspace, True) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.FindSymbols Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces <[UseExportProvider]> Public Class ISymbolExtensionsTests Inherits TestBase Private Shared Async Function TestIsAccessibleWithinAsync(workspaceDefinition As XElement, expectedVisible As Boolean) As Tasks.Task Using workspace = TestWorkspace.Create(workspaceDefinition) Dim cursorDocument = workspace.Documents.First(Function(d) d.CursorPosition.HasValue) Dim cursorPosition = cursorDocument.CursorPosition.Value Dim document = workspace.CurrentSolution.GetDocument(cursorDocument.Id) Dim semanticModel = Await document.GetSemanticModelAsync() Dim symbol = Await SymbolFinder.FindSymbolAtPositionAsync(document, cursorPosition) Dim namedTypeSymbol = semanticModel.GetEnclosingNamedType(cursorPosition, CancellationToken.None) Dim actualVisible = symbol.IsAccessibleWithin(namedTypeSymbol) Assert.Equal(expectedVisible, actualVisible) End Using End Function <Fact> Public Async Function TestIsAccessibleWithin_ProtectedInternal() As Task Dim workspace = <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document> public class Program { protected internal void M() { } } </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>CSharpAssembly</ProjectReference> <Document> class C { void M() { Program.$$M(); } } </Document> </Project> </Workspace> Await TestIsAccessibleWithinAsync(workspace, False) End Function <Fact> Public Async Function TestIsAccessibleWithin_ProtectedInternal_InternalsVisibleTo() As Task Dim workspace = <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("CSharpAssembly2")] public class Program { protected internal static int F; } </Document> </Project> <Project Language="C#" AssemblyName="CSharpAssembly2" CommonReferences="true"> <ProjectReference>CSharpAssembly</ProjectReference> <Document> class C { void M() { var f = Program.$$F; } } </Document> </Project> </Workspace> Await TestIsAccessibleWithinAsync(workspace, True) End Function <Fact> Public Async Function TestIsAccessibleWithin_ProtectedInternal_WrongInternalsVisibleTo() As Task Dim workspace = <Workspace> <Project Language="C#" AssemblyName="CSharpAssembly" CommonReferences="true"> <Document> using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("NonExisting")] public class Program { protected internal static int F; } </Document> </Project> <Project Language="C#" CommonReferences="true"> <ProjectReference>CSharpAssembly</ProjectReference> <Document> class C { void M() { var f = Program.$$F; } } </Document> </Project> </Workspace> Await TestIsAccessibleWithinAsync(workspace, False) End Function <Fact> Public Async Function TestIsAccessibleWithin_PrivateInsideNestedType() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Outer { private static int field; class Inner { private int consumer = $$field; } } </Document> </Project> </Workspace> Await TestIsAccessibleWithinAsync(workspace, True) End Function <Fact> Public Async Function TestIsAccessibleWithin_ProtectedInsideNestedType() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Outer { protected static int field; class Inner { private int consumer = $$field; } } </Document> </Project> </Workspace> Await TestIsAccessibleWithinAsync(workspace, True) End Function End Class End Namespace
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Analyzers/CSharp/CodeFixes/UseObjectInitializer/CSharpUseObjectInitializerCodeFixProvider.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.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.UseObjectInitializer; namespace Microsoft.CodeAnalysis.CSharp.UseObjectInitializer { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseObjectInitializer), Shared] internal class CSharpUseObjectInitializerCodeFixProvider : AbstractUseObjectInitializerCodeFixProvider< SyntaxKind, ExpressionSyntax, StatementSyntax, ObjectCreationExpressionSyntax, MemberAccessExpressionSyntax, ExpressionStatementSyntax, VariableDeclaratorSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseObjectInitializerCodeFixProvider() { } protected override StatementSyntax GetNewStatement( StatementSyntax statement, ObjectCreationExpressionSyntax objectCreation, ImmutableArray<Match<ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, ExpressionStatementSyntax>> matches) { return statement.ReplaceNode( objectCreation, GetNewObjectCreation(objectCreation, matches)); } private static ObjectCreationExpressionSyntax GetNewObjectCreation( ObjectCreationExpressionSyntax objectCreation, ImmutableArray<Match<ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, ExpressionStatementSyntax>> matches) { return UseInitializerHelpers.GetNewObjectCreation( objectCreation, CreateExpressions(matches)); } private static SeparatedSyntaxList<ExpressionSyntax> CreateExpressions( ImmutableArray<Match<ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, ExpressionStatementSyntax>> matches) { var nodesAndTokens = new List<SyntaxNodeOrToken>(); for (var i = 0; i < matches.Length; i++) { var match = matches[i]; var expressionStatement = match.Statement; var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression; var newAssignment = assignment.WithLeft( match.MemberAccessExpression.Name.WithLeadingTrivia(match.MemberAccessExpression.GetLeadingTrivia())); if (i < matches.Length - 1) { nodesAndTokens.Add(newAssignment); var commaToken = SyntaxFactory.Token(SyntaxKind.CommaToken) .WithTriviaFrom(expressionStatement.SemicolonToken); nodesAndTokens.Add(commaToken); } else { newAssignment = newAssignment.WithTrailingTrivia( expressionStatement.GetTrailingTrivia()); nodesAndTokens.Add(newAssignment); } } return SyntaxFactory.SeparatedList<ExpressionSyntax>(nodesAndTokens); } } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.UseObjectInitializer; namespace Microsoft.CodeAnalysis.CSharp.UseObjectInitializer { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseObjectInitializer), Shared] internal class CSharpUseObjectInitializerCodeFixProvider : AbstractUseObjectInitializerCodeFixProvider< SyntaxKind, ExpressionSyntax, StatementSyntax, ObjectCreationExpressionSyntax, MemberAccessExpressionSyntax, ExpressionStatementSyntax, VariableDeclaratorSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseObjectInitializerCodeFixProvider() { } protected override StatementSyntax GetNewStatement( StatementSyntax statement, ObjectCreationExpressionSyntax objectCreation, ImmutableArray<Match<ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, ExpressionStatementSyntax>> matches) { return statement.ReplaceNode( objectCreation, GetNewObjectCreation(objectCreation, matches)); } private static ObjectCreationExpressionSyntax GetNewObjectCreation( ObjectCreationExpressionSyntax objectCreation, ImmutableArray<Match<ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, ExpressionStatementSyntax>> matches) { return UseInitializerHelpers.GetNewObjectCreation( objectCreation, CreateExpressions(matches)); } private static SeparatedSyntaxList<ExpressionSyntax> CreateExpressions( ImmutableArray<Match<ExpressionSyntax, StatementSyntax, MemberAccessExpressionSyntax, ExpressionStatementSyntax>> matches) { var nodesAndTokens = new List<SyntaxNodeOrToken>(); for (var i = 0; i < matches.Length; i++) { var match = matches[i]; var expressionStatement = match.Statement; var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression; var newAssignment = assignment.WithLeft( match.MemberAccessExpression.Name.WithLeadingTrivia(match.MemberAccessExpression.GetLeadingTrivia())); if (i < matches.Length - 1) { nodesAndTokens.Add(newAssignment); var commaToken = SyntaxFactory.Token(SyntaxKind.CommaToken) .WithTriviaFrom(expressionStatement.SemicolonToken); nodesAndTokens.Add(commaToken); } else { newAssignment = newAssignment.WithTrailingTrivia( expressionStatement.GetTrailingTrivia()); nodesAndTokens.Add(newAssignment); } } return SyntaxFactory.SeparatedList<ExpressionSyntax>(nodesAndTokens); } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./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,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/SharedVerifierState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.CodeAnalysis.Testing; using Microsoft.CodeAnalysis.Testing.Verifiers; #if !CODE_STYLE using Roslyn.Utilities; #endif namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { internal sealed class SharedVerifierState { private readonly AnalyzerTest<XUnitVerifier> _test; private readonly string _defaultFileExt; /// <summary> /// The index in <see cref="Testing.ProjectState.AnalyzerConfigFiles"/> of the generated /// <strong>.editorconfig</strong> file for <see cref="Options"/>, or <see langword="null"/> if no such /// file has been generated yet. /// </summary> private int? _analyzerConfigIndex; /// <summary> /// The index in <see cref="AnalyzerTest{TVerifier}.SolutionTransforms"/> of the options transformation for /// remaining <see cref="Options"/>, or <see langword="null"/> if no such transfor has been generated yet. /// </summary> private Func<Solution, ProjectId, Solution>? _remainingOptionsSolutionTransform; public SharedVerifierState(AnalyzerTest<XUnitVerifier> test, string defaultFileExt) { _test = test; _defaultFileExt = defaultFileExt; Options = new OptionsCollection(test.Language); } public string? EditorConfig { get; set; } /// <summary> /// Gets a collection of options to apply to <see cref="Solution.Options"/> for testing. Values may be added /// using a collection initializer. /// </summary> internal OptionsCollection Options { get; } internal void Apply() { var (analyzerConfigSource, remainingOptions) = CodeFixVerifierHelper.ConvertOptionsToAnalyzerConfig(_defaultFileExt, EditorConfig, Options); if (analyzerConfigSource is not null) { if (_analyzerConfigIndex is null) { _analyzerConfigIndex = _test.TestState.AnalyzerConfigFiles.Count; _test.TestState.AnalyzerConfigFiles.Add(("/.editorconfig", analyzerConfigSource)); } else { _test.TestState.AnalyzerConfigFiles[_analyzerConfigIndex.Value] = ("/.editorconfig", analyzerConfigSource); } } else if (_analyzerConfigIndex is { } index) { _analyzerConfigIndex = null; _test.TestState.AnalyzerConfigFiles.RemoveAt(index); } var solutionTransformIndex = _remainingOptionsSolutionTransform is not null ? _test.SolutionTransforms.IndexOf(_remainingOptionsSolutionTransform) : -1; if (remainingOptions is not null) { // Generate a new solution transform _remainingOptionsSolutionTransform = (solution, projectId) => { #if !CODE_STYLE var options = solution.Options; foreach (var (key, value) in remainingOptions) { options = options.WithChangedOption(key, value); } solution = solution.WithOptions(options); #endif return solution; }; if (solutionTransformIndex < 0) { _test.SolutionTransforms.Add(_remainingOptionsSolutionTransform); } else { _test.SolutionTransforms[solutionTransformIndex] = _remainingOptionsSolutionTransform; } } else if (_remainingOptionsSolutionTransform is not null) { _test.SolutionTransforms.Remove(_remainingOptionsSolutionTransform); _remainingOptionsSolutionTransform = 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 Microsoft.CodeAnalysis.Testing; using Microsoft.CodeAnalysis.Testing.Verifiers; #if !CODE_STYLE using Roslyn.Utilities; #endif namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions { internal sealed class SharedVerifierState { private readonly AnalyzerTest<XUnitVerifier> _test; private readonly string _defaultFileExt; /// <summary> /// The index in <see cref="Testing.ProjectState.AnalyzerConfigFiles"/> of the generated /// <strong>.editorconfig</strong> file for <see cref="Options"/>, or <see langword="null"/> if no such /// file has been generated yet. /// </summary> private int? _analyzerConfigIndex; /// <summary> /// The index in <see cref="AnalyzerTest{TVerifier}.SolutionTransforms"/> of the options transformation for /// remaining <see cref="Options"/>, or <see langword="null"/> if no such transfor has been generated yet. /// </summary> private Func<Solution, ProjectId, Solution>? _remainingOptionsSolutionTransform; public SharedVerifierState(AnalyzerTest<XUnitVerifier> test, string defaultFileExt) { _test = test; _defaultFileExt = defaultFileExt; Options = new OptionsCollection(test.Language); } public string? EditorConfig { get; set; } /// <summary> /// Gets a collection of options to apply to <see cref="Solution.Options"/> for testing. Values may be added /// using a collection initializer. /// </summary> internal OptionsCollection Options { get; } internal void Apply() { var (analyzerConfigSource, remainingOptions) = CodeFixVerifierHelper.ConvertOptionsToAnalyzerConfig(_defaultFileExt, EditorConfig, Options); if (analyzerConfigSource is not null) { if (_analyzerConfigIndex is null) { _analyzerConfigIndex = _test.TestState.AnalyzerConfigFiles.Count; _test.TestState.AnalyzerConfigFiles.Add(("/.editorconfig", analyzerConfigSource)); } else { _test.TestState.AnalyzerConfigFiles[_analyzerConfigIndex.Value] = ("/.editorconfig", analyzerConfigSource); } } else if (_analyzerConfigIndex is { } index) { _analyzerConfigIndex = null; _test.TestState.AnalyzerConfigFiles.RemoveAt(index); } var solutionTransformIndex = _remainingOptionsSolutionTransform is not null ? _test.SolutionTransforms.IndexOf(_remainingOptionsSolutionTransform) : -1; if (remainingOptions is not null) { // Generate a new solution transform _remainingOptionsSolutionTransform = (solution, projectId) => { #if !CODE_STYLE var options = solution.Options; foreach (var (key, value) in remainingOptions) { options = options.WithChangedOption(key, value); } solution = solution.WithOptions(options); #endif return solution; }; if (solutionTransformIndex < 0) { _test.SolutionTransforms.Add(_remainingOptionsSolutionTransform); } else { _test.SolutionTransforms[solutionTransformIndex] = _remainingOptionsSolutionTransform; } } else if (_remainingOptionsSolutionTransform is not null) { _test.SolutionTransforms.Remove(_remainingOptionsSolutionTransform); _remainingOptionsSolutionTransform = null; } } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/EditorFeatures/VisualBasicTest/ExtractMethod/ExtractMethodTests.ControlFlowAnalysis.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.ExtractMethod Partial Public Class ExtractMethodTests ''' <summary> ''' This contains tests for Extract Method components that depend on Control Flow Analysis API ''' (A) Selection Validator ''' (B) Analyzer ''' </summary> ''' <remarks></remarks> <[UseExportProvider]> Public Class FlowAnalysis <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestExitSub() As Threading.Tasks.Task Dim code = <text>Class Test Sub Test() [|Exit Sub|] End Sub End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestExitFunction() As Threading.Tasks.Task Dim code = <text>Class Test Function Test1() As Integer Console.Write(42) [|Test1 = 1 Console.Write(5) Exit Function|] End Function End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <WorkItem(540046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540046")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestReturnStatement() As Task Dim code = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) [|Return x|] End Function End Class</text> Dim expected = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Return NewMethod(x) End Function Private Shared Function NewMethod(x As Integer) As Integer Return x End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestDoBranch() As Task Dim code = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer [|Do Console.Write(i) i = i + 1 Loop Until i > 5|] Return x End Function End Class</text> Dim expected = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer i = NewMethod(i) Return x End Function Private Shared Function NewMethod(i As Integer) As Integer Do Console.Write(i) i = i + 1 Loop Until i &gt; 5 Return i End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestDoBranchInvalidSelection() As Task Dim code = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer [|Do Console.Write(i)|] i = i + 1 Loop Until i > 5 Return x End Function End Class</text> Dim expected = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer i = NewMethod(i) Return x End Function Private Shared Function NewMethod(i As Integer) As Integer Do Console.Write(i) i = i + 1 Loop Until i &gt; 5 Return i End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestDoBranchWithContinue() As Task Dim code = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer [|Do Console.Write(i) i = i + 1 Continue Do 'Blah Loop Until i > 5|] Return x End Function End Class</text> Dim expected = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer i = NewMethod(i) Return x End Function Private Shared Function NewMethod(i As Integer) As Integer Do Console.Write(i) i = i + 1 Continue Do 'Blah Loop Until i > 5 Return i End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestInvalidSelectionLeftOfAssignment() As Task Dim code = <text>Class A Protected x As Integer = 1 Public Sub New() [|x|] = 42 End Sub End Class</text> Dim expected = <text>Class A Protected x As Integer = 1 Public Sub New() NewMethod() End Sub Private Sub NewMethod() x = 42 End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestInvalidSelectionOfArrayLiterals() As Task Dim code = <text>Class A Public Sub Test() Dim numbers = New Integer() [|{1,2,3,4}|] End Sub End Class</text> Dim expected = <text>Class A Public Sub Test() Dim numbers = GetNumbers() End Sub Private Shared Function GetNumbers() As Integer() Return New Integer() {1, 2, 3, 4} End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestBugFix6313() As Task Dim code = <text>Imports System Class A Sub Test(b As Boolean) [|If b Then Return End If Console.WriteLine(1)|] End Sub End Class</text> Dim expected = <text>Imports System Class A Sub Test(b As Boolean) NewMethod(b) End Sub Private Shared Sub NewMethod(b As Boolean) If b Then Return End If Console.WriteLine(1) End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function BugFix6313_1() As Task Dim code = <text>Imports System Class A Sub Test(b As Boolean) [|If b Then Return End If|] Console.WriteLine(1) End Sub End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function BugFix6313_2() As Threading.Tasks.Task Dim code = <text>Imports System Class A Function Test(b As Boolean) as Integer [|If b Then Return 1 End If Console.WriteLine(1)|] End Function End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestBugFix6313_3() As Task Dim code = <text>Imports System Class A Sub Test() [|Dim b as Boolean = True If b Then Return End If Dim d As Action = Sub() If b Then Return End If Console.WriteLine(1) End Sub|] End Sub End Class</text> Dim expected = <text>Imports System Class A Sub Test() NewMethod() End Sub Private Shared Sub NewMethod() Dim b as Boolean = True If b Then Return End If Dim d As Action = Sub() If b Then Return End If Console.WriteLine(1) End Sub End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestBugFix6313_4() As Task Dim code = <text>Imports System Class A Sub Test() [|Dim d As Action = Sub() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub Dim d2 As Action = Sub() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub|] Console.WriteLine(1) End Sub End Class</text> Dim expected = <text>Imports System Class A Sub Test() NewMethod() Console.WriteLine(1) End Sub Private Shared Sub NewMethod() Dim d As Action = Sub() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub Dim d2 As Action = Sub() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestBugFix6313_5() As Task Dim code = <text>Imports System Class A Sub Test() Dim d As Action = Sub() [|Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1)|] End Sub End Sub End Class</text> Dim expected = <text>Imports System Class A Sub Test() Dim d As Action = Sub() NewMethod() End Sub End Sub Private Shared Sub NewMethod() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154"), WorkItem(541484, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541484")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function BugFix6313_6() As Task Dim code = <text>Imports System Class A Sub Test() Dim d As Action = Sub() [|Dim i As Integer = 1 If i > 10 Then Return End If|] Console.WriteLine(1) End Function End Sub End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <WorkItem(543670, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543670")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function AnonymousLambdaInVarDecl() As Task Dim code = <text>Imports System Module Program Sub Main [|Dim u = Function(x As Integer) 5|] u.Invoke(Nothing) End Sub End Module</text> Await ExpectExtractMethodToFailAsync(code) End Function <Fact, WorkItem(531451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531451"), Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestInvalidSelectionNonExecutableStatementSyntax_01() As Task Dim code = <text>Module Program Sub Main(args As String()) [|If True Then ElseIf True Then Return|] End Sub End Module</text> Dim expected = <text>Module Program Sub Main(args As String()) NewMethod() End Sub Private Sub NewMethod() If True Then ElseIf True Then Return End Sub End Module</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, WorkItem(547156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547156"), Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestInvalidSelectionNonExecutableStatementSyntax_02() As Task Dim code = <text>Module Program Sub Main() If True Then Dim x [|Else Console.WriteLine()|] End Sub End Module</text> Await ExpectExtractMethodToFailAsync(code) End Function <Fact, WorkItem(530625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530625"), Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestUnreachableEndInFunction() As Task Dim code = <text>Module Program Function Goo() As Integer If True Then [|Do : Loop|] ' Extract method Exit Function Else Return 0 End If End Function End Module</text> Dim expected = <text>Module Program Function Goo() As Integer If True Then NewMethod() ' Extract method Exit Function Else Return 0 End If End Function Private Sub NewMethod() Do : Loop End Sub End Module</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, WorkItem(578066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578066"), Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestExitAsSupportedExitPoints() As Task Dim code = <text>Imports System.Threading Imports System.Threading.Tasks Module Module1 Sub Main() End Sub Async Sub test() End Sub Async Function asyncfunc(x As Integer) As Task(Of Integer) [|Await Task.Delay(100) If x = 1 Then Return 1 Else GoTo goo End If Exit Function goo: Return 2L|] End Function End Module</text> Dim expected = <text>Imports System.Threading Imports System.Threading.Tasks Module Module1 Sub Main() End Sub Async Sub test() End Sub Async Function asyncfunc(x As Integer) As Task(Of Integer) Return Await NewMethod(x) End Function Private Async Function NewMethod(x As Integer) As Task(Of Integer) Await Task.Delay(100) If x = 1 Then Return 1 Else GoTo goo End If Exit Function goo: Return 2L End Function End Module</text> Await TestExtractMethodAsync(code, expected) 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. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ExtractMethod Partial Public Class ExtractMethodTests ''' <summary> ''' This contains tests for Extract Method components that depend on Control Flow Analysis API ''' (A) Selection Validator ''' (B) Analyzer ''' </summary> ''' <remarks></remarks> <[UseExportProvider]> Public Class FlowAnalysis <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestExitSub() As Threading.Tasks.Task Dim code = <text>Class Test Sub Test() [|Exit Sub|] End Sub End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestExitFunction() As Threading.Tasks.Task Dim code = <text>Class Test Function Test1() As Integer Console.Write(42) [|Test1 = 1 Console.Write(5) Exit Function|] End Function End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <WorkItem(540046, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540046")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestReturnStatement() As Task Dim code = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) [|Return x|] End Function End Class</text> Dim expected = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Return NewMethod(x) End Function Private Shared Function NewMethod(x As Integer) As Integer Return x End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestDoBranch() As Task Dim code = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer [|Do Console.Write(i) i = i + 1 Loop Until i > 5|] Return x End Function End Class</text> Dim expected = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer i = NewMethod(i) Return x End Function Private Shared Function NewMethod(i As Integer) As Integer Do Console.Write(i) i = i + 1 Loop Until i &gt; 5 Return i End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestDoBranchInvalidSelection() As Task Dim code = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer [|Do Console.Write(i)|] i = i + 1 Loop Until i > 5 Return x End Function End Class</text> Dim expected = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer i = NewMethod(i) Return x End Function Private Shared Function NewMethod(i As Integer) As Integer Do Console.Write(i) i = i + 1 Loop Until i &gt; 5 Return i End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestDoBranchWithContinue() As Task Dim code = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer [|Do Console.Write(i) i = i + 1 Continue Do 'Blah Loop Until i > 5|] Return x End Function End Class</text> Dim expected = <text>Class A Function Test1() As Integer Dim x As Integer = 5 Console.Write(x) Dim i As Integer i = NewMethod(i) Return x End Function Private Shared Function NewMethod(i As Integer) As Integer Do Console.Write(i) i = i + 1 Continue Do 'Blah Loop Until i > 5 Return i End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestInvalidSelectionLeftOfAssignment() As Task Dim code = <text>Class A Protected x As Integer = 1 Public Sub New() [|x|] = 42 End Sub End Class</text> Dim expected = <text>Class A Protected x As Integer = 1 Public Sub New() NewMethod() End Sub Private Sub NewMethod() x = 42 End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestInvalidSelectionOfArrayLiterals() As Task Dim code = <text>Class A Public Sub Test() Dim numbers = New Integer() [|{1,2,3,4}|] End Sub End Class</text> Dim expected = <text>Class A Public Sub Test() Dim numbers = GetNumbers() End Sub Private Shared Function GetNumbers() As Integer() Return New Integer() {1, 2, 3, 4} End Function End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestBugFix6313() As Task Dim code = <text>Imports System Class A Sub Test(b As Boolean) [|If b Then Return End If Console.WriteLine(1)|] End Sub End Class</text> Dim expected = <text>Imports System Class A Sub Test(b As Boolean) NewMethod(b) End Sub Private Shared Sub NewMethod(b As Boolean) If b Then Return End If Console.WriteLine(1) End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function BugFix6313_1() As Task Dim code = <text>Imports System Class A Sub Test(b As Boolean) [|If b Then Return End If|] Console.WriteLine(1) End Sub End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function BugFix6313_2() As Threading.Tasks.Task Dim code = <text>Imports System Class A Function Test(b As Boolean) as Integer [|If b Then Return 1 End If Console.WriteLine(1)|] End Function End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestBugFix6313_3() As Task Dim code = <text>Imports System Class A Sub Test() [|Dim b as Boolean = True If b Then Return End If Dim d As Action = Sub() If b Then Return End If Console.WriteLine(1) End Sub|] End Sub End Class</text> Dim expected = <text>Imports System Class A Sub Test() NewMethod() End Sub Private Shared Sub NewMethod() Dim b as Boolean = True If b Then Return End If Dim d As Action = Sub() If b Then Return End If Console.WriteLine(1) End Sub End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestBugFix6313_4() As Task Dim code = <text>Imports System Class A Sub Test() [|Dim d As Action = Sub() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub Dim d2 As Action = Sub() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub|] Console.WriteLine(1) End Sub End Class</text> Dim expected = <text>Imports System Class A Sub Test() NewMethod() Console.WriteLine(1) End Sub Private Shared Sub NewMethod() Dim d As Action = Sub() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub Dim d2 As Action = Sub() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestBugFix6313_5() As Task Dim code = <text>Imports System Class A Sub Test() Dim d As Action = Sub() [|Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1)|] End Sub End Sub End Class</text> Dim expected = <text>Imports System Class A Sub Test() Dim d As Action = Sub() NewMethod() End Sub End Sub Private Shared Sub NewMethod() Dim i As Integer = 1 If i > 10 Then Return End If Console.WriteLine(1) End Sub End Class</text> Await TestExtractMethodAsync(code, expected) End Function <WorkItem(540154, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540154"), WorkItem(541484, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541484")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function BugFix6313_6() As Task Dim code = <text>Imports System Class A Sub Test() Dim d As Action = Sub() [|Dim i As Integer = 1 If i > 10 Then Return End If|] Console.WriteLine(1) End Function End Sub End Class</text> Await ExpectExtractMethodToFailAsync(code) End Function <WorkItem(543670, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543670")> <Fact, Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function AnonymousLambdaInVarDecl() As Task Dim code = <text>Imports System Module Program Sub Main [|Dim u = Function(x As Integer) 5|] u.Invoke(Nothing) End Sub End Module</text> Await ExpectExtractMethodToFailAsync(code) End Function <Fact, WorkItem(531451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531451"), Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestInvalidSelectionNonExecutableStatementSyntax_01() As Task Dim code = <text>Module Program Sub Main(args As String()) [|If True Then ElseIf True Then Return|] End Sub End Module</text> Dim expected = <text>Module Program Sub Main(args As String()) NewMethod() End Sub Private Sub NewMethod() If True Then ElseIf True Then Return End Sub End Module</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, WorkItem(547156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547156"), Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestInvalidSelectionNonExecutableStatementSyntax_02() As Task Dim code = <text>Module Program Sub Main() If True Then Dim x [|Else Console.WriteLine()|] End Sub End Module</text> Await ExpectExtractMethodToFailAsync(code) End Function <Fact, WorkItem(530625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530625"), Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestUnreachableEndInFunction() As Task Dim code = <text>Module Program Function Goo() As Integer If True Then [|Do : Loop|] ' Extract method Exit Function Else Return 0 End If End Function End Module</text> Dim expected = <text>Module Program Function Goo() As Integer If True Then NewMethod() ' Extract method Exit Function Else Return 0 End If End Function Private Sub NewMethod() Do : Loop End Sub End Module</text> Await TestExtractMethodAsync(code, expected) End Function <Fact, WorkItem(578066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/578066"), Trait(Traits.Feature, Traits.Features.ExtractMethod)> Public Async Function TestExitAsSupportedExitPoints() As Task Dim code = <text>Imports System.Threading Imports System.Threading.Tasks Module Module1 Sub Main() End Sub Async Sub test() End Sub Async Function asyncfunc(x As Integer) As Task(Of Integer) [|Await Task.Delay(100) If x = 1 Then Return 1 Else GoTo goo End If Exit Function goo: Return 2L|] End Function End Module</text> Dim expected = <text>Imports System.Threading Imports System.Threading.Tasks Module Module1 Sub Main() End Sub Async Sub test() End Sub Async Function asyncfunc(x As Integer) As Task(Of Integer) Return Await NewMethod(x) End Function Private Async Function NewMethod(x As Integer) As Task(Of Integer) Await Task.Delay(100) If x = 1 Then Return 1 Else GoTo goo End If Exit Function goo: Return 2L End Function End Module</text> Await TestExtractMethodAsync(code, expected) End Function End Class End Class End Namespace
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/Core/Portable/AddImport/CodeActions/InstallWithPackageManagerCodeAction.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Packaging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private class InstallWithPackageManagerCodeAction : CodeAction { private readonly IPackageInstallerService _installerService; private readonly string _packageName; public InstallWithPackageManagerCodeAction( IPackageInstallerService installerService, string packageName) { _installerService = installerService; _packageName = packageName; } public override string Title => FeaturesResources.Install_with_package_manager; protected override Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken) { return Task.FromResult(SpecializedCollections.SingletonEnumerable<CodeActionOperation>( new InstallWithPackageManagerCodeActionOperation(_installerService, _packageName))); } private class InstallWithPackageManagerCodeActionOperation : CodeActionOperation { private readonly IPackageInstallerService _installerService; private readonly string _packageName; public InstallWithPackageManagerCodeActionOperation( IPackageInstallerService installerService, string packageName) { _installerService = installerService; _packageName = packageName; } public override string Title => FeaturesResources.Install_with_package_manager; public override void Apply(Workspace workspace, CancellationToken cancellationToken) => _installerService.ShowManagePackagesDialog(_packageName); } } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Packaging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private class InstallWithPackageManagerCodeAction : CodeAction { private readonly IPackageInstallerService _installerService; private readonly string _packageName; public InstallWithPackageManagerCodeAction( IPackageInstallerService installerService, string packageName) { _installerService = installerService; _packageName = packageName; } public override string Title => FeaturesResources.Install_with_package_manager; protected override Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(CancellationToken cancellationToken) { return Task.FromResult(SpecializedCollections.SingletonEnumerable<CodeActionOperation>( new InstallWithPackageManagerCodeActionOperation(_installerService, _packageName))); } private class InstallWithPackageManagerCodeActionOperation : CodeActionOperation { private readonly IPackageInstallerService _installerService; private readonly string _packageName; public InstallWithPackageManagerCodeActionOperation( IPackageInstallerService installerService, string packageName) { _installerService = installerService; _packageName = packageName; } public override string Title => FeaturesResources.Install_with_package_manager; public override void Apply(Workspace workspace, CancellationToken cancellationToken) => _installerService.ShowManagePackagesDialog(_packageName); } } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/Core/Portable/SolutionCrawler/IncrementalAnalyzerProviderBase.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; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal class IncrementalAnalyzerProviderBase : IIncrementalAnalyzerProvider { private readonly List<Lazy<IPerLanguageIncrementalAnalyzerProvider, PerLanguageIncrementalAnalyzerProviderMetadata>> _providers; protected IncrementalAnalyzerProviderBase( string name, IEnumerable<Lazy<IPerLanguageIncrementalAnalyzerProvider, PerLanguageIncrementalAnalyzerProviderMetadata>> providers) { _providers = providers.Where(p => p.Metadata.Name == name).ToList(); } public virtual IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) => new AggregateIncrementalAnalyzer(workspace, this, _providers); } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal class IncrementalAnalyzerProviderBase : IIncrementalAnalyzerProvider { private readonly List<Lazy<IPerLanguageIncrementalAnalyzerProvider, PerLanguageIncrementalAnalyzerProviderMetadata>> _providers; protected IncrementalAnalyzerProviderBase( string name, IEnumerable<Lazy<IPerLanguageIncrementalAnalyzerProvider, PerLanguageIncrementalAnalyzerProviderMetadata>> providers) { _providers = providers.Where(p => p.Metadata.Name == name).ToList(); } public virtual IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) => new AggregateIncrementalAnalyzer(workspace, this, _providers); } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Workspaces/Core/Portable/Shared/Extensions/ITypeParameterSymbolExtensions.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class ITypeParameterSymbolExtensions { public static INamedTypeSymbol? GetNamedTypeSymbolConstraint(this ITypeParameterSymbol typeParameter) => typeParameter.ConstraintTypes.Select(GetNamedTypeSymbol).WhereNotNull().FirstOrDefault(); private static INamedTypeSymbol? GetNamedTypeSymbol(ITypeSymbol type) { return type is INamedTypeSymbol ? (INamedTypeSymbol)type : type is ITypeParameterSymbol ? GetNamedTypeSymbolConstraint((ITypeParameterSymbol)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.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class ITypeParameterSymbolExtensions { public static INamedTypeSymbol? GetNamedTypeSymbolConstraint(this ITypeParameterSymbol typeParameter) => typeParameter.ConstraintTypes.Select(GetNamedTypeSymbol).WhereNotNull().FirstOrDefault(); private static INamedTypeSymbol? GetNamedTypeSymbol(ITypeSymbol type) { return type is INamedTypeSymbol ? (INamedTypeSymbol)type : type is ITypeParameterSymbol ? GetNamedTypeSymbolConstraint((ITypeParameterSymbol)type) : null; } } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Compilers/Core/Portable/Symbols/Attributes/CommonTypeWellKnownAttributeData.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.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from well-known custom attributes applied on a type. /// </summary> internal class CommonTypeWellKnownAttributeData : WellKnownAttributeData, ISecurityAttributeTarget { #region SpecialNameAttribute private bool _hasSpecialNameAttribute; public bool HasSpecialNameAttribute { get { VerifySealed(expected: true); return _hasSpecialNameAttribute; } set { VerifySealed(expected: false); _hasSpecialNameAttribute = value; SetDataStored(); } } #endregion #region SerializableAttribute private bool _hasSerializableAttribute; public bool HasSerializableAttribute { get { VerifySealed(expected: true); return _hasSerializableAttribute; } set { VerifySealed(expected: false); _hasSerializableAttribute = value; SetDataStored(); } } #endregion #region DefaultMemberAttribute private bool _hasDefaultMemberAttribute; public bool HasDefaultMemberAttribute { get { VerifySealed(expected: true); return _hasDefaultMemberAttribute; } set { VerifySealed(expected: false); _hasDefaultMemberAttribute = value; SetDataStored(); } } #endregion #region SuppressUnmanagedCodeSecurityAttribute private bool _hasSuppressUnmanagedCodeSecurityAttribute; public bool HasSuppressUnmanagedCodeSecurityAttribute { get { VerifySealed(expected: true); return _hasSuppressUnmanagedCodeSecurityAttribute; } set { VerifySealed(expected: false); _hasSuppressUnmanagedCodeSecurityAttribute = value; SetDataStored(); } } #endregion #region Security Attributes private SecurityWellKnownAttributeData _lazySecurityAttributeData; SecurityWellKnownAttributeData ISecurityAttributeTarget.GetOrCreateData() { VerifySealed(expected: false); if (_lazySecurityAttributeData == null) { _lazySecurityAttributeData = new SecurityWellKnownAttributeData(); SetDataStored(); } return _lazySecurityAttributeData; } internal bool HasDeclarativeSecurity { get { VerifySealed(expected: true); return _lazySecurityAttributeData != null || this.HasSuppressUnmanagedCodeSecurityAttribute; } } /// <summary> /// Returns data decoded from security attributes or null if there are no security attributes. /// </summary> public SecurityWellKnownAttributeData SecurityInformation { get { VerifySealed(expected: true); return _lazySecurityAttributeData; } } #endregion #region WindowsRuntimeImportAttribute private bool _hasWindowsRuntimeImportAttribute; public bool HasWindowsRuntimeImportAttribute { get { VerifySealed(expected: true); return _hasWindowsRuntimeImportAttribute; } set { VerifySealed(expected: false); _hasWindowsRuntimeImportAttribute = value; SetDataStored(); } } #endregion #region GuidAttribute // Decoded guid string from GuidAttribute private string _guidString; public string GuidString { get { VerifySealed(expected: true); return _guidString; } set { VerifySealed(expected: false); Debug.Assert(value != null); _guidString = value; SetDataStored(); } } #endregion #region StructLayoutAttribute private TypeLayout _layout; private CharSet _charSet; // StructLayoutAttribute public void SetStructLayout(TypeLayout layout, CharSet charSet) { VerifySealed(expected: false); Debug.Assert(charSet == CharSet.Ansi || charSet == CharSet.Unicode || charSet == Cci.Constants.CharSet_Auto); _layout = layout; _charSet = charSet; SetDataStored(); } public bool HasStructLayoutAttribute { get { VerifySealed(expected: true); // charSet is non-zero iff it was set by SetStructLayout called from StructLayoutAttribute decoder return _charSet != 0; } } public TypeLayout Layout { get { VerifySealed(expected: true); Debug.Assert(HasStructLayoutAttribute); return _layout; } } public CharSet MarshallingCharSet { get { VerifySealed(expected: true); Debug.Assert(HasStructLayoutAttribute); return _charSet; } } #endregion #region SecurityCriticalAttribute and SecuritySafeCriticalAttribute private bool _hasSecurityCriticalAttributes; public bool HasSecurityCriticalAttributes { get { VerifySealed(expected: true); return _hasSecurityCriticalAttributes; } set { VerifySealed(expected: false); _hasSecurityCriticalAttributes = value; SetDataStored(); } } #endregion #region ExcludeFromCodeCoverageAttribute private bool _hasExcludeFromCodeCoverageAttribute; public bool HasExcludeFromCodeCoverageAttribute { get { VerifySealed(expected: true); return _hasExcludeFromCodeCoverageAttribute; } set { VerifySealed(expected: false); _hasExcludeFromCodeCoverageAttribute = value; SetDataStored(); } } #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.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Information decoded from well-known custom attributes applied on a type. /// </summary> internal class CommonTypeWellKnownAttributeData : WellKnownAttributeData, ISecurityAttributeTarget { #region SpecialNameAttribute private bool _hasSpecialNameAttribute; public bool HasSpecialNameAttribute { get { VerifySealed(expected: true); return _hasSpecialNameAttribute; } set { VerifySealed(expected: false); _hasSpecialNameAttribute = value; SetDataStored(); } } #endregion #region SerializableAttribute private bool _hasSerializableAttribute; public bool HasSerializableAttribute { get { VerifySealed(expected: true); return _hasSerializableAttribute; } set { VerifySealed(expected: false); _hasSerializableAttribute = value; SetDataStored(); } } #endregion #region DefaultMemberAttribute private bool _hasDefaultMemberAttribute; public bool HasDefaultMemberAttribute { get { VerifySealed(expected: true); return _hasDefaultMemberAttribute; } set { VerifySealed(expected: false); _hasDefaultMemberAttribute = value; SetDataStored(); } } #endregion #region SuppressUnmanagedCodeSecurityAttribute private bool _hasSuppressUnmanagedCodeSecurityAttribute; public bool HasSuppressUnmanagedCodeSecurityAttribute { get { VerifySealed(expected: true); return _hasSuppressUnmanagedCodeSecurityAttribute; } set { VerifySealed(expected: false); _hasSuppressUnmanagedCodeSecurityAttribute = value; SetDataStored(); } } #endregion #region Security Attributes private SecurityWellKnownAttributeData _lazySecurityAttributeData; SecurityWellKnownAttributeData ISecurityAttributeTarget.GetOrCreateData() { VerifySealed(expected: false); if (_lazySecurityAttributeData == null) { _lazySecurityAttributeData = new SecurityWellKnownAttributeData(); SetDataStored(); } return _lazySecurityAttributeData; } internal bool HasDeclarativeSecurity { get { VerifySealed(expected: true); return _lazySecurityAttributeData != null || this.HasSuppressUnmanagedCodeSecurityAttribute; } } /// <summary> /// Returns data decoded from security attributes or null if there are no security attributes. /// </summary> public SecurityWellKnownAttributeData SecurityInformation { get { VerifySealed(expected: true); return _lazySecurityAttributeData; } } #endregion #region WindowsRuntimeImportAttribute private bool _hasWindowsRuntimeImportAttribute; public bool HasWindowsRuntimeImportAttribute { get { VerifySealed(expected: true); return _hasWindowsRuntimeImportAttribute; } set { VerifySealed(expected: false); _hasWindowsRuntimeImportAttribute = value; SetDataStored(); } } #endregion #region GuidAttribute // Decoded guid string from GuidAttribute private string _guidString; public string GuidString { get { VerifySealed(expected: true); return _guidString; } set { VerifySealed(expected: false); Debug.Assert(value != null); _guidString = value; SetDataStored(); } } #endregion #region StructLayoutAttribute private TypeLayout _layout; private CharSet _charSet; // StructLayoutAttribute public void SetStructLayout(TypeLayout layout, CharSet charSet) { VerifySealed(expected: false); Debug.Assert(charSet == CharSet.Ansi || charSet == CharSet.Unicode || charSet == Cci.Constants.CharSet_Auto); _layout = layout; _charSet = charSet; SetDataStored(); } public bool HasStructLayoutAttribute { get { VerifySealed(expected: true); // charSet is non-zero iff it was set by SetStructLayout called from StructLayoutAttribute decoder return _charSet != 0; } } public TypeLayout Layout { get { VerifySealed(expected: true); Debug.Assert(HasStructLayoutAttribute); return _layout; } } public CharSet MarshallingCharSet { get { VerifySealed(expected: true); Debug.Assert(HasStructLayoutAttribute); return _charSet; } } #endregion #region SecurityCriticalAttribute and SecuritySafeCriticalAttribute private bool _hasSecurityCriticalAttributes; public bool HasSecurityCriticalAttributes { get { VerifySealed(expected: true); return _hasSecurityCriticalAttributes; } set { VerifySealed(expected: false); _hasSecurityCriticalAttributes = value; SetDataStored(); } } #endregion #region ExcludeFromCodeCoverageAttribute private bool _hasExcludeFromCodeCoverageAttribute; public bool HasExcludeFromCodeCoverageAttribute { get { VerifySealed(expected: true); return _hasExcludeFromCodeCoverageAttribute; } set { VerifySealed(expected: false); _hasExcludeFromCodeCoverageAttribute = value; SetDataStored(); } } #endregion } }
-1
dotnet/roslyn
55,737
Inline Hints: Added double click on hint to insert text
Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
akhera99
2021-08-19T22:48:17Z
2022-01-07T17:06:38Z
ffde321ee629f942e346318503766ea367393533
13a91f02e48d5e042c40edbefd2f95daf82f95c1
Inline Hints: Added double click on hint to insert text. Fixes: #55519 Added functionality in for parameter and type hints to be double-clicked and inserted into the text. Type hints replace var
./src/Features/Core/Portable/CodeLens/ICodeLensReferencesService.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; namespace Microsoft.CodeAnalysis.CodeLens { internal interface ICodeLensReferencesService : IWorkspaceService { ValueTask<VersionStamp> GetProjectCodeLensVersionAsync(Solution solution, ProjectId projectId, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns the number of locations where the located node is referenced. /// <para> /// Optionally, the service supports capping the reference count to a value specified by <paramref name="maxSearchResults"/> /// if <paramref name="maxSearchResults"/> is greater than 0. /// </para> /// </summary> Task<ReferenceCount?> GetReferenceCountAsync(Solution solution, DocumentId documentId, SyntaxNode? syntaxNode, int maxSearchResults, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns a collection of locations where the located node is referenced. /// </summary> Task<ImmutableArray<ReferenceLocationDescriptor>?> FindReferenceLocationsAsync(Solution solution, DocumentId documentId, SyntaxNode? syntaxNode, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns a collection of locations of methods that refer to the located node. /// </summary> Task<ImmutableArray<ReferenceMethodDescriptor>?> FindReferenceMethodsAsync(Solution solution, DocumentId documentId, SyntaxNode? syntaxNode, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns the fully qualified name of the located node's declaration. /// </summary> Task<string?> GetFullyQualifiedNameAsync(Solution solution, DocumentId documentId, SyntaxNode? syntaxNode, 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; namespace Microsoft.CodeAnalysis.CodeLens { internal interface ICodeLensReferencesService : IWorkspaceService { ValueTask<VersionStamp> GetProjectCodeLensVersionAsync(Solution solution, ProjectId projectId, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns the number of locations where the located node is referenced. /// <para> /// Optionally, the service supports capping the reference count to a value specified by <paramref name="maxSearchResults"/> /// if <paramref name="maxSearchResults"/> is greater than 0. /// </para> /// </summary> Task<ReferenceCount?> GetReferenceCountAsync(Solution solution, DocumentId documentId, SyntaxNode? syntaxNode, int maxSearchResults, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns a collection of locations where the located node is referenced. /// </summary> Task<ImmutableArray<ReferenceLocationDescriptor>?> FindReferenceLocationsAsync(Solution solution, DocumentId documentId, SyntaxNode? syntaxNode, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns a collection of locations of methods that refer to the located node. /// </summary> Task<ImmutableArray<ReferenceMethodDescriptor>?> FindReferenceMethodsAsync(Solution solution, DocumentId documentId, SyntaxNode? syntaxNode, CancellationToken cancellationToken); /// <summary> /// Given a document and syntax node, returns the fully qualified name of the located node's declaration. /// </summary> Task<string?> GetFullyQualifiedNameAsync(Solution solution, DocumentId documentId, SyntaxNode? syntaxNode, CancellationToken cancellationToken); } }
-1