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,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Semantic/Semantics/StackAllocInitializerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.StackAllocInitializer)] public class StackAllocInitializerTests : CompilingTestBase { [Fact, WorkItem(33945, "https://github.com/dotnet/roslyn/issues/33945")] public void RestrictedTypesAllowedInStackalloc() { var comp = CreateCompilationWithMscorlibAndSpan(@" public ref struct RefS { } public ref struct RefG<T> { public T field; } class C { unsafe void M() { var x1 = stackalloc RefS[10]; var x2 = stackalloc RefG<string>[10]; var x3 = stackalloc RefG<int>[10]; var x4 = stackalloc System.TypedReference[10]; // Note: this should be disallowed by adding a dummy field to the ref assembly for TypedReference var x5 = stackalloc System.ArgIterator[10]; var x6 = stackalloc System.RuntimeArgumentHandle[10]; var y1 = new RefS[10]; var y2 = new RefG<string>[10]; var y3 = new RefG<int>[10]; var y4 = new System.TypedReference[10]; var y5 = new System.ArgIterator[10]; var y6 = new System.RuntimeArgumentHandle[10]; RefS[] z1 = null; RefG<string>[] z2 = null; RefG<int>[] z3 = null; System.TypedReference[] z4 = null; System.ArgIterator[] z5 = null; System.RuntimeArgumentHandle[] z6 = null; _ = z1; _ = z2; _ = z3; _ = z4; _ = z5; _ = z6; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (10,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('RefG<string>') // var x2 = stackalloc RefG<string>[10]; Diagnostic(ErrorCode.ERR_ManagedAddr, "RefG<string>").WithArguments("RefG<string>").WithLocation(10, 29), // (16,22): error CS0611: Array elements cannot be of type 'RefS' // var y1 = new RefS[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefS").WithArguments("RefS").WithLocation(16, 22), // (17,22): error CS0611: Array elements cannot be of type 'RefG<string>' // var y2 = new RefG<string>[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<string>").WithArguments("RefG<string>").WithLocation(17, 22), // (18,22): error CS0611: Array elements cannot be of type 'RefG<int>' // var y3 = new RefG<int>[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<int>").WithArguments("RefG<int>").WithLocation(18, 22), // (19,22): error CS0611: Array elements cannot be of type 'TypedReference' // var y4 = new System.TypedReference[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(19, 22), // (20,22): error CS0611: Array elements cannot be of type 'ArgIterator' // var y5 = new System.ArgIterator[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(20, 22), // (21,22): error CS0611: Array elements cannot be of type 'RuntimeArgumentHandle' // var y6 = new System.RuntimeArgumentHandle[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(21, 22), // (23,9): error CS0611: Array elements cannot be of type 'RefS' // RefS[] z1 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefS").WithArguments("RefS").WithLocation(23, 9), // (24,9): error CS0611: Array elements cannot be of type 'RefG<string>' // RefG<string>[] z2 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<string>").WithArguments("RefG<string>").WithLocation(24, 9), // (25,9): error CS0611: Array elements cannot be of type 'RefG<int>' // RefG<int>[] z3 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<int>").WithArguments("RefG<int>").WithLocation(25, 9), // (26,9): error CS0611: Array elements cannot be of type 'TypedReference' // System.TypedReference[] z4 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(26, 9), // (27,9): error CS0611: Array elements cannot be of type 'ArgIterator' // System.ArgIterator[] z5 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(27, 9), // (28,9): error CS0611: Array elements cannot be of type 'RuntimeArgumentHandle' // System.RuntimeArgumentHandle[] z6 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(28, 9) ); } [Fact] public void NoBestType_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { struct A {} struct B {} void Method(dynamic d, RefStruct r) { var p0 = stackalloc[] { new A(), new B() }; var p1 = stackalloc[] { }; var p2 = stackalloc[] { VoidMethod() }; var p3 = stackalloc[] { null }; var p4 = stackalloc[] { (1, null) }; var p5 = stackalloc[] { () => { } }; var p6 = stackalloc[] { new {} , new { i = 0 } }; var p7 = stackalloc[] { d }; var p8 = stackalloc[] { _ }; } public void VoidMethod() {} } namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 a, T2 b) => throw null; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // void Method(dynamic d, RefStruct r) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "RefStruct").WithArguments("RefStruct").WithLocation(7, 28), // (9,18): error CS0826: No best type found for implicitly-typed array // var p0 = stackalloc[] { new A(), new B() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new A(), new B() }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var p1 = stackalloc[] { }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { }").WithLocation(10, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var p2 = stackalloc[] { VoidMethod() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { VoidMethod() }").WithLocation(11, 18), // (12,18): error CS0826: No best type found for implicitly-typed array // var p3 = stackalloc[] { null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { null }").WithLocation(12, 18), // (13,18): error CS0826: No best type found for implicitly-typed array // var p4 = stackalloc[] { (1, null) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { (1, null) }").WithLocation(13, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var p5 = stackalloc[] { () => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { () => { } }").WithLocation(14, 18), // (15,18): error CS0826: No best type found for implicitly-typed array // var p6 = stackalloc[] { new {} , new { i = 0 } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new {} , new { i = 0 } }").WithLocation(15, 18), // (16,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var p7 = stackalloc[] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { d }").WithArguments("dynamic").WithLocation(16, 18), // (17,33): error CS0103: The name '_' does not exist in the current context // var p8 = stackalloc[] { _ }; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(17, 33) ); } [Fact] public void NoBestType_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { struct A {} struct B {} void Method(dynamic d, bool c) { var p0 = c ? default : stackalloc[] { new A(), new B() }; var p1 = c ? default : stackalloc[] { }; var p2 = c ? default : stackalloc[] { VoidMethod() }; var p3 = c ? default : stackalloc[] { null }; var p4 = c ? default : stackalloc[] { (1, null) }; var p5 = c ? default : stackalloc[] { () => { } }; var p6 = c ? default : stackalloc[] { new {} , new { i = 0 } }; var p7 = c ? default : stackalloc[] { d }; var p8 = c ? default : stackalloc[] { _ }; } public void VoidMethod() {} } namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 a, T2 b) => throw null; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (9,32): error CS0826: No best type found for implicitly-typed array // var p0 = c ? default : stackalloc[] { new A(), new B() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new A(), new B() }").WithLocation(9, 32), // (10,32): error CS0826: No best type found for implicitly-typed array // var p1 = c ? default : stackalloc[] { }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { }").WithLocation(10, 32), // (11,32): error CS0826: No best type found for implicitly-typed array // var p2 = c ? default : stackalloc[] { VoidMethod() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { VoidMethod() }").WithLocation(11, 32), // (12,32): error CS0826: No best type found for implicitly-typed array // var p3 = c ? default : stackalloc[] { null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { null }").WithLocation(12, 32), // (13,32): error CS0826: No best type found for implicitly-typed array // var p4 = c ? default : stackalloc[] { (1, null) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { (1, null) }").WithLocation(13, 32), // (14,32): error CS0826: No best type found for implicitly-typed array // var p5 = c ? default : stackalloc[] { () => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { () => { } }").WithLocation(14, 32), // (15,32): error CS0826: No best type found for implicitly-typed array // var p6 = c ? default : stackalloc[] { new {} , new { i = 0 } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new {} , new { i = 0 } }").WithLocation(15, 32), // (16,32): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var p7 = c ? default : stackalloc[] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { d }").WithArguments("dynamic").WithLocation(16, 32), // (17,47): error CS0103: The name '_' does not exist in the current context // var p8 = c ? default : stackalloc[] { _ }; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(17, 47) ); } [Fact] public void InitializeWithSelf_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void Method1() { var obj1 = stackalloc int[1] { obj1 }; var obj2 = stackalloc int[ ] { obj2 }; var obj3 = stackalloc [ ] { obj3 }; } void Method2() { var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,40): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[1] { obj1 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(6, 40), // (7,40): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(7, 40), // (8,40): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(8, 40), // (13,40): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 40), // (13,50): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 50), // (14,40): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 40), // (14,50): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 50), // (15,40): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 40), // (15,50): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 50) ); } [Fact] public void InitializeWithSelf_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void Method1(bool c) { var obj1 = c ? default : stackalloc int[1] { obj1 }; var obj2 = c ? default : stackalloc int[ ] { obj2 }; var obj3 = c ? default : stackalloc [ ] { obj3 }; } void Method2(bool c) { var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,54): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[1] { obj1 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(6, 54), // (7,54): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(7, 54), // (8,54): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(8, 54), // (13,54): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 54), // (13,64): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 64), // (14,54): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 54), // (14,64): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 64), // (15,54): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 54), // (15,64): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 64) ); } [Fact] public void BadBestType_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { ref struct S {} void Method1(S s) { var obj1 = stackalloc[] { """" }; var obj2 = stackalloc[] { new {} }; var obj3 = stackalloc[] { s }; // OK } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // var obj1 = stackalloc[] { "" }; Diagnostic(ErrorCode.ERR_ManagedAddr, @"stackalloc[] { """" }").WithArguments("string").WithLocation(7, 20), // (8,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>') // var obj2 = stackalloc[] { new {} }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { new {} }").WithArguments("<empty anonymous type>").WithLocation(8, 20) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.String*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.String*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.String", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.String", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("<empty anonymous type>*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("<empty anonymous type>..ctor()", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("Test.S*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("Test.S*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("Test.S s", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.Type.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); } [Fact] public void BadBestType_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { ref struct S {} void Method1(S s, bool c) { var obj1 = c ? default : stackalloc[] { """" }; var obj2 = c ? default : stackalloc[] { new {} }; var obj3 = c ? default : stackalloc[] { s }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,34): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // var obj1 = c ? default : stackalloc[] { "" }; Diagnostic(ErrorCode.ERR_ManagedAddr, @"stackalloc[] { """" }").WithArguments("string").WithLocation(7, 34), // (8,34): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>') // var obj2 = c ? default : stackalloc[] { new {} }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { new {} }").WithArguments("<empty anonymous type>").WithLocation(8, 34), // (9,34): error CS0306: The type 'Test.S' may not be used as a type argument // var obj3 = c ? default : stackalloc[] { s }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "stackalloc[] { s }").WithArguments("Test.S").WithLocation(9, 34) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.String>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.String>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.String", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.String", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<<empty anonymous type>>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<<empty anonymous type>>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("<empty anonymous type>..ctor()", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<Test.S>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<Test.S>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("Test.S s", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.Type.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); } [Fact] public void TestFor_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { static void Method1() { int i = 0; for (var p = stackalloc int[3] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method2() { int i = 0; for (var p = stackalloc int[ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method3() { int i = 0; for (var p = stackalloc [ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } public static void Main() { Method1(); Method2(); Method3(); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "123123123", verify: Verification.Fails); } [Fact] public void TestFor_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { static void Method1() { int i = 0; for (Span<int> p = stackalloc int[3] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method2() { int i = 0; for (Span<int> p = stackalloc int[ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method3() { int i = 0; for (Span<int> p = stackalloc [ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } public static void Main() { Method1(); Method2(); Method3(); } }", TestOptions.DebugExe); comp.VerifyDiagnostics(); } [Fact] public void TestForTernary() { var comp = CreateCompilationWithMscorlibAndSpan(@" class Test { static void Method1(bool b) { for (var p = b ? stackalloc int[3] { 1, 2, 3 } : default; false;) {} for (var p = b ? stackalloc int[ ] { 1, 2, 3 } : default; false;) {} for (var p = b ? stackalloc [ ] { 1, 2, 3 } : default; false;) {} } }", TestOptions.ReleaseDll); comp.VerifyDiagnostics(); } [Fact] public void TestLock() { var source = @" class Test { static void Method1() { lock (stackalloc int[3] { 1, 2, 3 }) {} lock (stackalloc int[ ] { 1, 2, 3 }) {} lock (stackalloc [ ] { 1, 2, 3 }) {} } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (6,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 15), // (6,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int*").WithLocation(6, 15), // (7,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 15), // (7,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[ ] { 1, 2, 3 }").WithArguments("int*").WithLocation(7, 15), // (8,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 15), // (8,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc [ ] { 1, 2, 3 }").WithArguments("int*").WithLocation(8, 15) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (6,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(6, 15), // (7,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 15), // (8,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 15) ); } [Fact] public void TestSelect() { var source = @" using System.Linq; class Test { static void Method1(int[] array) { var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (7,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 44), // (8,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 44), // (9,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 44) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (7,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc int[3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 37), // (8,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc int[ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 37), // (9,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(9, 37) ); } [Fact] public void TestLet() { var source = @" using System.Linq; class Test { static void Method1(int[] array) { var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (7,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 45), // (8,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 45), // (9,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 45) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (7,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(7, 75), // (8,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(8, 75), // (9,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(9, 75) ); } [Fact] public void TestAwait_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System.Threading.Tasks; unsafe class Test { async void M() { var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,32): error CS4004: Cannot await in an unsafe context // var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.FromResult(1)").WithLocation(7, 32), // (7,60): error CS4004: Cannot await in an unsafe context // var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.FromResult(2)").WithLocation(7, 60) ); } [Fact] public void TestAwait_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; using System.Threading.Tasks; class Test { async void M() { Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (8,38): error CS0150: A constant value is expected // Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_ConstantExpected, "await Task.FromResult(1)").WithLocation(8, 38), // (8,9): error CS4012: Parameters or locals of type 'Span<int>' cannot be declared in async methods or async lambda expressions. // Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "Span<int>").WithArguments("System.Span<int>").WithLocation(8, 9) ); } [Fact] public void TestSelfInSize() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void M() { var x = stackalloc int[x] { }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,32): error CS0841: Cannot use local variable 'x' before it is declared // var x = stackalloc int[x] { }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 32) ); } [Fact] public void WrongLength() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[10] { }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,20): error CS0847: An array initializer of length '10' is expected // var obj1 = stackalloc int[10] { }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc int[10] { }").WithArguments("10").WithLocation(6, 20) ); } [Fact] public void NoInit() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[]; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,34): error CS1586: Array creation must have array size or array initializer // var obj1 = stackalloc int[]; Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 34) ); } [Fact] public void NestedInit() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[1] { { 42 } }; var obj2 = stackalloc int[ ] { { 42 } }; var obj3 = stackalloc [ ] { { 42 } }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj1 = stackalloc int[1] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(6, 40), // (7,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj2 = stackalloc int[ ] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(7, 40), // (8,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj3 = stackalloc [ ] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(8, 40) ); } [Fact] public void AsStatement() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { stackalloc[] {1}; stackalloc int[] {1}; stackalloc int[1] {1}; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc[] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc[] {1}").WithLocation(6, 9), // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc int[] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc int[] {1}").WithLocation(7, 9), // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc int[1] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc int[1] {1}").WithLocation(8, 9) ); } [Fact] public void BadRank() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[][] { 1 }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]') // var obj1 = stackalloc int[][] { 1 }; Diagnostic(ErrorCode.ERR_ManagedAddr, "int").WithArguments("int[]").WithLocation(6, 31), // (6,31): error CS1575: A stackalloc expression requires [] after type // var obj1 = stackalloc int[][] { 1 }; Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[][]").WithLocation(6, 31) ); } [Fact] public void BadDimension() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[,] { 1 }; var obj2 = stackalloc [,] { 1 }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,35): error CS8381: "Invalid rank specifier: expected ']' // var obj2 = stackalloc [,] { 1 }; Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(7, 35), // (6,31): error CS1575: A stackalloc expression requires [] after type // var obj1 = stackalloc int[,] { 1 }; Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[,]").WithLocation(6, 31) ); } [Fact] public void TestFlowPass1() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public static void Main() { int i, j, k; var obj1 = stackalloc int [1] { i = 1 }; var obj2 = stackalloc int [ ] { j = 2 }; var obj3 = stackalloc [ ] { k = 3 }; Console.Write(i); Console.Write(j); Console.Write(k); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestFlowPass2() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public static void Main() { int i, j, k; var obj1 = stackalloc int [1] { i }; var obj2 = stackalloc int [ ] { j }; var obj3 = stackalloc [ ] { k }; } }", TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,41): error CS0165: Use of unassigned local variable 'i' // var obj1 = stackalloc int [1] { i }; Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(7, 41), // (8,41): error CS0165: Use of unassigned local variable 'j' // var obj2 = stackalloc int [ ] { j }; Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j").WithLocation(8, 41), // (9,41): error CS0165: Use of unassigned local variable 'k' // var obj3 = stackalloc [ ] { k }; Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k").WithLocation(9, 41) ); } [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Implicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { Test obj1 = stackalloc int[3] { 1, 2, 3 }; var obj2 = stackalloc int[3] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[3] { 1, 2, 3 }; int* obj4 = stackalloc int[3] { 1, 2, 3 }; double* obj5 = stackalloc int[3] { 1, 2, 3 }; } public void Method2() { Test obj1 = stackalloc int[] { 1, 2, 3 }; var obj2 = stackalloc int[] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[] { 1, 2, 3 }; int* obj4 = stackalloc int[] { 1, 2, 3 }; double* obj5 = stackalloc int[] { 1, 2, 3 }; } public void Method3() { Test obj1 = stackalloc[] { 1, 2, 3 }; var obj2 = stackalloc[] { 1, 2, 3 }; Span<int> obj3 = stackalloc[] { 1, 2, 3 }; int* obj4 = stackalloc[] { 1, 2, 3 }; double* obj5 = stackalloc[] { 1, 2, 3 }; } public static implicit operator Test(int* value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(11, 24), // (20,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(20, 24), // (29,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(29, 24) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(15, variables.Count()); for (int i = 0; i < 15; i += 5) { var obj1 = variables.ElementAt(i); Assert.Equal("obj1", obj1.Identifier.Text); var obj1Value = model.GetSemanticInfoSummary(obj1.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj1Value.Type).PointedAtType.SpecialType); Assert.Equal("Test", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.ImplicitUserDefined, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(i + 1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(i + 2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(i + 3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(i + 4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } } [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Explicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { Test obj1 = (Test)stackalloc int[3] { 1, 2, 3 }; var obj2 = stackalloc int[3] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[3] { 1, 2, 3 }; int* obj4 = stackalloc int[3] { 1, 2, 3 }; double* obj5 = stackalloc int[3] { 1, 2, 3 }; } public void Method2() { Test obj1 = (Test)stackalloc int[] { 1, 2, 3 }; var obj2 = stackalloc int[] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[] { 1, 2, 3 }; int* obj4 = stackalloc int[] { 1, 2, 3 }; double* obj5 = stackalloc int[] { 1, 2, 3 }; } public void Method3() { Test obj1 = (Test)stackalloc [] { 1, 2, 3 }; var obj2 = stackalloc[] { 1, 2, 3 }; Span<int> obj3 = stackalloc [] { 1, 2, 3 }; int* obj4 = stackalloc[] { 1, 2, 3 }; double* obj5 = stackalloc[] { 1, 2, 3 }; } public static explicit operator Test(Span<int> value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(11, 24), // (20,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(20, 24), // (29,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(29, 24) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(15, variables.Count()); for (int i = 0; i < 15; i += 5) { var obj1 = variables.ElementAt(i); Assert.Equal("obj1", obj1.Identifier.Text); Assert.Equal(SyntaxKind.CastExpression, obj1.Initializer.Value.Kind()); var obj1Value = model.GetSemanticInfoSummary(((CastExpressionSyntax)obj1.Initializer.Value).Expression); Assert.Equal("Span", obj1Value.Type.Name); Assert.Equal("Span", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(i + 1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(i + 2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(i + 3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(i + 4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } } [Fact] public void ConversionError() { CreateCompilationWithMscorlibAndSpan(@" class Test { void Method1() { double x = stackalloc int[3] { 1, 2, 3 }; // implicit short y = (short)stackalloc int[3] { 1, 2, 3 }; // explicit } void Method2() { double x = stackalloc int[] { 1, 2, 3 }; // implicit short y = (short)stackalloc int[] { 1, 2, 3 }; // explicit } void Method3() { double x = stackalloc[] { 1, 2, 3 }; // implicit short y = (short)stackalloc[] { 1, 2, 3 }; // explicit } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc int[3] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(6, 20), // (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc int[3] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(7, 19), // (12,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc int[] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(12, 20), // (13,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc int[] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(13, 19), // (18,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc[] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(18, 20), // (19,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc[] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc[] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(19, 19) ); } [Fact] public void MissingSpanType() { CreateCompilation(@" class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; } }").VerifyDiagnostics( // (6,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(6, 9), // (6,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(6, 24), // (7,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(7, 9), // (7,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(7, 24), // (8,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(8, 9), // (8,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(8, 24) ); } [Fact] public void MissingSpanConstructor() { CreateCompilation(@" namespace System { ref struct Span<T> { } class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; } } }").VerifyEmitDiagnostics( // (11,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(11, 28), // (12,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(12, 28), // (13,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(13, 28) ); } [Fact] public void ConditionalExpressionOnSpan_BothStackallocSpans() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3 } : stackalloc int [3] { 1, 2, 3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : stackalloc int [ ] { 1, 2, 3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : stackalloc [ ] { 1, 2, 3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_Convertible() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3 } : (Span<int>)stackalloc int [3] { 1, 2, 3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : (Span<int>)stackalloc int [ ] { 1, 2, 3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : (Span<int>)stackalloc [ ] { 1, 2, 3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_NoCast() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3, } : (Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3, } : (Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3, } : (Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x1 = true ? stackalloc int [3] { 1, 2, 3, } : (Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(7, 59), // (8,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x2 = true ? stackalloc int [ ] { 1, 2, 3, } : (Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(8, 59), // (9,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x3 = true ? stackalloc [ ] { 1, 2, 3, } : (Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(9, 59) ); } [Fact] public void ConditionalExpressionOnSpan_CompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a1; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a2; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a3; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_IncompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<short> a = stackalloc short [10]; var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [3] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(8, 18), // (9,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [ ] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(9, 18), // (10,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc [ ] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(10, 18) ); } [Fact] public void ConditionalExpressionOnSpan_Nested() { CreateCompilationWithMscorlibAndSpan(@" class Test { bool N() => true; void M() { var x = N() ? N() ? stackalloc int[1] { 42 } : stackalloc int[ ] { 42 } : N() ? stackalloc[] { 42 } : N() ? stackalloc int[2] : stackalloc int[3]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void BooleanOperatorOnSpan_NoTargetTyping() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { if (stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }) { } if (stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }) { } if (stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }) { } } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(6, 13), // (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(7, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(8, 13) ); } [Fact] public void StackAllocInitializerSyntaxProducesErrorsOnEarlierVersions() { var parseOptions = new CSharpParseOptions().WithLanguageVersion(LanguageVersion.CSharp7); CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> x1 = stackalloc int [3] { 1, 2, 3 }; Span<int> x2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> x3 = stackalloc [ ] { 1, 2, 3 }; } }", options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions).VerifyDiagnostics( // (7,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(7, 24), // (8,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(8, 24), // (9,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(9, 24) ); } [Fact] public void StackAllocSyntaxProducesUnsafeErrorInSafeCode() { CreateCompilation(@" class Test { void M() { var x1 = stackalloc int [3] { 1, 2, 3 }; var x2 = stackalloc int [ ] { 1, 2, 3 }; var x3 = stackalloc [ ] { 1, 2, 3 }; } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int [3] { 1, 2, 3 }").WithLocation(6, 18), // (7,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(7, 18), // (8,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc [ ] { 1, 2, 3 }").WithLocation(8, 18) ); } [Fact] public void StackAllocInUsing1() { var test = @" public class Test { unsafe public static void Main() { using (var v1 = stackalloc int [3] { 1, 2, 3 }) using (var v2 = stackalloc int [ ] { 1, 2, 3 }) using (var v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v1 = stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(6, 16), // (7,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v2 = stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 16), // (8,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v3 = stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 16) ); } [Fact] public void StackAllocInUsing2() { var test = @" public class Test { unsafe public static void Main() { using (System.IDisposable v1 = stackalloc int [3] { 1, 2, 3 }) using (System.IDisposable v2 = stackalloc int [ ] { 1, 2, 3 }) using (System.IDisposable v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int [3] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(6, 40), // (7,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(7, 40), // (8,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc [ ] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(8, 40) ); } [Fact] public void StackAllocInFixed() { var test = @" public class Test { unsafe public static void Main() { fixed (int* v1 = stackalloc int [3] { 1, 2, 3 }) fixed (int* v2 = stackalloc int [ ] { 1, 2, 3 }) fixed (int* v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int [3] { 1, 2, 3 }").WithLocation(6, 26), // (7,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(7, 26), // (8,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc [ ] { 1, 2, 3 }").WithLocation(8, 26) ); } [Fact] public void ConstStackAllocExpression() { var test = @" unsafe public class Test { void M() { const int* p1 = stackalloc int [3] { 1, 2, 3 }; const int* p2 = stackalloc int [ ] { 1, 2, 3 }; const int* p3 = stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilation(test, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (6,15): error CS0283: The type 'int*' cannot be declared const // const int* p1 = stackalloc int[1] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(6, 15), // (7,15): error CS0283: The type 'int*' cannot be declared const // const int* p2 = stackalloc int[] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(7, 15), // (8,15): error CS0283: The type 'int*' cannot be declared const // const int* p3 = stackalloc [] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(8, 15) ); } [Fact] public void RefStackAllocAssignment_ValueToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p1 = stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 23), // (7,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 28), // (8,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p2 = stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 23), // (8,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 28), // (9,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p3 = stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 23), // (9,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 28) ); } [Fact] public void RefStackAllocAssignment_RefToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p1 = ref stackalloc int [3] { 1, 2, 3 }; ref Span<int> p2 = ref stackalloc int [ ] { 1, 2, 3 }; ref Span<int> p3 = ref stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p1 = ref stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 32), // (8,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p2 = ref stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 32), // (9,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p3 = ref stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 32) ); } [Fact] public void InvalidPositionForStackAllocSpan() { var test = @" using System; public class Test { void M() { N(stackalloc int [3] { 1, 2, 3 }); N(stackalloc int [ ] { 1, 2, 3 }); N(stackalloc [ ] { 1, 2, 3 }); } void N(Span<int> span) { } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 11), // (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11), // (9,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 11) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void CannotDotIntoStackAllocExpression() { var test = @" public class Test { void M() { int length1 = (stackalloc int [3] { 1, 2, 3 }).Length; int length2 = (stackalloc int [ ] { 1, 2, 3 }).Length; int length3 = (stackalloc [ ] { 1, 2, 3 }).Length; int length4 = stackalloc int [3] { 1, 2, 3 }.Length; int length5 = stackalloc int [ ] { 1, 2, 3 }.Length; int length6 = stackalloc [ ] { 1, 2, 3 }.Length; } } "; CreateCompilationWithMscorlibAndSpan(test, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length1 = (stackalloc int [3] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 24), // (7,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length2 = (stackalloc int [ ] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 24), // (8,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length3 = (stackalloc [ ] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 24), // (10,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length4 = stackalloc int [3] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(10, 23), // (11,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length5 = stackalloc int [ ] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(11, 23), // (12,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length6 = stackalloc [ ] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(12, 23) ); CreateCompilationWithMscorlibAndSpan(test, TestOptions.ReleaseDll).VerifyDiagnostics( ); } [Fact] public void OverloadResolution_Fail() { var test = @" using System; unsafe public class Test { static void Main() { Invoke(stackalloc int [3] { 1, 2, 3 }); Invoke(stackalloc int [ ] { 1, 2, 3 }); Invoke(stackalloc [ ] { 1, 2, 3 }); } static void Invoke(Span<short> shortSpan) => Console.WriteLine(""shortSpan""); static void Invoke(Span<bool> boolSpan) => Console.WriteLine(""boolSpan""); static void Invoke(int* intPointer) => Console.WriteLine(""intPointer""); static void Invoke(void* voidPointer) => Console.WriteLine(""voidPointer""); } "; CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 16), // (8,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 16), // (9,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 16) ); CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe).VerifyDiagnostics( // (7,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [3] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(7, 16), // (8,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(8, 16), // (9,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(9, 16) ); } [Fact] public void StackAllocWithDynamic() { CreateCompilation(@" class Program { static void Main() { dynamic d = 1; var d1 = stackalloc dynamic [3] { d }; var d2 = stackalloc dynamic [ ] { d }; var d3 = stackalloc [ ] { d }; } }").VerifyDiagnostics( // (7,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(7, 29), // (7,18): error CS0847: An array initializer of length '3' is expected // var d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc dynamic [3] { d }").WithArguments("3").WithLocation(7, 18), // (8,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d2 = stackalloc dynamic [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(8, 29), // (9,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [ ] { d }").WithArguments("dynamic").WithLocation(9, 18), // (9,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc [ ] { d }").WithLocation(9, 18) ); } [Fact] public void StackAllocWithDynamicSpan() { CreateCompilationWithMscorlibAndSpan(@" using System; class Program { static void Main() { dynamic d = 1; Span<dynamic> d1 = stackalloc dynamic [3] { d }; Span<dynamic> d2 = stackalloc dynamic [ ] { d }; Span<dynamic> d3 = stackalloc [ ] { d }; } }").VerifyDiagnostics( // (8,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(8, 39), // (8,28): error CS0847: An array initializer of length '3' is expected // Span<dynamic> d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc dynamic [3] { d }").WithArguments("3").WithLocation(8, 28), // (9,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d2 = stackalloc dynamic [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(9, 39), // (10,28): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [ ] { d }").WithArguments("dynamic").WithLocation(10, 28) ); } [Fact] public void StackAllocAsArgument() { var source = @" class Program { static void N(object p) { } static void Main() { N(stackalloc int [3] { 1, 2, 3 }); N(stackalloc int [ ] { 1, 2, 3 }); N(stackalloc [ ] { 1, 2, 3 }); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11), // (9,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 11), // (10,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(10, 11) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [3] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(8, 11), // (9,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(9, 11), // (10,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(10, 11) ); } [Fact] public void StackAllocInParenthesis() { var source = @" class Program { static void Main() { var x1 = (stackalloc int [3] { 1, 2, 3 }); var x2 = (stackalloc int [ ] { 1, 2, 3 }); var x3 = (stackalloc [ ] { 1, 2, 3 }); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = (stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 19), // (7,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = (stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 19), // (8,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = (stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 19) ); CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void StackAllocInNullConditionalOperator() { var source = @" class Program { static void Main() { var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 18), // (6,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 52), // (7,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 18), // (7,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 52), // (8,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 18), // (8,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 52) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(6, 18), // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(7, 18), // (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(8, 18) ); } [Fact] public void StackAllocInCastAndConditionalOperator() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public void Method() { Test value1 = true ? new Test() : (Test)stackalloc int [3] { 1, 2, 3 }; Test value2 = true ? new Test() : (Test)stackalloc int [ ] { 1, 2, 3 }; Test value3 = true ? new Test() : (Test)stackalloc [ ] { 1, 2, 3 }; } public static explicit operator Test(Span<int> value) { return new Test(); } }", TestOptions.ReleaseDll).VerifyDiagnostics(); } [Fact] public void ERR_StackallocInCatchFinally_Catch() { var text = @" unsafe class C { int x = M(() => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err11 = stackalloc int [3] { 1, 2, 3 }; int* err12 = stackalloc int [ ] { 1, 2, 3 }; int* err13 = stackalloc [ ] { 1, 2, 3 }; } }; } catch { int* err21 = stackalloc int [3] { 1, 2, 3 }; int* err22 = stackalloc int [ ] { 1, 2, 3 }; int* err23 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err31 = stackalloc int [3] { 1, 2, 3 }; int* err32 = stackalloc int [ ] { 1, 2, 3 }; int* err33 = stackalloc [ ] { 1, 2, 3 }; } }; } }); static int M(System.Action action) { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err41 = stackalloc int [3] { 1, 2, 3 }; int* err42 = stackalloc int [ ] { 1, 2, 3 }; int* err43 = stackalloc [ ] { 1, 2, 3 }; } }; } catch { int* err51 = stackalloc int [3] { 1, 2, 3 }; int* err52 = stackalloc int [ ] { 1, 2, 3 }; int* err53 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err61 = stackalloc int [3] { 1, 2, 3 }; int* err62 = stackalloc int [ ] { 1, 2, 3 }; int* err63 = stackalloc [ ] { 1, 2, 3 }; } }; } return 0; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (23,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err11 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(23, 34), // (24,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err12 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(24, 34), // (25,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err13 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(25, 34), // (31,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err21 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(31, 26), // (32,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err22 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(32, 26), // (33,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err23 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(33, 26), // (45,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err31 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(45, 34), // (46,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err32 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(46, 34), // (47,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err33 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(47, 34), // (72,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err41 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(72, 34), // (73,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err42 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(73, 34), // (74,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err43 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(74, 34), // (80,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err51 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(80, 26), // (81,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err52 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(81, 26), // (82,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err53 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(82, 26), // (94,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err61 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(94, 34), // (95,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err62 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(95, 34), // (96,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err63 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(96, 34) ); } [Fact] public void ERR_StackallocInCatchFinally_Finally() { var text = @" unsafe class C { int x = M(() => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err11 = stackalloc int [3] { 1, 2, 3 }; int* err12 = stackalloc int [ ] { 1, 2, 3 }; int* err13 = stackalloc [ ] { 1, 2, 3 }; } }; } finally { int* err21 = stackalloc int [3] { 1, 2, 3 }; int* err22 = stackalloc int [ ] { 1, 2, 3 }; int* err23 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err31 = stackalloc int [3] { 1, 2, 3 }; int* err32 = stackalloc int [ ] { 1, 2, 3 }; int* err33 = stackalloc [ ] { 1, 2, 3 }; } }; } }); static int M(System.Action action) { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err41 = stackalloc int [3] { 1, 2, 3 }; int* err42 = stackalloc int [ ] { 1, 2, 3 }; int* err43 = stackalloc [ ] { 1, 2, 3 }; } }; } finally { int* err51 = stackalloc int [3] { 1, 2, 3 }; int* err52 = stackalloc int [ ] { 1, 2, 3 }; int* err53 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err61 = stackalloc int [3] { 1, 2, 3 }; int* err62 = stackalloc int [ ] { 1, 2, 3 }; int* err63 = stackalloc [ ] { 1, 2, 3 }; } }; } return 0; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (23,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err11 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(23, 34), // (24,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err12 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(24, 34), // (25,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err13 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(25, 34), // (31,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err21 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(31, 26), // (32,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err22 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(32, 26), // (33,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err23 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(33, 26), // (45,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err31 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(45, 34), // (46,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err32 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(46, 34), // (47,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err33 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(47, 34), // (72,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err41 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(72, 34), // (73,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err42 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(73, 34), // (74,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err43 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(74, 34), // (80,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err51 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(80, 26), // (81,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err52 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(81, 26), // (82,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err53 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(82, 26), // (94,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err61 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(94, 34), // (95,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err62 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(95, 34), // (96,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err63 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(96, 34) ); } [Fact] public void StackAllocArrayCreationExpression_Symbols() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { var obj1 = stackalloc double[2] { 1, 1.2 }; Span<double> obj2 = stackalloc double[2] { 1, 1.2 }; _ = stackalloc double[2] { 1, 1.2 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,13): error CS8353: A result of a stackalloc expression of type 'Span<double>' cannot be used in this context because it may be exposed outside of the containing method // _ = stackalloc double[2] { 1, 1.2 }; Diagnostic(ErrorCode.ERR_EscapeStackAlloc, "stackalloc double[2] { 1, 1.2 }").WithArguments("System.Span<double>").WithLocation(9, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); var sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void ImplicitStackAllocArrayCreationExpression_Symbols() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { var obj1 = stackalloc[] { 1, 1.2 }; Span<double> obj2 = stackalloc[] { 1, 1.2 }; _ = stackalloc[] { 1, 1.2 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,13): error CS8353: A result of a stackalloc expression of type 'Span<double>' cannot be used in this context because it may be exposed outside of the containing method // _ = stackalloc[] { 1, 1.2 }; Diagnostic(ErrorCode.ERR_EscapeStackAlloc, "stackalloc[] { 1, 1.2 }").WithArguments("System.Span<double>").WithLocation(9, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void StackAllocArrayCreationExpression_Symbols_ErrorCase() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,41): error CS0150: A constant value is expected // short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_ConstantExpected, "*obj1").WithLocation(7, 41), // (8,46): error CS0150: A constant value is expected // Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_ConstantExpected, "obj2.Length").WithLocation(8, 46), // (7,42): error CS0165: Use of unassigned local variable 'obj1' // short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(7, 42), // (8,46): error CS0165: Use of unassigned local variable 'obj2' // Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(8, 46) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(2, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int16*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.NoConversion, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int16", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Int16", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); var sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int16", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Int16>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.NoConversion, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("ref System.Int16 System.Span<System.Int16>.this[System.Int32 i] { get; }", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int16", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Equal("System.Int32 System.Span<System.Int16>.Length { get; }", element1Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Equal("System.Int32 System.Span<System.Int16>.Length { get; }", sizeInfo.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void ImplicitStackAllocArrayCreationExpression_Symbols_ErrorCase() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { double* obj1 = stackalloc[] { obj1[0], *obj1 }; Span<double> obj2 = stackalloc[] { obj2[0], obj2.Length }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,39): error CS0165: Use of unassigned local variable 'obj1' // double* obj1 = stackalloc[] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(7, 39), // (8,44): error CS0165: Use of unassigned local variable 'obj2' // Span<double> obj2 = stackalloc[] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(8, 44) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(2, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Double", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("ref System.Double System.Span<System.Double>.this[System.Int32 i] { get; }", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Equal("System.Int32 System.Span<System.Double>.Length { get; }", element1Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.StackAllocInitializer)] public class StackAllocInitializerTests : CompilingTestBase { [Fact, WorkItem(33945, "https://github.com/dotnet/roslyn/issues/33945")] public void RestrictedTypesAllowedInStackalloc() { var comp = CreateCompilationWithMscorlibAndSpan(@" public ref struct RefS { } public ref struct RefG<T> { public T field; } class C { unsafe void M() { var x1 = stackalloc RefS[10]; var x2 = stackalloc RefG<string>[10]; var x3 = stackalloc RefG<int>[10]; var x4 = stackalloc System.TypedReference[10]; // Note: this should be disallowed by adding a dummy field to the ref assembly for TypedReference var x5 = stackalloc System.ArgIterator[10]; var x6 = stackalloc System.RuntimeArgumentHandle[10]; var y1 = new RefS[10]; var y2 = new RefG<string>[10]; var y3 = new RefG<int>[10]; var y4 = new System.TypedReference[10]; var y5 = new System.ArgIterator[10]; var y6 = new System.RuntimeArgumentHandle[10]; RefS[] z1 = null; RefG<string>[] z2 = null; RefG<int>[] z3 = null; System.TypedReference[] z4 = null; System.ArgIterator[] z5 = null; System.RuntimeArgumentHandle[] z6 = null; _ = z1; _ = z2; _ = z3; _ = z4; _ = z5; _ = z6; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (10,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('RefG<string>') // var x2 = stackalloc RefG<string>[10]; Diagnostic(ErrorCode.ERR_ManagedAddr, "RefG<string>").WithArguments("RefG<string>").WithLocation(10, 29), // (16,22): error CS0611: Array elements cannot be of type 'RefS' // var y1 = new RefS[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefS").WithArguments("RefS").WithLocation(16, 22), // (17,22): error CS0611: Array elements cannot be of type 'RefG<string>' // var y2 = new RefG<string>[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<string>").WithArguments("RefG<string>").WithLocation(17, 22), // (18,22): error CS0611: Array elements cannot be of type 'RefG<int>' // var y3 = new RefG<int>[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<int>").WithArguments("RefG<int>").WithLocation(18, 22), // (19,22): error CS0611: Array elements cannot be of type 'TypedReference' // var y4 = new System.TypedReference[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(19, 22), // (20,22): error CS0611: Array elements cannot be of type 'ArgIterator' // var y5 = new System.ArgIterator[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(20, 22), // (21,22): error CS0611: Array elements cannot be of type 'RuntimeArgumentHandle' // var y6 = new System.RuntimeArgumentHandle[10]; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(21, 22), // (23,9): error CS0611: Array elements cannot be of type 'RefS' // RefS[] z1 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefS").WithArguments("RefS").WithLocation(23, 9), // (24,9): error CS0611: Array elements cannot be of type 'RefG<string>' // RefG<string>[] z2 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<string>").WithArguments("RefG<string>").WithLocation(24, 9), // (25,9): error CS0611: Array elements cannot be of type 'RefG<int>' // RefG<int>[] z3 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "RefG<int>").WithArguments("RefG<int>").WithLocation(25, 9), // (26,9): error CS0611: Array elements cannot be of type 'TypedReference' // System.TypedReference[] z4 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(26, 9), // (27,9): error CS0611: Array elements cannot be of type 'ArgIterator' // System.ArgIterator[] z5 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(27, 9), // (28,9): error CS0611: Array elements cannot be of type 'RuntimeArgumentHandle' // System.RuntimeArgumentHandle[] z6 = null; Diagnostic(ErrorCode.ERR_ArrayElementCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(28, 9) ); } [Fact] public void NoBestType_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { struct A {} struct B {} void Method(dynamic d, RefStruct r) { var p0 = stackalloc[] { new A(), new B() }; var p1 = stackalloc[] { }; var p2 = stackalloc[] { VoidMethod() }; var p3 = stackalloc[] { null }; var p4 = stackalloc[] { (1, null) }; var p5 = stackalloc[] { () => { } }; var p6 = stackalloc[] { new {} , new { i = 0 } }; var p7 = stackalloc[] { d }; var p8 = stackalloc[] { _ }; } public void VoidMethod() {} } namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 a, T2 b) => throw null; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // void Method(dynamic d, RefStruct r) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "RefStruct").WithArguments("RefStruct").WithLocation(7, 28), // (9,18): error CS0826: No best type found for implicitly-typed array // var p0 = stackalloc[] { new A(), new B() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new A(), new B() }").WithLocation(9, 18), // (10,18): error CS0826: No best type found for implicitly-typed array // var p1 = stackalloc[] { }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { }").WithLocation(10, 18), // (11,18): error CS0826: No best type found for implicitly-typed array // var p2 = stackalloc[] { VoidMethod() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { VoidMethod() }").WithLocation(11, 18), // (12,18): error CS0826: No best type found for implicitly-typed array // var p3 = stackalloc[] { null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { null }").WithLocation(12, 18), // (13,18): error CS0826: No best type found for implicitly-typed array // var p4 = stackalloc[] { (1, null) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { (1, null) }").WithLocation(13, 18), // (14,18): error CS0826: No best type found for implicitly-typed array // var p5 = stackalloc[] { () => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { () => { } }").WithLocation(14, 18), // (15,18): error CS0826: No best type found for implicitly-typed array // var p6 = stackalloc[] { new {} , new { i = 0 } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new {} , new { i = 0 } }").WithLocation(15, 18), // (16,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var p7 = stackalloc[] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { d }").WithArguments("dynamic").WithLocation(16, 18), // (17,33): error CS0103: The name '_' does not exist in the current context // var p8 = stackalloc[] { _ }; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(17, 33) ); } [Fact] public void NoBestType_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { struct A {} struct B {} void Method(dynamic d, bool c) { var p0 = c ? default : stackalloc[] { new A(), new B() }; var p1 = c ? default : stackalloc[] { }; var p2 = c ? default : stackalloc[] { VoidMethod() }; var p3 = c ? default : stackalloc[] { null }; var p4 = c ? default : stackalloc[] { (1, null) }; var p5 = c ? default : stackalloc[] { () => { } }; var p6 = c ? default : stackalloc[] { new {} , new { i = 0 } }; var p7 = c ? default : stackalloc[] { d }; var p8 = c ? default : stackalloc[] { _ }; } public void VoidMethod() {} } namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 a, T2 b) => throw null; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (9,32): error CS0826: No best type found for implicitly-typed array // var p0 = c ? default : stackalloc[] { new A(), new B() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new A(), new B() }").WithLocation(9, 32), // (10,32): error CS0826: No best type found for implicitly-typed array // var p1 = c ? default : stackalloc[] { }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { }").WithLocation(10, 32), // (11,32): error CS0826: No best type found for implicitly-typed array // var p2 = c ? default : stackalloc[] { VoidMethod() }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { VoidMethod() }").WithLocation(11, 32), // (12,32): error CS0826: No best type found for implicitly-typed array // var p3 = c ? default : stackalloc[] { null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { null }").WithLocation(12, 32), // (13,32): error CS0826: No best type found for implicitly-typed array // var p4 = c ? default : stackalloc[] { (1, null) }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { (1, null) }").WithLocation(13, 32), // (14,32): error CS0826: No best type found for implicitly-typed array // var p5 = c ? default : stackalloc[] { () => { } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { () => { } }").WithLocation(14, 32), // (15,32): error CS0826: No best type found for implicitly-typed array // var p6 = c ? default : stackalloc[] { new {} , new { i = 0 } }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "stackalloc[] { new {} , new { i = 0 } }").WithLocation(15, 32), // (16,32): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var p7 = c ? default : stackalloc[] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { d }").WithArguments("dynamic").WithLocation(16, 32), // (17,47): error CS0103: The name '_' does not exist in the current context // var p8 = c ? default : stackalloc[] { _ }; Diagnostic(ErrorCode.ERR_NameNotInContext, "_").WithArguments("_").WithLocation(17, 47) ); } [Fact] public void InitializeWithSelf_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void Method1() { var obj1 = stackalloc int[1] { obj1 }; var obj2 = stackalloc int[ ] { obj2 }; var obj3 = stackalloc [ ] { obj3 }; } void Method2() { var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,40): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[1] { obj1 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(6, 40), // (7,40): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(7, 40), // (8,40): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(8, 40), // (13,40): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 40), // (13,50): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 50), // (14,40): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 40), // (14,50): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 50), // (15,40): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 40), // (15,50): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 50) ); } [Fact] public void InitializeWithSelf_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void Method1(bool c) { var obj1 = c ? default : stackalloc int[1] { obj1 }; var obj2 = c ? default : stackalloc int[ ] { obj2 }; var obj3 = c ? default : stackalloc [ ] { obj3 }; } void Method2(bool c) { var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; } } ", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,54): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[1] { obj1 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(6, 54), // (7,54): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(7, 54), // (8,54): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3 }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(8, 54), // (13,54): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 54), // (13,64): error CS0841: Cannot use local variable 'obj1' before it is declared // var obj1 = c ? default : stackalloc int[2] { obj1[0] , obj1[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj1").WithArguments("obj1").WithLocation(13, 64), // (14,54): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 54), // (14,64): error CS0841: Cannot use local variable 'obj2' before it is declared // var obj2 = c ? default : stackalloc int[ ] { obj2[0] , obj2[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj2").WithArguments("obj2").WithLocation(14, 64), // (15,54): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 54), // (15,64): error CS0841: Cannot use local variable 'obj3' before it is declared // var obj3 = c ? default : stackalloc [ ] { obj3[0] , obj3[1] }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "obj3").WithArguments("obj3").WithLocation(15, 64) ); } [Fact] public void BadBestType_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { ref struct S {} void Method1(S s) { var obj1 = stackalloc[] { """" }; var obj2 = stackalloc[] { new {} }; var obj3 = stackalloc[] { s }; // OK } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // var obj1 = stackalloc[] { "" }; Diagnostic(ErrorCode.ERR_ManagedAddr, @"stackalloc[] { """" }").WithArguments("string").WithLocation(7, 20), // (8,20): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>') // var obj2 = stackalloc[] { new {} }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { new {} }").WithArguments("<empty anonymous type>").WithLocation(8, 20) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.String*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.String*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.String", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.String", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("<empty anonymous type>*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("<empty anonymous type>..ctor()", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("Test.S*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("Test.S*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("Test.S s", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.Type.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); } [Fact] public void BadBestType_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { ref struct S {} void Method1(S s, bool c) { var obj1 = c ? default : stackalloc[] { """" }; var obj2 = c ? default : stackalloc[] { new {} }; var obj3 = c ? default : stackalloc[] { s }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,34): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // var obj1 = c ? default : stackalloc[] { "" }; Diagnostic(ErrorCode.ERR_ManagedAddr, @"stackalloc[] { """" }").WithArguments("string").WithLocation(7, 34), // (8,34): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('<empty anonymous type>') // var obj2 = c ? default : stackalloc[] { new {} }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { new {} }").WithArguments("<empty anonymous type>").WithLocation(8, 34), // (9,34): error CS0306: The type 'Test.S' may not be used as a type argument // var obj3 = c ? default : stackalloc[] { s }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "stackalloc[] { s }").WithArguments("Test.S").WithLocation(9, 34) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.String>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.String>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.String", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.String", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<<empty anonymous type>>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<<empty anonymous type>>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("<empty anonymous type>..ctor()", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.Type.ToTestDisplayString()); Assert.Equal("<empty anonymous type>", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<Test.S>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<Test.S>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("Test.S s", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.Type.ToTestDisplayString()); Assert.Equal("Test.S", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); } [Fact] public void TestFor_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { static void Method1() { int i = 0; for (var p = stackalloc int[3] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method2() { int i = 0; for (var p = stackalloc int[ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method3() { int i = 0; for (var p = stackalloc [ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } public static void Main() { Method1(); Method2(); Method3(); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "123123123", verify: Verification.Fails); } [Fact] public void TestFor_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { static void Method1() { int i = 0; for (Span<int> p = stackalloc int[3] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method2() { int i = 0; for (Span<int> p = stackalloc int[ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } static void Method3() { int i = 0; for (Span<int> p = stackalloc [ ] { 1, 2, 3 }; i < 3; i++) Console.Write(p[i]); } public static void Main() { Method1(); Method2(); Method3(); } }", TestOptions.DebugExe); comp.VerifyDiagnostics(); } [Fact] public void TestForTernary() { var comp = CreateCompilationWithMscorlibAndSpan(@" class Test { static void Method1(bool b) { for (var p = b ? stackalloc int[3] { 1, 2, 3 } : default; false;) {} for (var p = b ? stackalloc int[ ] { 1, 2, 3 } : default; false;) {} for (var p = b ? stackalloc [ ] { 1, 2, 3 } : default; false;) {} } }", TestOptions.ReleaseDll); comp.VerifyDiagnostics(); } [Fact] public void TestLock() { var source = @" class Test { static void Method1() { lock (stackalloc int[3] { 1, 2, 3 }) {} lock (stackalloc int[ ] { 1, 2, 3 }) {} lock (stackalloc [ ] { 1, 2, 3 }) {} } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (6,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 15), // (6,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int*").WithLocation(6, 15), // (7,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 15), // (7,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[ ] { 1, 2, 3 }").WithArguments("int*").WithLocation(7, 15), // (8,15): error CS8370: Feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 15), // (8,15): error CS0185: 'int*' is not a reference type as required by the lock statement // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc [ ] { 1, 2, 3 }").WithArguments("int*").WithLocation(8, 15) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (6,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc int[3] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(6, 15), // (7,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc int[ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc int[ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 15), // (8,15): error CS0185: 'Span<int>' is not a reference type as required by the lock statement // lock (stackalloc [ ] { 1, 2, 3 }) {} Diagnostic(ErrorCode.ERR_LockNeedsReference, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 15) ); } [Fact] public void TestSelect() { var source = @" using System.Linq; class Test { static void Method1(int[] array) { var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (7,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 44), // (8,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 44), // (9,44): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 44) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (7,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q1 = from item in array select stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc int[3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 37), // (8,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q2 = from item in array select stackalloc int[ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc int[ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 37), // (9,37): error CS0306: The type 'Span<int>' may not be used as a type argument // var q3 = from item in array select stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(9, 37) ); } [Fact] public void TestLet() { var source = @" using System.Linq; class Test { static void Method1(int[] array) { var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; } }"; CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (7,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 45), // (8,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 45), // (9,45): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 45) ); CreateCompilationWithMscorlibAndSpan(source, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8) .VerifyDiagnostics( // (7,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q1 = from item in array let v = stackalloc int[3] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(7, 75), // (8,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q2 = from item in array let v = stackalloc int[ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(8, 75), // (9,75): error CS0306: The type 'Span<int>' may not be used as a type argument // var q3 = from item in array let v = stackalloc [ ] { 1, 2, 3 } select v; Diagnostic(ErrorCode.ERR_BadTypeArgument, "select v").WithArguments("System.Span<int>").WithLocation(9, 75) ); } [Fact] public void TestAwait_Pointer() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System.Threading.Tasks; unsafe class Test { async void M() { var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,32): error CS4004: Cannot await in an unsafe context // var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.FromResult(1)").WithLocation(7, 32), // (7,60): error CS4004: Cannot await in an unsafe context // var p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_AwaitInUnsafeContext, "await Task.FromResult(2)").WithLocation(7, 60) ); } [Fact] public void TestAwait_Span() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; using System.Threading.Tasks; class Test { async void M() { Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (8,38): error CS0150: A constant value is expected // Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_ConstantExpected, "await Task.FromResult(1)").WithLocation(8, 38), // (8,9): error CS4012: Parameters or locals of type 'Span<int>' cannot be declared in async methods or async lambda expressions. // Span<int> p = stackalloc int[await Task.FromResult(1)] { await Task.FromResult(2) }; Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "Span<int>").WithArguments("System.Span<int>").WithLocation(8, 9) ); } [Fact] public void TestSelfInSize() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { void M() { var x = stackalloc int[x] { }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,32): error CS0841: Cannot use local variable 'x' before it is declared // var x = stackalloc int[x] { }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 32) ); } [Fact] public void WrongLength() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[10] { }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,20): error CS0847: An array initializer of length '10' is expected // var obj1 = stackalloc int[10] { }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc int[10] { }").WithArguments("10").WithLocation(6, 20) ); } [Fact] public void NoInit() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[]; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,34): error CS1586: Array creation must have array size or array initializer // var obj1 = stackalloc int[]; Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(6, 34) ); } [Fact] public void NestedInit() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[1] { { 42 } }; var obj2 = stackalloc int[ ] { { 42 } }; var obj3 = stackalloc [ ] { { 42 } }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj1 = stackalloc int[1] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(6, 40), // (7,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj2 = stackalloc int[ ] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(7, 40), // (8,40): error CS0623: Array initializers can only be used in a variable or field initializer. Try using a new expression instead. // var obj3 = stackalloc [ ] { { 42 } }; Diagnostic(ErrorCode.ERR_ArrayInitInBadPlace, "{ 42 }").WithLocation(8, 40) ); } [Fact] public void AsStatement() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { stackalloc[] {1}; stackalloc int[] {1}; stackalloc int[1] {1}; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc[] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc[] {1}").WithLocation(6, 9), // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc int[] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc int[] {1}").WithLocation(7, 9), // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // stackalloc int[1] {1}; Diagnostic(ErrorCode.ERR_IllegalStatement, "stackalloc int[1] {1}").WithLocation(8, 9) ); } [Fact] public void BadRank() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[][] { 1 }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,31): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('int[]') // var obj1 = stackalloc int[][] { 1 }; Diagnostic(ErrorCode.ERR_ManagedAddr, "int").WithArguments("int[]").WithLocation(6, 31), // (6,31): error CS1575: A stackalloc expression requires [] after type // var obj1 = stackalloc int[][] { 1 }; Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[][]").WithLocation(6, 31) ); } [Fact] public void BadDimension() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public void Method1() { var obj1 = stackalloc int[,] { 1 }; var obj2 = stackalloc [,] { 1 }; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,35): error CS8381: "Invalid rank specifier: expected ']' // var obj2 = stackalloc [,] { 1 }; Diagnostic(ErrorCode.ERR_InvalidStackAllocArray, ",").WithLocation(7, 35), // (6,31): error CS1575: A stackalloc expression requires [] after type // var obj1 = stackalloc int[,] { 1 }; Diagnostic(ErrorCode.ERR_BadStackAllocExpr, "int[,]").WithLocation(6, 31) ); } [Fact] public void TestFlowPass1() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public static void Main() { int i, j, k; var obj1 = stackalloc int [1] { i = 1 }; var obj2 = stackalloc int [ ] { j = 2 }; var obj3 = stackalloc [ ] { k = 3 }; Console.Write(i); Console.Write(j); Console.Write(k); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "123"); } [Fact] public void TestFlowPass2() { var comp = CreateCompilationWithMscorlibAndSpan(@" unsafe class Test { public static void Main() { int i, j, k; var obj1 = stackalloc int [1] { i }; var obj2 = stackalloc int [ ] { j }; var obj3 = stackalloc [ ] { k }; } }", TestOptions.UnsafeReleaseExe); comp.VerifyDiagnostics( // (7,41): error CS0165: Use of unassigned local variable 'i' // var obj1 = stackalloc int [1] { i }; Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(7, 41), // (8,41): error CS0165: Use of unassigned local variable 'j' // var obj2 = stackalloc int [ ] { j }; Diagnostic(ErrorCode.ERR_UseDefViolation, "j").WithArguments("j").WithLocation(8, 41), // (9,41): error CS0165: Use of unassigned local variable 'k' // var obj3 = stackalloc [ ] { k }; Diagnostic(ErrorCode.ERR_UseDefViolation, "k").WithArguments("k").WithLocation(9, 41) ); } [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Implicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { Test obj1 = stackalloc int[3] { 1, 2, 3 }; var obj2 = stackalloc int[3] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[3] { 1, 2, 3 }; int* obj4 = stackalloc int[3] { 1, 2, 3 }; double* obj5 = stackalloc int[3] { 1, 2, 3 }; } public void Method2() { Test obj1 = stackalloc int[] { 1, 2, 3 }; var obj2 = stackalloc int[] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[] { 1, 2, 3 }; int* obj4 = stackalloc int[] { 1, 2, 3 }; double* obj5 = stackalloc int[] { 1, 2, 3 }; } public void Method3() { Test obj1 = stackalloc[] { 1, 2, 3 }; var obj2 = stackalloc[] { 1, 2, 3 }; Span<int> obj3 = stackalloc[] { 1, 2, 3 }; int* obj4 = stackalloc[] { 1, 2, 3 }; double* obj5 = stackalloc[] { 1, 2, 3 }; } public static implicit operator Test(int* value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(11, 24), // (20,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(20, 24), // (29,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(29, 24) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(15, variables.Count()); for (int i = 0; i < 15; i += 5) { var obj1 = variables.ElementAt(i); Assert.Equal("obj1", obj1.Identifier.Text); var obj1Value = model.GetSemanticInfoSummary(obj1.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj1Value.Type).PointedAtType.SpecialType); Assert.Equal("Test", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.ImplicitUserDefined, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(i + 1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(i + 2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(i + 3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(i + 4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } } [Fact] public void ConversionFromPointerStackAlloc_UserDefined_Explicit() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { Test obj1 = (Test)stackalloc int[3] { 1, 2, 3 }; var obj2 = stackalloc int[3] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[3] { 1, 2, 3 }; int* obj4 = stackalloc int[3] { 1, 2, 3 }; double* obj5 = stackalloc int[3] { 1, 2, 3 }; } public void Method2() { Test obj1 = (Test)stackalloc int[] { 1, 2, 3 }; var obj2 = stackalloc int[] { 1, 2, 3 }; Span<int> obj3 = stackalloc int[] { 1, 2, 3 }; int* obj4 = stackalloc int[] { 1, 2, 3 }; double* obj5 = stackalloc int[] { 1, 2, 3 }; } public void Method3() { Test obj1 = (Test)stackalloc [] { 1, 2, 3 }; var obj2 = stackalloc[] { 1, 2, 3 }; Span<int> obj3 = stackalloc [] { 1, 2, 3 }; int* obj4 = stackalloc[] { 1, 2, 3 }; double* obj5 = stackalloc[] { 1, 2, 3 }; } public static explicit operator Test(Span<int> value) { return default(Test); } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (11,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(11, 24), // (20,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc int[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(20, 24), // (29,24): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double*' is not possible. // double* obj5 = stackalloc[] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double*").WithLocation(29, 24) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var variables = tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>(); Assert.Equal(15, variables.Count()); for (int i = 0; i < 15; i += 5) { var obj1 = variables.ElementAt(i); Assert.Equal("obj1", obj1.Identifier.Text); Assert.Equal(SyntaxKind.CastExpression, obj1.Initializer.Value.Kind()); var obj1Value = model.GetSemanticInfoSummary(((CastExpressionSyntax)obj1.Initializer.Value).Expression); Assert.Equal("Span", obj1Value.Type.Name); Assert.Equal("Span", obj1Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj1Value.ImplicitConversion.Kind); var obj2 = variables.ElementAt(i + 1); Assert.Equal("obj2", obj2.Identifier.Text); var obj2Value = model.GetSemanticInfoSummary(obj2.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj2Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj2Value.ImplicitConversion.Kind); var obj3 = variables.ElementAt(i + 2); Assert.Equal("obj3", obj3.Identifier.Text); var obj3Value = model.GetSemanticInfoSummary(obj3.Initializer.Value); Assert.Equal("Span", obj3Value.Type.Name); Assert.Equal("Span", obj3Value.ConvertedType.Name); Assert.Equal(ConversionKind.Identity, obj3Value.ImplicitConversion.Kind); var obj4 = variables.ElementAt(i + 3); Assert.Equal("obj4", obj4.Identifier.Text); var obj4Value = model.GetSemanticInfoSummary(obj4.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj4Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.Identity, obj4Value.ImplicitConversion.Kind); var obj5 = variables.ElementAt(i + 4); Assert.Equal("obj5", obj5.Identifier.Text); var obj5Value = model.GetSemanticInfoSummary(obj5.Initializer.Value); Assert.Equal(SpecialType.System_Int32, ((IPointerTypeSymbol)obj5Value.Type).PointedAtType.SpecialType); Assert.Equal(SpecialType.System_Double, ((IPointerTypeSymbol)obj5Value.ConvertedType).PointedAtType.SpecialType); Assert.Equal(ConversionKind.NoConversion, obj5Value.ImplicitConversion.Kind); } } [Fact] public void ConversionError() { CreateCompilationWithMscorlibAndSpan(@" class Test { void Method1() { double x = stackalloc int[3] { 1, 2, 3 }; // implicit short y = (short)stackalloc int[3] { 1, 2, 3 }; // explicit } void Method2() { double x = stackalloc int[] { 1, 2, 3 }; // implicit short y = (short)stackalloc int[] { 1, 2, 3 }; // explicit } void Method3() { double x = stackalloc[] { 1, 2, 3 }; // implicit short y = (short)stackalloc[] { 1, 2, 3 }; // explicit } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc int[3] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(6, 20), // (7,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc int[3] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[3] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(7, 19), // (12,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc int[] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int[] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(12, 20), // (13,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc int[] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc int[] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(13, 19), // (18,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'double' is not possible. // double x = stackalloc[] { 1, 2, 3 }; // implicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1, 2, 3 }").WithArguments("int", "double").WithLocation(18, 20), // (19,19): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'short' is not possible. // short y = (short)stackalloc[] { 1, 2, 3 }; // explicit Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(short)stackalloc[] { 1, 2, 3 }").WithArguments("int", "short").WithLocation(19, 19) ); } [Fact] public void MissingSpanType() { CreateCompilation(@" class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; } }").VerifyDiagnostics( // (6,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(6, 9), // (6,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(6, 24), // (7,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(7, 9), // (7,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(7, 24), // (8,9): error CS0246: The type or namespace name 'Span<>' could not be found (are you missing a using directive or an assembly reference?) // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Span<int>").WithArguments("Span<>").WithLocation(8, 9), // (8,24): error CS0518: Predefined type 'System.Span`1' is not defined or imported // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span`1").WithLocation(8, 24) ); } [Fact] public void MissingSpanConstructor() { CreateCompilation(@" namespace System { ref struct Span<T> { } class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; } } }").VerifyEmitDiagnostics( // (11,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(11, 28), // (12,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(12, 28), // (13,28): error CS0656: Missing compiler required member 'System.Span`1..ctor' // Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span`1", ".ctor").WithLocation(13, 28) ); } [Fact] public void ConditionalExpressionOnSpan_BothStackallocSpans() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3 } : stackalloc int [3] { 1, 2, 3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : stackalloc int [ ] { 1, 2, 3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : stackalloc [ ] { 1, 2, 3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_Convertible() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3 } : (Span<int>)stackalloc int [3] { 1, 2, 3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : (Span<int>)stackalloc int [ ] { 1, 2, 3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : (Span<int>)stackalloc [ ] { 1, 2, 3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_NoCast() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { var x1 = true ? stackalloc int [3] { 1, 2, 3, } : (Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }; var x2 = true ? stackalloc int [ ] { 1, 2, 3, } : (Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }; var x3 = true ? stackalloc [ ] { 1, 2, 3, } : (Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x1 = true ? stackalloc int [3] { 1, 2, 3, } : (Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [3] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(7, 59), // (8,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x2 = true ? stackalloc int [ ] { 1, 2, 3, } : (Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc short [ ] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(8, 59), // (9,59): error CS8346: Conversion of a stackalloc expression of type 'short' to type 'Span<int>' is not possible. // var x3 = true ? stackalloc [ ] { 1, 2, 3, } : (Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "(Span<int>)stackalloc [ ] { (short)1, (short)2, (short)3 }").WithArguments("short", "System.Span<int>").WithLocation(9, 59) ); } [Fact] public void ConditionalExpressionOnSpan_CompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> a1 = stackalloc int [3] { 1, 2, 3 }; Span<int> a2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> a3 = stackalloc [ ] { 1, 2, 3 }; var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a1; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a2; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a3; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void ConditionalExpressionOnSpan_IncompatibleTypes() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<short> a = stackalloc short [10]; var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a; var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a; var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x1 = true ? stackalloc int [3] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [3] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(8, 18), // (9,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x2 = true ? stackalloc int [ ] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc int [ ] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(9, 18), // (10,18): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Span<int>' and 'System.Span<short>' // var x3 = true ? stackalloc [ ] { 1, 2, 3 } : a; Diagnostic(ErrorCode.ERR_InvalidQM, "true ? stackalloc [ ] { 1, 2, 3 } : a").WithArguments("System.Span<int>", "System.Span<short>").WithLocation(10, 18) ); } [Fact] public void ConditionalExpressionOnSpan_Nested() { CreateCompilationWithMscorlibAndSpan(@" class Test { bool N() => true; void M() { var x = N() ? N() ? stackalloc int[1] { 42 } : stackalloc int[ ] { 42 } : N() ? stackalloc[] { 42 } : N() ? stackalloc int[2] : stackalloc int[3]; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact] public void BooleanOperatorOnSpan_NoTargetTyping() { CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { if (stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }) { } if (stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }) { } if (stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }) { } } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[3] { 1, 2, 3 } == stackalloc int[3] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(6, 13), // (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int[ ] { 1, 2, 3 } == stackalloc int[ ] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(7, 13), // (8,13): error CS0019: Operator '==' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // if (stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }) { } Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc [ ] { 1, 2, 3 } == stackalloc [ ] { 1, 2, 3 }").WithArguments("==", "System.Span<int>", "System.Span<int>").WithLocation(8, 13) ); } [Fact] public void StackAllocInitializerSyntaxProducesErrorsOnEarlierVersions() { var parseOptions = new CSharpParseOptions().WithLanguageVersion(LanguageVersion.CSharp7); CreateCompilationWithMscorlibAndSpan(@" using System; class Test { void M() { Span<int> x1 = stackalloc int [3] { 1, 2, 3 }; Span<int> x2 = stackalloc int [ ] { 1, 2, 3 }; Span<int> x3 = stackalloc [ ] { 1, 2, 3 }; } }", options: TestOptions.UnsafeReleaseDll, parseOptions: parseOptions).VerifyDiagnostics( // (7,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(7, 24), // (8,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(8, 24), // (9,24): error CS8107: Feature 'stackalloc initializer' is not available in C# 7.0. Please use language version 7.3 or greater. // Span<int> x3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "stackalloc").WithArguments("stackalloc initializer", "7.3").WithLocation(9, 24) ); } [Fact] public void StackAllocSyntaxProducesUnsafeErrorInSafeCode() { CreateCompilation(@" class Test { void M() { var x1 = stackalloc int [3] { 1, 2, 3 }; var x2 = stackalloc int [ ] { 1, 2, 3 }; var x3 = stackalloc [ ] { 1, 2, 3 }; } }", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int [3] { 1, 2, 3 }").WithLocation(6, 18), // (7,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(7, 18), // (8,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc [ ] { 1, 2, 3 }").WithLocation(8, 18) ); } [Fact] public void StackAllocInUsing1() { var test = @" public class Test { unsafe public static void Main() { using (var v1 = stackalloc int [3] { 1, 2, 3 }) using (var v2 = stackalloc int [ ] { 1, 2, 3 }) using (var v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v1 = stackalloc int [3] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(6, 16), // (7,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v2 = stackalloc int [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(7, 16), // (8,16): error CS1674: 'Span<int>': type used in a using statement must be implicitly convertible to 'System.IDisposable' // using (var v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_NoConvToIDisp, "var v3 = stackalloc [ ] { 1, 2, 3 }").WithArguments("System.Span<int>").WithLocation(8, 16) ); } [Fact] public void StackAllocInUsing2() { var test = @" public class Test { unsafe public static void Main() { using (System.IDisposable v1 = stackalloc int [3] { 1, 2, 3 }) using (System.IDisposable v2 = stackalloc int [ ] { 1, 2, 3 }) using (System.IDisposable v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int [3] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(6, 40), // (7,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(7, 40), // (8,40): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'IDisposable' is not possible. // using (System.IDisposable v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc [ ] { 1, 2, 3 }").WithArguments("int", "System.IDisposable").WithLocation(8, 40) ); } [Fact] public void StackAllocInFixed() { var test = @" public class Test { unsafe public static void Main() { fixed (int* v1 = stackalloc int [3] { 1, 2, 3 }) fixed (int* v2 = stackalloc int [ ] { 1, 2, 3 }) fixed (int* v3 = stackalloc [ ] { 1, 2, 3 }) { } } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (6,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v1 = stackalloc int [3] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int [3] { 1, 2, 3 }").WithLocation(6, 26), // (7,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v2 = stackalloc int [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(7, 26), // (8,26): error CS9385: The given expression cannot be used in a fixed statement // fixed (int* v3 = stackalloc [ ] { 1, 2, 3 }) Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "stackalloc [ ] { 1, 2, 3 }").WithLocation(8, 26) ); } [Fact] public void ConstStackAllocExpression() { var test = @" unsafe public class Test { void M() { const int* p1 = stackalloc int [3] { 1, 2, 3 }; const int* p2 = stackalloc int [ ] { 1, 2, 3 }; const int* p3 = stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilation(test, options: TestOptions.UnsafeDebugDll).VerifyDiagnostics( // (6,15): error CS0283: The type 'int*' cannot be declared const // const int* p1 = stackalloc int[1] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(6, 15), // (7,15): error CS0283: The type 'int*' cannot be declared const // const int* p2 = stackalloc int[] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(7, 15), // (8,15): error CS0283: The type 'int*' cannot be declared const // const int* p3 = stackalloc [] { 1 }; Diagnostic(ErrorCode.ERR_BadConstType, "int*").WithArguments("int*").WithLocation(8, 15) ); } [Fact] public void RefStackAllocAssignment_ValueToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p1 = stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 23), // (7,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p1 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 28), // (8,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p2 = stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 23), // (8,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p2 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 28), // (9,23): error CS8172: Cannot initialize a by-reference variable with a value // ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_InitializeByReferenceVariableWithValue, "p3 = stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 23), // (9,28): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p3 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 28) ); } [Fact] public void RefStackAllocAssignment_RefToRef() { var test = @" using System; public class Test { void M() { ref Span<int> p1 = ref stackalloc int [3] { 1, 2, 3 }; ref Span<int> p2 = ref stackalloc int [ ] { 1, 2, 3 }; ref Span<int> p3 = ref stackalloc [ ] { 1, 2, 3 }; } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true)).VerifyDiagnostics( // (7,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p1 = ref stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [3] { 1, 2, 3 }").WithLocation(7, 32), // (8,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p2 = ref stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(8, 32), // (9,32): error CS1510: A ref or out value must be an assignable variable // ref Span<int> p3 = ref stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "stackalloc [ ] { 1, 2, 3 }").WithLocation(9, 32) ); } [Fact] public void InvalidPositionForStackAllocSpan() { var test = @" using System; public class Test { void M() { N(stackalloc int [3] { 1, 2, 3 }); N(stackalloc int [ ] { 1, 2, 3 }); N(stackalloc [ ] { 1, 2, 3 }); } void N(Span<int> span) { } } "; CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 11), // (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11), // (9,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 11) ); CreateCompilationWithMscorlibAndSpan(test, options: TestOptions.ReleaseDll.WithAllowUnsafe(true), parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void CannotDotIntoStackAllocExpression() { var test = @" public class Test { void M() { int length1 = (stackalloc int [3] { 1, 2, 3 }).Length; int length2 = (stackalloc int [ ] { 1, 2, 3 }).Length; int length3 = (stackalloc [ ] { 1, 2, 3 }).Length; int length4 = stackalloc int [3] { 1, 2, 3 }.Length; int length5 = stackalloc int [ ] { 1, 2, 3 }.Length; int length6 = stackalloc [ ] { 1, 2, 3 }.Length; } } "; CreateCompilationWithMscorlibAndSpan(test, TestOptions.ReleaseDll, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length1 = (stackalloc int [3] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 24), // (7,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length2 = (stackalloc int [ ] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 24), // (8,24): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length3 = (stackalloc [ ] { 1, 2, 3 }).Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 24), // (10,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length4 = stackalloc int [3] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(10, 23), // (11,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length5 = stackalloc int [ ] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(11, 23), // (12,23): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // int length6 = stackalloc [ ] { 1, 2, 3 }.Length; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(12, 23) ); CreateCompilationWithMscorlibAndSpan(test, TestOptions.ReleaseDll).VerifyDiagnostics( ); } [Fact] public void OverloadResolution_Fail() { var test = @" using System; unsafe public class Test { static void Main() { Invoke(stackalloc int [3] { 1, 2, 3 }); Invoke(stackalloc int [ ] { 1, 2, 3 }); Invoke(stackalloc [ ] { 1, 2, 3 }); } static void Invoke(Span<short> shortSpan) => Console.WriteLine(""shortSpan""); static void Invoke(Span<bool> boolSpan) => Console.WriteLine(""boolSpan""); static void Invoke(int* intPointer) => Console.WriteLine(""intPointer""); static void Invoke(void* voidPointer) => Console.WriteLine(""voidPointer""); } "; CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (7,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 16), // (8,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 16), // (9,16): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // Invoke(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 16) ); CreateCompilationWithMscorlibAndSpan(test, TestOptions.UnsafeReleaseExe).VerifyDiagnostics( // (7,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [3] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(7, 16), // (8,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(8, 16), // (9,16): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'System.Span<short>' // Invoke(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "System.Span<short>").WithLocation(9, 16) ); } [Fact] public void StackAllocWithDynamic() { CreateCompilation(@" class Program { static void Main() { dynamic d = 1; var d1 = stackalloc dynamic [3] { d }; var d2 = stackalloc dynamic [ ] { d }; var d3 = stackalloc [ ] { d }; } }").VerifyDiagnostics( // (7,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(7, 29), // (7,18): error CS0847: An array initializer of length '3' is expected // var d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc dynamic [3] { d }").WithArguments("3").WithLocation(7, 18), // (8,29): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d2 = stackalloc dynamic [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(8, 29), // (9,18): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // var d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [ ] { d }").WithArguments("dynamic").WithLocation(9, 18), // (9,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc [ ] { d }").WithLocation(9, 18) ); } [Fact] public void StackAllocWithDynamicSpan() { CreateCompilationWithMscorlibAndSpan(@" using System; class Program { static void Main() { dynamic d = 1; Span<dynamic> d1 = stackalloc dynamic [3] { d }; Span<dynamic> d2 = stackalloc dynamic [ ] { d }; Span<dynamic> d3 = stackalloc [ ] { d }; } }").VerifyDiagnostics( // (8,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(8, 39), // (8,28): error CS0847: An array initializer of length '3' is expected // Span<dynamic> d1 = stackalloc dynamic [3] { d }; Diagnostic(ErrorCode.ERR_ArrayInitializerIncorrectLength, "stackalloc dynamic [3] { d }").WithArguments("3").WithLocation(8, 28), // (9,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d2 = stackalloc dynamic [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "dynamic").WithArguments("dynamic").WithLocation(9, 39), // (10,28): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('dynamic') // Span<dynamic> d3 = stackalloc [ ] { d }; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc [ ] { d }").WithArguments("dynamic").WithLocation(10, 28) ); } [Fact] public void StackAllocAsArgument() { var source = @" class Program { static void N(object p) { } static void Main() { N(stackalloc int [3] { 1, 2, 3 }); N(stackalloc int [ ] { 1, 2, 3 }); N(stackalloc [ ] { 1, 2, 3 }); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (8,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 11), // (9,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(9, 11), // (10,11): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(10, 11) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( // (8,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [3] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(8, 11), // (9,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc int [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(9, 11), // (10,11): error CS1503: Argument 1: cannot convert from 'System.Span<int>' to 'object' // N(stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_BadArgType, "stackalloc [ ] { 1, 2, 3 }").WithArguments("1", "System.Span<int>", "object").WithLocation(10, 11) ); } [Fact] public void StackAllocInParenthesis() { var source = @" class Program { static void Main() { var x1 = (stackalloc int [3] { 1, 2, 3 }); var x2 = (stackalloc int [ ] { 1, 2, 3 }); var x3 = (stackalloc [ ] { 1, 2, 3 }); } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = (stackalloc int [3] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 19), // (7,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = (stackalloc int [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 19), // (8,19): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = (stackalloc [ ] { 1, 2, 3 }); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 19) ); CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( ); } [Fact] public void StackAllocInNullConditionalOperator() { var source = @" class Program { static void Main() { var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; } }"; CreateCompilationWithMscorlibAndSpan(source, parseOptions: TestOptions.Regular7_3).VerifyDiagnostics( // (6,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 18), // (6,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(6, 52), // (7,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 18), // (7,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(7, 52), // (8,18): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 18), // (8,52): error CS8652: The feature 'stackalloc in nested expressions' is not available in C# 7.3. Please use language version 8.0 or greater. // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "stackalloc").WithArguments("stackalloc in nested expressions", "8.0").WithLocation(8, 52) ); CreateCompilationWithMscorlibAndSpan(source).VerifyDiagnostics( // (6,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x1 = stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int [3] { 1, 2, 3 } ?? stackalloc int [3] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(6, 18), // (7,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x2 = stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc int [ ] { 1, 2, 3 } ?? stackalloc int [ ] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(7, 18), // (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'Span<int>' and 'Span<int>' // var x3 = stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, "stackalloc [ ] { 1, 2, 3 } ?? stackalloc [ ] { 1, 2, 3 }").WithArguments("??", "System.Span<int>", "System.Span<int>").WithLocation(8, 18) ); } [Fact] public void StackAllocInCastAndConditionalOperator() { CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public void Method() { Test value1 = true ? new Test() : (Test)stackalloc int [3] { 1, 2, 3 }; Test value2 = true ? new Test() : (Test)stackalloc int [ ] { 1, 2, 3 }; Test value3 = true ? new Test() : (Test)stackalloc [ ] { 1, 2, 3 }; } public static explicit operator Test(Span<int> value) { return new Test(); } }", TestOptions.ReleaseDll).VerifyDiagnostics(); } [Fact] public void ERR_StackallocInCatchFinally_Catch() { var text = @" unsafe class C { int x = M(() => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err11 = stackalloc int [3] { 1, 2, 3 }; int* err12 = stackalloc int [ ] { 1, 2, 3 }; int* err13 = stackalloc [ ] { 1, 2, 3 }; } }; } catch { int* err21 = stackalloc int [3] { 1, 2, 3 }; int* err22 = stackalloc int [ ] { 1, 2, 3 }; int* err23 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err31 = stackalloc int [3] { 1, 2, 3 }; int* err32 = stackalloc int [ ] { 1, 2, 3 }; int* err33 = stackalloc [ ] { 1, 2, 3 }; } }; } }); static int M(System.Action action) { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err41 = stackalloc int [3] { 1, 2, 3 }; int* err42 = stackalloc int [ ] { 1, 2, 3 }; int* err43 = stackalloc [ ] { 1, 2, 3 }; } }; } catch { int* err51 = stackalloc int [3] { 1, 2, 3 }; int* err52 = stackalloc int [ ] { 1, 2, 3 }; int* err53 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } catch { int* err61 = stackalloc int [3] { 1, 2, 3 }; int* err62 = stackalloc int [ ] { 1, 2, 3 }; int* err63 = stackalloc [ ] { 1, 2, 3 }; } }; } return 0; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (23,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err11 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(23, 34), // (24,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err12 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(24, 34), // (25,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err13 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(25, 34), // (31,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err21 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(31, 26), // (32,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err22 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(32, 26), // (33,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err23 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(33, 26), // (45,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err31 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(45, 34), // (46,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err32 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(46, 34), // (47,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err33 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(47, 34), // (72,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err41 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(72, 34), // (73,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err42 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(73, 34), // (74,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err43 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(74, 34), // (80,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err51 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(80, 26), // (81,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err52 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(81, 26), // (82,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err53 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(82, 26), // (94,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err61 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(94, 34), // (95,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err62 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(95, 34), // (96,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err63 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(96, 34) ); } [Fact] public void ERR_StackallocInCatchFinally_Finally() { var text = @" unsafe class C { int x = M(() => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err11 = stackalloc int [3] { 1, 2, 3 }; int* err12 = stackalloc int [ ] { 1, 2, 3 }; int* err13 = stackalloc [ ] { 1, 2, 3 }; } }; } finally { int* err21 = stackalloc int [3] { 1, 2, 3 }; int* err22 = stackalloc int [ ] { 1, 2, 3 }; int* err23 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err31 = stackalloc int [3] { 1, 2, 3 }; int* err32 = stackalloc int [ ] { 1, 2, 3 }; int* err33 = stackalloc [ ] { 1, 2, 3 }; } }; } }); static int M(System.Action action) { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* q1 = stackalloc int [3] { 1, 2, 3 }; int* q2 = stackalloc int [ ] { 1, 2, 3 }; int* q3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err41 = stackalloc int [3] { 1, 2, 3 }; int* err42 = stackalloc int [ ] { 1, 2, 3 }; int* err43 = stackalloc [ ] { 1, 2, 3 }; } }; } finally { int* err51 = stackalloc int [3] { 1, 2, 3 }; int* err52 = stackalloc int [ ] { 1, 2, 3 }; int* err53 = stackalloc [ ] { 1, 2, 3 }; System.Action a = () => { try { // fine int* p1 = stackalloc int [3] { 1, 2, 3 }; int* p2 = stackalloc int [ ] { 1, 2, 3 }; int* p3 = stackalloc [ ] { 1, 2, 3 }; } finally { int* err61 = stackalloc int [3] { 1, 2, 3 }; int* err62 = stackalloc int [ ] { 1, 2, 3 }; int* err63 = stackalloc [ ] { 1, 2, 3 }; } }; } return 0; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (23,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err11 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(23, 34), // (24,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err12 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(24, 34), // (25,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err13 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(25, 34), // (31,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err21 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(31, 26), // (32,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err22 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(32, 26), // (33,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err23 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(33, 26), // (45,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err31 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(45, 34), // (46,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err32 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(46, 34), // (47,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err33 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(47, 34), // (72,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err41 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(72, 34), // (73,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err42 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(73, 34), // (74,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err43 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(74, 34), // (80,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err51 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(80, 26), // (81,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err52 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(81, 26), // (82,26): error CS0255: stackalloc may not be used in a catch or finally block // int* err53 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(82, 26), // (94,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err61 = stackalloc int [3] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [3] { 1, 2, 3 }").WithLocation(94, 34), // (95,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err62 = stackalloc int [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc int [ ] { 1, 2, 3 }").WithLocation(95, 34), // (96,34): error CS0255: stackalloc may not be used in a catch or finally block // int* err63 = stackalloc [ ] { 1, 2, 3 }; Diagnostic(ErrorCode.ERR_StackallocInCatchFinally, "stackalloc [ ] { 1, 2, 3 }").WithLocation(96, 34) ); } [Fact] public void StackAllocArrayCreationExpression_Symbols() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { var obj1 = stackalloc double[2] { 1, 1.2 }; Span<double> obj2 = stackalloc double[2] { 1, 1.2 }; _ = stackalloc double[2] { 1, 1.2 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,13): error CS8353: A result of a stackalloc expression of type 'Span<double>' cannot be used in this context because it may be exposed outside of the containing method // _ = stackalloc double[2] { 1, 1.2 }; Diagnostic(ErrorCode.ERR_EscapeStackAlloc, "stackalloc double[2] { 1, 1.2 }").WithArguments("System.Span<double>").WithLocation(9, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); var sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void ImplicitStackAllocArrayCreationExpression_Symbols() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { var obj1 = stackalloc[] { 1, 1.2 }; Span<double> obj2 = stackalloc[] { 1, 1.2 }; _ = stackalloc[] { 1, 1.2 }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (9,13): error CS8353: A result of a stackalloc expression of type 'Span<double>' cannot be used in this context because it may be exposed outside of the containing method // _ = stackalloc[] { 1, 1.2 }; Diagnostic(ErrorCode.ERR_EscapeStackAlloc, "stackalloc[] { 1, 1.2 }").WithArguments("System.Span<double>").WithLocation(9, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(3, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[2]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int32", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void StackAllocArrayCreationExpression_Symbols_ErrorCase() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,41): error CS0150: A constant value is expected // short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_ConstantExpected, "*obj1").WithLocation(7, 41), // (8,46): error CS0150: A constant value is expected // Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_ConstantExpected, "obj2.Length").WithLocation(8, 46), // (7,42): error CS0165: Use of unassigned local variable 'obj1' // short* obj1 = stackalloc double[*obj1] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(7, 42), // (8,46): error CS0165: Use of unassigned local variable 'obj2' // Span<short> obj2 = stackalloc double[obj2.Length] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(8, 46) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<StackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(2, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int16*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.NoConversion, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Int16", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Int16", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); var sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Null(sizeInfo.Symbol); Assert.Equal("System.Int16", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Int16>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.NoConversion, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("ref System.Int16 System.Span<System.Int16>.this[System.Int32 i] { get; }", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int16", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Equal("System.Int32 System.Span<System.Int16>.Length { get; }", element1Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); sizeInfo = model.GetSemanticInfoSummary(((ArrayTypeSyntax)@stackalloc.Type).RankSpecifiers[0].Sizes[0]); Assert.Equal("System.Int32 System.Span<System.Int16>.Length { get; }", sizeInfo.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.Type.ToTestDisplayString()); Assert.Equal("System.Int32", sizeInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, sizeInfo.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } [Fact] public void ImplicitStackAllocArrayCreationExpression_Symbols_ErrorCase() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public void Method1() { double* obj1 = stackalloc[] { obj1[0], *obj1 }; Span<double> obj2 = stackalloc[] { obj2[0], obj2.Length }; } }", TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (7,39): error CS0165: Use of unassigned local variable 'obj1' // double* obj1 = stackalloc[] { obj1[0], *obj1 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(7, 39), // (8,44): error CS0165: Use of unassigned local variable 'obj2' // Span<double> obj2 = stackalloc[] { obj2[0], obj2.Length }; Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(8, 44) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var expressions = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ImplicitStackAllocArrayCreationExpressionSyntax>().ToArray(); Assert.Equal(2, expressions.Length); var @stackalloc = expressions[0]; var stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Double*", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Double*", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); var element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Null(element0Info.Symbol); Assert.Equal("System.Double", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); var element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Null(element1Info.Symbol); Assert.Equal("System.Double", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); @stackalloc = expressions[1]; stackallocInfo = model.GetSemanticInfoSummary(@stackalloc); Assert.Null(stackallocInfo.Symbol); Assert.Equal("System.Span<System.Double>", stackallocInfo.Type.ToTestDisplayString()); Assert.Equal("System.Span<System.Double>", stackallocInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, stackallocInfo.ImplicitConversion); element0Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[0]); Assert.Equal("ref System.Double System.Span<System.Double>.this[System.Int32 i] { get; }", element0Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element0Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.Identity, element0Info.ImplicitConversion); element1Info = model.GetSemanticInfoSummary(@stackalloc.Initializer.Expressions[1]); Assert.Equal("System.Int32 System.Span<System.Double>.Length { get; }", element1Info.Symbol.ToTestDisplayString()); Assert.Equal("System.Int32", element1Info.Type.ToTestDisplayString()); Assert.Equal("System.Double", element1Info.ConvertedType.ToTestDisplayString()); Assert.Equal(Conversion.ImplicitNumeric, element1Info.ImplicitConversion); Assert.Null(model.GetDeclaredSymbol(@stackalloc)); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/IGenerateEqualsAndGetHashCodeService.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.Host; namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers { /// <summary> /// Service that can be used to generate <see cref="object.Equals(object)"/> and /// <see cref="object.GetHashCode"/> overloads for use from other IDE features. /// </summary> internal interface IGenerateEqualsAndGetHashCodeService : ILanguageService { /// <summary> /// Formats only the members in the provided document that were generated by this interface. /// </summary> Task<Document> FormatDocumentAsync(Document document, CancellationToken cancellationToken); /// <summary> /// Generates an override of <see cref="object.Equals(object)"/> that works by comparing the /// provided <paramref name="members"/>. /// </summary> Task<IMethodSymbol> GenerateEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, string? localNameOpt, CancellationToken cancellationToken); /// <summary> /// Generates an override of <see cref="object.Equals(object)"/> that works by delegating to /// <see cref="IEquatable{T}.Equals(T)"/>. /// </summary> Task<IMethodSymbol> GenerateEqualsMethodThroughIEquatableEqualsAsync(Document document, INamedTypeSymbol namedType, CancellationToken cancellationToken); /// <summary> /// Generates an implementation of <see cref="IEquatable{T}.Equals"/> that works by /// comparing the provided <paramref name="members"/>. /// </summary> Task<IMethodSymbol> GenerateIEquatableEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, INamedTypeSymbol constructedEquatableType, CancellationToken cancellationToken); /// <summary> /// Generates an override of <see cref="object.GetHashCode"/> that computes a reasonable /// hash based on the provided <paramref name="members"/>. The generated function will /// defer to HashCode.Combine if it exists. Otherwise, it will determine if it should /// generate code directly in-line to compute the hash, or defer to something like /// <see cref="ValueTuple.GetHashCode"/> to provide a reasonable alternative. /// </summary> Task<IMethodSymbol> GenerateGetHashCodeMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, 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; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers { /// <summary> /// Service that can be used to generate <see cref="object.Equals(object)"/> and /// <see cref="object.GetHashCode"/> overloads for use from other IDE features. /// </summary> internal interface IGenerateEqualsAndGetHashCodeService : ILanguageService { /// <summary> /// Formats only the members in the provided document that were generated by this interface. /// </summary> Task<Document> FormatDocumentAsync(Document document, CancellationToken cancellationToken); /// <summary> /// Generates an override of <see cref="object.Equals(object)"/> that works by comparing the /// provided <paramref name="members"/>. /// </summary> Task<IMethodSymbol> GenerateEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, string? localNameOpt, CancellationToken cancellationToken); /// <summary> /// Generates an override of <see cref="object.Equals(object)"/> that works by delegating to /// <see cref="IEquatable{T}.Equals(T)"/>. /// </summary> Task<IMethodSymbol> GenerateEqualsMethodThroughIEquatableEqualsAsync(Document document, INamedTypeSymbol namedType, CancellationToken cancellationToken); /// <summary> /// Generates an implementation of <see cref="IEquatable{T}.Equals"/> that works by /// comparing the provided <paramref name="members"/>. /// </summary> Task<IMethodSymbol> GenerateIEquatableEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, INamedTypeSymbol constructedEquatableType, CancellationToken cancellationToken); /// <summary> /// Generates an override of <see cref="object.GetHashCode"/> that computes a reasonable /// hash based on the provided <paramref name="members"/>. The generated function will /// defer to HashCode.Combine if it exists. Otherwise, it will determine if it should /// generate code directly in-line to compute the hash, or defer to something like /// <see cref="ValueTuple.GetHashCode"/> to provide a reasonable alternative. /// </summary> Task<IMethodSymbol> GenerateGetHashCodeMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Tools/ExternalAccess/FSharp/SignatureHelp/IFSharpSignatureHelpProvider.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; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.SignatureHelp { internal interface IFSharpSignatureHelpProvider { /// <summary> /// Returns true if the character might trigger completion, /// e.g. '(' and ',' for method invocations /// </summary> bool IsTriggerCharacter(char ch); /// <summary> /// Returns true if the character might end a Signature Help session, /// e.g. ')' for method invocations. /// </summary> bool IsRetriggerCharacter(char ch); /// <summary> /// Returns valid signature help items at the specified position in the document. /// </summary> Task<FSharpSignatureHelpItems> GetItemsAsync(Document document, int position, FSharpSignatureHelpTriggerInfo triggerInfo, 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. #nullable disable using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.SignatureHelp { internal interface IFSharpSignatureHelpProvider { /// <summary> /// Returns true if the character might trigger completion, /// e.g. '(' and ',' for method invocations /// </summary> bool IsTriggerCharacter(char ch); /// <summary> /// Returns true if the character might end a Signature Help session, /// e.g. ')' for method invocations. /// </summary> bool IsRetriggerCharacter(char ch); /// <summary> /// Returns valid signature help items at the specified position in the document. /// </summary> Task<FSharpSignatureHelpItems> GetItemsAsync(Document document, int position, FSharpSignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/DiagnosticsTestUtilities/MoveToNamespace/AbstractMoveToNamespaceTests.TestState.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.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.MoveToNamespace; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Test.Utilities.MoveToNamespace { public abstract partial class AbstractMoveToNamespaceTests { internal class TestState : IDisposable { public TestState(TestWorkspace workspace) => Workspace = workspace; public void Dispose() => Workspace?.Dispose(); public TestWorkspace Workspace { get; } public TestHostDocument TestInvocationDocument => Workspace.Documents.Single(); public Document InvocationDocument => Workspace.CurrentSolution.GetDocument(TestInvocationDocument.Id); public TestMoveToNamespaceOptionsService TestMoveToNamespaceOptionsService => (TestMoveToNamespaceOptionsService)MoveToNamespaceService.OptionsService; public IMoveToNamespaceService MoveToNamespaceService => InvocationDocument.GetRequiredLanguageService<IMoveToNamespaceService>(); } } }
// Licensed to the .NET Foundation under one or more 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.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.MoveToNamespace; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.Test.Utilities.MoveToNamespace { public abstract partial class AbstractMoveToNamespaceTests { internal class TestState : IDisposable { public TestState(TestWorkspace workspace) => Workspace = workspace; public void Dispose() => Workspace?.Dispose(); public TestWorkspace Workspace { get; } public TestHostDocument TestInvocationDocument => Workspace.Documents.Single(); public Document InvocationDocument => Workspace.CurrentSolution.GetDocument(TestInvocationDocument.Id); public TestMoveToNamespaceOptionsService TestMoveToNamespaceOptionsService => (TestMoveToNamespaceOptionsService)MoveToNamespaceService.OptionsService; public IMoveToNamespaceService MoveToNamespaceService => InvocationDocument.GetRequiredLanguageService<IMoveToNamespaceService>(); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/ExtractMethod/MethodExtractor.VariableSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { /// <summary> /// temporary symbol until we have a symbol that can hold onto both local and parameter symbol /// </summary> protected abstract class VariableSymbol { protected VariableSymbol(Compilation compilation, ITypeSymbol type) { OriginalTypeHadAnonymousTypeOrDelegate = type.ContainsAnonymousType(); OriginalType = OriginalTypeHadAnonymousTypeOrDelegate ? type.RemoveAnonymousTypes(compilation) : type; } public abstract int DisplayOrder { get; } public abstract string Name { get; } public abstract bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken); public abstract SyntaxAnnotation IdentifierTokenAnnotation { get; } public abstract SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken); public abstract void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken); protected abstract int CompareTo(VariableSymbol right); /// <summary> /// return true if original type had anonymous type or delegate somewhere in the type /// </summary> public bool OriginalTypeHadAnonymousTypeOrDelegate { get; } /// <summary> /// get the original type with anonymous type removed /// </summary> public ITypeSymbol OriginalType { get; } public static int Compare( VariableSymbol left, VariableSymbol right, INamedTypeSymbol cancellationTokenType) { // CancellationTokens always go at the end of method signature. var leftIsCancellationToken = left.OriginalType.Equals(cancellationTokenType); var rightIsCancellationToken = right.OriginalType.Equals(cancellationTokenType); if (leftIsCancellationToken && !rightIsCancellationToken) { return 1; } else if (!leftIsCancellationToken && rightIsCancellationToken) { return -1; } if (left.DisplayOrder == right.DisplayOrder) { return left.CompareTo(right); } return left.DisplayOrder - right.DisplayOrder; } } protected abstract class NotMovableVariableSymbol : VariableSymbol { public NotMovableVariableSymbol(Compilation compilation, ITypeSymbol type) : base(compilation, type) { } public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken) { // decl never get moved return false; } public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken) => throw ExceptionUtilities.Unreachable; public override SyntaxAnnotation IdentifierTokenAnnotation => throw ExceptionUtilities.Unreachable; public override void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken) { // do nothing for parameter } } protected class ParameterVariableSymbol : NotMovableVariableSymbol, IComparable<ParameterVariableSymbol> { private readonly IParameterSymbol _parameterSymbol; public ParameterVariableSymbol(Compilation compilation, IParameterSymbol parameterSymbol, ITypeSymbol type) : base(compilation, type) { Contract.ThrowIfNull(parameterSymbol); _parameterSymbol = parameterSymbol; } public override int DisplayOrder => 0; protected override int CompareTo(VariableSymbol right) => CompareTo((ParameterVariableSymbol)right); public int CompareTo(ParameterVariableSymbol other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } var compare = CompareMethodParameters((IMethodSymbol)_parameterSymbol.ContainingSymbol, (IMethodSymbol)other._parameterSymbol.ContainingSymbol); if (compare != 0) { return compare; } Contract.ThrowIfFalse(_parameterSymbol.Ordinal != other._parameterSymbol.Ordinal); return (_parameterSymbol.Ordinal > other._parameterSymbol.Ordinal) ? 1 : -1; } private static int CompareMethodParameters(IMethodSymbol left, IMethodSymbol right) { if (left == null && right == null) { // not method parameters return 0; } if (left.Equals(right)) { // parameter of same method return 0; } // these methods can be either regular one, anonymous function, local function and etc // but all must belong to same outer regular method. // so, it should have location pointing to same tree var leftLocations = left.Locations; var rightLocations = right.Locations; var commonTree = leftLocations.Select(l => l.SourceTree).Intersect(rightLocations.Select(l => l.SourceTree)).WhereNotNull().First(); var leftLocation = leftLocations.First(l => l.SourceTree == commonTree); var rightLocation = rightLocations.First(l => l.SourceTree == commonTree); return leftLocation.SourceSpan.Start - rightLocation.SourceSpan.Start; } public override string Name { get { return _parameterSymbol.ToDisplayString( new SymbolDisplayFormat( parameterOptions: SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } } protected class LocalVariableSymbol<T> : VariableSymbol, IComparable<LocalVariableSymbol<T>> where T : SyntaxNode { private readonly SyntaxAnnotation _annotation; private readonly ILocalSymbol _localSymbol; private readonly HashSet<int> _nonNoisySet; public LocalVariableSymbol(Compilation compilation, ILocalSymbol localSymbol, ITypeSymbol type, HashSet<int> nonNoisySet) : base(compilation, type) { Contract.ThrowIfNull(localSymbol); Contract.ThrowIfNull(nonNoisySet); _annotation = new SyntaxAnnotation(); _localSymbol = localSymbol; _nonNoisySet = nonNoisySet; } public override int DisplayOrder => 1; protected override int CompareTo(VariableSymbol right) => CompareTo((LocalVariableSymbol<T>)right); public int CompareTo(LocalVariableSymbol<T> other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(other._localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource); Contract.ThrowIfFalse(other._localSymbol.Locations[0].IsInSource); Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceTree == other._localSymbol.Locations[0].SourceTree); Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceSpan.Start != other._localSymbol.Locations[0].SourceSpan.Start); return _localSymbol.Locations[0].SourceSpan.Start - other._localSymbol.Locations[0].SourceSpan.Start; } public override string Name { get { return _localSymbol.ToDisplayString( new SymbolDisplayFormat( miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken) { Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource); Contract.ThrowIfNull(_localSymbol.Locations[0].SourceTree); var tree = _localSymbol.Locations[0].SourceTree; var span = _localSymbol.Locations[0].SourceSpan; var token = tree.GetRoot(cancellationToken).FindToken(span.Start); Contract.ThrowIfFalse(token.Span.Equals(span)); return token; } public override SyntaxAnnotation IdentifierTokenAnnotation => _annotation; public override void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken) { annotations.Add(Tuple.Create(GetOriginalIdentifierToken(cancellationToken), _annotation)); } public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken) { var identifier = GetOriginalIdentifierToken(cancellationToken); // check whether there is a noisy trivia around the token. if (ContainsNoisyTrivia(identifier.LeadingTrivia)) { return true; } if (ContainsNoisyTrivia(identifier.TrailingTrivia)) { return true; } var declStatement = identifier.Parent.FirstAncestorOrSelf<T>(); if (declStatement == null) { return true; } foreach (var token in declStatement.DescendantTokens()) { if (ContainsNoisyTrivia(token.LeadingTrivia)) { return true; } if (ContainsNoisyTrivia(token.TrailingTrivia)) { return true; } } return false; } private bool ContainsNoisyTrivia(SyntaxTriviaList list) => list.Any(t => !_nonNoisySet.Contains(t.RawKind)); } protected class QueryVariableSymbol : NotMovableVariableSymbol, IComparable<QueryVariableSymbol> { private readonly IRangeVariableSymbol _symbol; public QueryVariableSymbol(Compilation compilation, IRangeVariableSymbol symbol, ITypeSymbol type) : base(compilation, type) { Contract.ThrowIfNull(symbol); _symbol = symbol; } public override int DisplayOrder => 2; protected override int CompareTo(VariableSymbol right) => CompareTo((QueryVariableSymbol)right); public int CompareTo(QueryVariableSymbol other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } var locationLeft = _symbol.Locations.First(); var locationRight = other._symbol.Locations.First(); Contract.ThrowIfFalse(locationLeft.IsInSource); Contract.ThrowIfFalse(locationRight.IsInSource); Contract.ThrowIfFalse(locationLeft.SourceTree == locationRight.SourceTree); Contract.ThrowIfFalse(locationLeft.SourceSpan.Start != locationRight.SourceSpan.Start); return locationLeft.SourceSpan.Start - locationRight.SourceSpan.Start; } public override string Name { get { return _symbol.ToDisplayString( new SymbolDisplayFormat( miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { /// <summary> /// temporary symbol until we have a symbol that can hold onto both local and parameter symbol /// </summary> protected abstract class VariableSymbol { protected VariableSymbol(Compilation compilation, ITypeSymbol type) { OriginalTypeHadAnonymousTypeOrDelegate = type.ContainsAnonymousType(); OriginalType = OriginalTypeHadAnonymousTypeOrDelegate ? type.RemoveAnonymousTypes(compilation) : type; } public abstract int DisplayOrder { get; } public abstract string Name { get; } public abstract bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken); public abstract SyntaxAnnotation IdentifierTokenAnnotation { get; } public abstract SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken); public abstract void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken); protected abstract int CompareTo(VariableSymbol right); /// <summary> /// return true if original type had anonymous type or delegate somewhere in the type /// </summary> public bool OriginalTypeHadAnonymousTypeOrDelegate { get; } /// <summary> /// get the original type with anonymous type removed /// </summary> public ITypeSymbol OriginalType { get; } public static int Compare( VariableSymbol left, VariableSymbol right, INamedTypeSymbol cancellationTokenType) { // CancellationTokens always go at the end of method signature. var leftIsCancellationToken = left.OriginalType.Equals(cancellationTokenType); var rightIsCancellationToken = right.OriginalType.Equals(cancellationTokenType); if (leftIsCancellationToken && !rightIsCancellationToken) { return 1; } else if (!leftIsCancellationToken && rightIsCancellationToken) { return -1; } if (left.DisplayOrder == right.DisplayOrder) { return left.CompareTo(right); } return left.DisplayOrder - right.DisplayOrder; } } protected abstract class NotMovableVariableSymbol : VariableSymbol { public NotMovableVariableSymbol(Compilation compilation, ITypeSymbol type) : base(compilation, type) { } public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken) { // decl never get moved return false; } public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken) => throw ExceptionUtilities.Unreachable; public override SyntaxAnnotation IdentifierTokenAnnotation => throw ExceptionUtilities.Unreachable; public override void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken) { // do nothing for parameter } } protected class ParameterVariableSymbol : NotMovableVariableSymbol, IComparable<ParameterVariableSymbol> { private readonly IParameterSymbol _parameterSymbol; public ParameterVariableSymbol(Compilation compilation, IParameterSymbol parameterSymbol, ITypeSymbol type) : base(compilation, type) { Contract.ThrowIfNull(parameterSymbol); _parameterSymbol = parameterSymbol; } public override int DisplayOrder => 0; protected override int CompareTo(VariableSymbol right) => CompareTo((ParameterVariableSymbol)right); public int CompareTo(ParameterVariableSymbol other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } var compare = CompareMethodParameters((IMethodSymbol)_parameterSymbol.ContainingSymbol, (IMethodSymbol)other._parameterSymbol.ContainingSymbol); if (compare != 0) { return compare; } Contract.ThrowIfFalse(_parameterSymbol.Ordinal != other._parameterSymbol.Ordinal); return (_parameterSymbol.Ordinal > other._parameterSymbol.Ordinal) ? 1 : -1; } private static int CompareMethodParameters(IMethodSymbol left, IMethodSymbol right) { if (left == null && right == null) { // not method parameters return 0; } if (left.Equals(right)) { // parameter of same method return 0; } // these methods can be either regular one, anonymous function, local function and etc // but all must belong to same outer regular method. // so, it should have location pointing to same tree var leftLocations = left.Locations; var rightLocations = right.Locations; var commonTree = leftLocations.Select(l => l.SourceTree).Intersect(rightLocations.Select(l => l.SourceTree)).WhereNotNull().First(); var leftLocation = leftLocations.First(l => l.SourceTree == commonTree); var rightLocation = rightLocations.First(l => l.SourceTree == commonTree); return leftLocation.SourceSpan.Start - rightLocation.SourceSpan.Start; } public override string Name { get { return _parameterSymbol.ToDisplayString( new SymbolDisplayFormat( parameterOptions: SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } } protected class LocalVariableSymbol<T> : VariableSymbol, IComparable<LocalVariableSymbol<T>> where T : SyntaxNode { private readonly SyntaxAnnotation _annotation; private readonly ILocalSymbol _localSymbol; private readonly HashSet<int> _nonNoisySet; public LocalVariableSymbol(Compilation compilation, ILocalSymbol localSymbol, ITypeSymbol type, HashSet<int> nonNoisySet) : base(compilation, type) { Contract.ThrowIfNull(localSymbol); Contract.ThrowIfNull(nonNoisySet); _annotation = new SyntaxAnnotation(); _localSymbol = localSymbol; _nonNoisySet = nonNoisySet; } public override int DisplayOrder => 1; protected override int CompareTo(VariableSymbol right) => CompareTo((LocalVariableSymbol<T>)right); public int CompareTo(LocalVariableSymbol<T> other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(other._localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource); Contract.ThrowIfFalse(other._localSymbol.Locations[0].IsInSource); Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceTree == other._localSymbol.Locations[0].SourceTree); Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceSpan.Start != other._localSymbol.Locations[0].SourceSpan.Start); return _localSymbol.Locations[0].SourceSpan.Start - other._localSymbol.Locations[0].SourceSpan.Start; } public override string Name { get { return _localSymbol.ToDisplayString( new SymbolDisplayFormat( miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken) { Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource); Contract.ThrowIfNull(_localSymbol.Locations[0].SourceTree); var tree = _localSymbol.Locations[0].SourceTree; var span = _localSymbol.Locations[0].SourceSpan; var token = tree.GetRoot(cancellationToken).FindToken(span.Start); Contract.ThrowIfFalse(token.Span.Equals(span)); return token; } public override SyntaxAnnotation IdentifierTokenAnnotation => _annotation; public override void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken) { annotations.Add(Tuple.Create(GetOriginalIdentifierToken(cancellationToken), _annotation)); } public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken) { var identifier = GetOriginalIdentifierToken(cancellationToken); // check whether there is a noisy trivia around the token. if (ContainsNoisyTrivia(identifier.LeadingTrivia)) { return true; } if (ContainsNoisyTrivia(identifier.TrailingTrivia)) { return true; } var declStatement = identifier.Parent.FirstAncestorOrSelf<T>(); if (declStatement == null) { return true; } foreach (var token in declStatement.DescendantTokens()) { if (ContainsNoisyTrivia(token.LeadingTrivia)) { return true; } if (ContainsNoisyTrivia(token.TrailingTrivia)) { return true; } } return false; } private bool ContainsNoisyTrivia(SyntaxTriviaList list) => list.Any(t => !_nonNoisySet.Contains(t.RawKind)); } protected class QueryVariableSymbol : NotMovableVariableSymbol, IComparable<QueryVariableSymbol> { private readonly IRangeVariableSymbol _symbol; public QueryVariableSymbol(Compilation compilation, IRangeVariableSymbol symbol, ITypeSymbol type) : base(compilation, type) { Contract.ThrowIfNull(symbol); _symbol = symbol; } public override int DisplayOrder => 2; protected override int CompareTo(VariableSymbol right) => CompareTo((QueryVariableSymbol)right); public int CompareTo(QueryVariableSymbol other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } var locationLeft = _symbol.Locations.First(); var locationRight = other._symbol.Locations.First(); Contract.ThrowIfFalse(locationLeft.IsInSource); Contract.ThrowIfFalse(locationRight.IsInSource); Contract.ThrowIfFalse(locationLeft.SourceTree == locationRight.SourceTree); Contract.ThrowIfFalse(locationLeft.SourceSpan.Start != locationRight.SourceSpan.Start); return locationLeft.SourceSpan.Start - locationRight.SourceSpan.Start; } public override string Name { get { return _symbol.ToDisplayString( new SymbolDisplayFormat( miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/GroupKeywordRecommender.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; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class GroupKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public GroupKeywordRecommender() : base(SyntaxKind.GroupKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var token = context.TargetToken; // var q = from x in y // | if (!token.IntersectsWith(position) && token.IsLastTokenOfQueryClause()) { return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class GroupKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public GroupKeywordRecommender() : base(SyntaxKind.GroupKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var token = context.TargetToken; // var q = from x in y // | if (!token.IntersectsWith(position) && token.IsLastTokenOfQueryClause()) { return true; } return false; } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/ExpressionEvaluator/Core/Source/FunctionResolver/MetadataResolver.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 Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal delegate void OnFunctionResolvedDelegate<TModule, TRequest>(TModule module, TRequest request, int token, int version, int ilOffset); internal sealed class MetadataResolver<TProcess, TModule, TRequest> where TProcess : class where TModule : class where TRequest : class { private readonly TProcess _process; private readonly TModule _module; private readonly MetadataReader _reader; private readonly StringComparer _stringComparer; // for comparing strings private readonly bool _ignoreCase; // for comparing strings to strings represented with StringHandles private readonly OnFunctionResolvedDelegate<TModule, TRequest> _onFunctionResolved; internal MetadataResolver( TProcess process, TModule module, MetadataReader reader, bool ignoreCase, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { _process = process; _module = module; _reader = reader; _stringComparer = ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; _ignoreCase = ignoreCase; _onFunctionResolved = onFunctionResolved; } internal void Resolve(TRequest request, RequestSignature signature) { QualifiedName qualifiedTypeName; ImmutableArray<string> memberTypeParameters; GetNameAndTypeParameters(signature.MemberName, out qualifiedTypeName, out memberTypeParameters); var typeName = qualifiedTypeName.Qualifier; var memberName = qualifiedTypeName.Name; var memberParameters = signature.Parameters; var allTypeParameters = GetAllGenericTypeParameters(typeName); foreach (var typeHandle in _reader.TypeDefinitions) { var typeDef = _reader.GetTypeDefinition(typeHandle); int containingArity = CompareToTypeDefinition(typeDef, typeName); if (containingArity < 0) { continue; } // Visit methods. foreach (var methodHandle in typeDef.GetMethods()) { var methodDef = _reader.GetMethodDefinition(methodHandle); if (!IsResolvableMethod(methodDef)) { continue; } if (MatchesMethod(typeDef, methodDef, typeName, memberName, allTypeParameters, containingArity, memberTypeParameters, memberParameters)) { OnFunctionResolved(request, methodHandle); } } if (memberTypeParameters.IsEmpty) { // Visit properties. foreach (var propertyHandle in typeDef.GetProperties()) { var propertyDef = _reader.GetPropertyDefinition(propertyHandle); if (MatchesProperty(typeDef, propertyDef, typeName, memberName, allTypeParameters, containingArity, memberParameters)) { var accessors = propertyDef.GetAccessors(); OnAccessorResolved(request, accessors.Getter); OnAccessorResolved(request, accessors.Setter); } } } } } // If the signature matches the TypeDefinition, including some or all containing // types and namespaces, returns a non-negative value indicating the arity of the // containing types that were not specified in the signature; otherwise returns -1. // For instance, "C<T>.D" will return 1 matching against metadata type N.M.A<T>.B.C<U>.D, // where N.M is a namespace and A<T>, B, C<U>, D are nested types. The value 1 // is the arity of the containing types A<T>.B that were missing from the signature. // "C<T>.D" will not match C<T> or C<T>.D.E since the match must include the entire // signature, from nested TypeDefinition, out. private int CompareToTypeDefinition(TypeDefinition typeDef, Name signature) { if (signature == null) { return typeDef.GetGenericParameters().Count; } QualifiedName qualifiedName; ImmutableArray<string> typeParameters; GetNameAndTypeParameters(signature, out qualifiedName, out typeParameters); if (!MatchesTypeName(typeDef, qualifiedName.Name)) { return -1; } var declaringTypeHandle = typeDef.GetDeclaringType(); var declaringType = declaringTypeHandle.IsNil ? default(TypeDefinition) : _reader.GetTypeDefinition(declaringTypeHandle); int declaringTypeParameterCount = declaringTypeHandle.IsNil ? 0 : declaringType.GetGenericParameters().Count; if (!MatchesTypeParameterCount(typeParameters, typeDef.GetGenericParameters(), declaringTypeParameterCount)) { return -1; } var qualifier = qualifiedName.Qualifier; if (declaringTypeHandle.IsNil) { // Compare namespace. return MatchesNamespace(typeDef, qualifier) ? 0 : -1; } else { // Compare declaring type. return CompareToTypeDefinition(declaringType, qualifier); } } private bool MatchesNamespace(TypeDefinition typeDef, Name signature) { if (signature == null) { return true; } var namespaceName = _reader.GetString(typeDef.Namespace); if (string.IsNullOrEmpty(namespaceName)) { return false; } var parts = namespaceName.Split('.'); for (int index = parts.Length - 1; index >= 0; index--) { if (signature == null) { return true; } var qualifiedName = signature as QualifiedName; if (qualifiedName == null) { return false; } var part = parts[index]; if (!_stringComparer.Equals(qualifiedName.Name, part)) { return false; } signature = qualifiedName.Qualifier; } return signature == null; } private bool MatchesTypeName(TypeDefinition typeDef, string name) { var typeName = RemoveAritySeparatorIfAny(_reader.GetString(typeDef.Name)); return _stringComparer.Equals(typeName, name); } private bool MatchesMethod( TypeDefinition typeDef, MethodDefinition methodDef, Name typeName, string methodName, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<string> methodTypeParameters, ImmutableArray<ParameterSignature> methodParameters) { if ((methodDef.Attributes & MethodAttributes.RTSpecialName) != 0) { if (!_reader.StringComparer.Equals(methodDef.Name, ".ctor", ignoreCase: false)) { // Unhandled special name. return false; } if (!MatchesTypeName(typeDef, methodName)) { return false; } } else if (!_reader.StringComparer.Equals(methodDef.Name, methodName, _ignoreCase)) { return false; } if (!MatchesTypeParameterCount(methodTypeParameters, methodDef.GetGenericParameters(), offset: 0)) { return false; } if (methodParameters.IsDefault) { return true; } return MatchesParameters(methodDef, allTypeParameters, containingArity, methodTypeParameters, methodParameters); } private bool MatchesProperty( TypeDefinition typeDef, PropertyDefinition propertyDef, Name typeName, string propertyName, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<ParameterSignature> propertyParameters) { if (!_reader.StringComparer.Equals(propertyDef.Name, propertyName, _ignoreCase)) { return false; } if (propertyParameters.IsDefault) { return true; } if (propertyParameters.Length == 0) { // Parameter-less properties should be specified // with no parameter list. return false; } // Match parameters against getter. Not supporting // matching against setter for write-only properties. var methodHandle = propertyDef.GetAccessors().Getter; if (methodHandle.IsNil) { return false; } var methodDef = _reader.GetMethodDefinition(methodHandle); return MatchesParameters(methodDef, allTypeParameters, containingArity, ImmutableArray<string>.Empty, propertyParameters); } private ImmutableArray<string> GetAllGenericTypeParameters(Name typeName) { var builder = ImmutableArray.CreateBuilder<string>(); GetAllGenericTypeParameters(typeName, builder); return builder.ToImmutable(); } private void GetAllGenericTypeParameters(Name typeName, ImmutableArray<string>.Builder builder) { if (typeName == null) { return; } QualifiedName qualifiedName; ImmutableArray<string> typeParameters; GetNameAndTypeParameters(typeName, out qualifiedName, out typeParameters); GetAllGenericTypeParameters(qualifiedName.Qualifier, builder); builder.AddRange(typeParameters); } private bool MatchesParameters( MethodDefinition methodDef, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<string> methodTypeParameters, ImmutableArray<ParameterSignature> methodParameters) { ImmutableArray<ParameterSignature> parameters; try { var decoder = new MetadataDecoder(_reader, allTypeParameters, containingArity, methodTypeParameters); parameters = decoder.DecodeParameters(methodDef); } catch (NotSupportedException) { return false; } catch (BadImageFormatException) { return false; } return methodParameters.SequenceEqual(parameters, MatchesParameter); } private void OnFunctionResolved( TRequest request, MethodDefinitionHandle handle) { Debug.Assert(!handle.IsNil); _onFunctionResolved(_module, request, token: MetadataTokens.GetToken(handle), version: 1, ilOffset: 0); } private void OnAccessorResolved( TRequest request, MethodDefinitionHandle handle) { if (handle.IsNil) { return; } var methodDef = _reader.GetMethodDefinition(handle); if (IsResolvableMethod(methodDef)) { OnFunctionResolved(request, handle); } } private static bool MatchesTypeParameterCount(ImmutableArray<string> typeArguments, GenericParameterHandleCollection typeParameters, int offset) { return typeArguments.Length == typeParameters.Count - offset; } // parameterA from string signature, parameterB from metadata. private bool MatchesParameter(ParameterSignature parameterA, ParameterSignature parameterB) { return MatchesType(parameterA.Type, parameterB.Type) && parameterA.IsByRef == parameterB.IsByRef; } // typeA from string signature, typeB from metadata. private bool MatchesType(TypeSignature typeA, TypeSignature typeB) { if (typeA.Kind != typeB.Kind) { return false; } switch (typeA.Kind) { case TypeSignatureKind.GenericType: { var genericA = (GenericTypeSignature)typeA; var genericB = (GenericTypeSignature)typeB; return MatchesType(genericA.QualifiedName, genericB.QualifiedName) && genericA.TypeArguments.SequenceEqual(genericB.TypeArguments, MatchesType); } case TypeSignatureKind.QualifiedType: { var qualifiedA = (QualifiedTypeSignature)typeA; var qualifiedB = (QualifiedTypeSignature)typeB; // Metadata signature may be more qualified than the // string signature but still considered a match // (e.g.: "B<U>.C" should match N.A<T>.B<U>.C). return (qualifiedA.Qualifier == null || (qualifiedB.Qualifier != null && MatchesType(qualifiedA.Qualifier, qualifiedB.Qualifier))) && _stringComparer.Equals(qualifiedA.Name, qualifiedB.Name); } case TypeSignatureKind.ArrayType: { var arrayA = (ArrayTypeSignature)typeA; var arrayB = (ArrayTypeSignature)typeB; return MatchesType(arrayA.ElementType, arrayB.ElementType) && arrayA.Rank == arrayB.Rank; } case TypeSignatureKind.PointerType: { var pointerA = (PointerTypeSignature)typeA; var pointerB = (PointerTypeSignature)typeB; return MatchesType(pointerA.PointedAtType, pointerB.PointedAtType); } default: throw ExceptionUtilities.UnexpectedValue(typeA.Kind); } } private static void GetNameAndTypeParameters( Name name, out QualifiedName qualifiedName, out ImmutableArray<string> typeParameters) { switch (name.Kind) { case NameKind.GenericName: { var genericName = (GenericName)name; qualifiedName = genericName.QualifiedName; typeParameters = genericName.TypeParameters; } break; case NameKind.QualifiedName: { qualifiedName = (QualifiedName)name; typeParameters = ImmutableArray<string>.Empty; } break; default: throw ExceptionUtilities.UnexpectedValue(name.Kind); } } private static bool IsResolvableMethod(MethodDefinition methodDef) { return (methodDef.Attributes & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0; } private static string RemoveAritySeparatorIfAny(string typeName) { int index = typeName.LastIndexOf('`'); return (index < 0) ? typeName : typeName.Substring(0, 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. #nullable disable using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal delegate void OnFunctionResolvedDelegate<TModule, TRequest>(TModule module, TRequest request, int token, int version, int ilOffset); internal sealed class MetadataResolver<TProcess, TModule, TRequest> where TProcess : class where TModule : class where TRequest : class { private readonly TProcess _process; private readonly TModule _module; private readonly MetadataReader _reader; private readonly StringComparer _stringComparer; // for comparing strings private readonly bool _ignoreCase; // for comparing strings to strings represented with StringHandles private readonly OnFunctionResolvedDelegate<TModule, TRequest> _onFunctionResolved; internal MetadataResolver( TProcess process, TModule module, MetadataReader reader, bool ignoreCase, OnFunctionResolvedDelegate<TModule, TRequest> onFunctionResolved) { _process = process; _module = module; _reader = reader; _stringComparer = ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; _ignoreCase = ignoreCase; _onFunctionResolved = onFunctionResolved; } internal void Resolve(TRequest request, RequestSignature signature) { QualifiedName qualifiedTypeName; ImmutableArray<string> memberTypeParameters; GetNameAndTypeParameters(signature.MemberName, out qualifiedTypeName, out memberTypeParameters); var typeName = qualifiedTypeName.Qualifier; var memberName = qualifiedTypeName.Name; var memberParameters = signature.Parameters; var allTypeParameters = GetAllGenericTypeParameters(typeName); foreach (var typeHandle in _reader.TypeDefinitions) { var typeDef = _reader.GetTypeDefinition(typeHandle); int containingArity = CompareToTypeDefinition(typeDef, typeName); if (containingArity < 0) { continue; } // Visit methods. foreach (var methodHandle in typeDef.GetMethods()) { var methodDef = _reader.GetMethodDefinition(methodHandle); if (!IsResolvableMethod(methodDef)) { continue; } if (MatchesMethod(typeDef, methodDef, typeName, memberName, allTypeParameters, containingArity, memberTypeParameters, memberParameters)) { OnFunctionResolved(request, methodHandle); } } if (memberTypeParameters.IsEmpty) { // Visit properties. foreach (var propertyHandle in typeDef.GetProperties()) { var propertyDef = _reader.GetPropertyDefinition(propertyHandle); if (MatchesProperty(typeDef, propertyDef, typeName, memberName, allTypeParameters, containingArity, memberParameters)) { var accessors = propertyDef.GetAccessors(); OnAccessorResolved(request, accessors.Getter); OnAccessorResolved(request, accessors.Setter); } } } } } // If the signature matches the TypeDefinition, including some or all containing // types and namespaces, returns a non-negative value indicating the arity of the // containing types that were not specified in the signature; otherwise returns -1. // For instance, "C<T>.D" will return 1 matching against metadata type N.M.A<T>.B.C<U>.D, // where N.M is a namespace and A<T>, B, C<U>, D are nested types. The value 1 // is the arity of the containing types A<T>.B that were missing from the signature. // "C<T>.D" will not match C<T> or C<T>.D.E since the match must include the entire // signature, from nested TypeDefinition, out. private int CompareToTypeDefinition(TypeDefinition typeDef, Name signature) { if (signature == null) { return typeDef.GetGenericParameters().Count; } QualifiedName qualifiedName; ImmutableArray<string> typeParameters; GetNameAndTypeParameters(signature, out qualifiedName, out typeParameters); if (!MatchesTypeName(typeDef, qualifiedName.Name)) { return -1; } var declaringTypeHandle = typeDef.GetDeclaringType(); var declaringType = declaringTypeHandle.IsNil ? default(TypeDefinition) : _reader.GetTypeDefinition(declaringTypeHandle); int declaringTypeParameterCount = declaringTypeHandle.IsNil ? 0 : declaringType.GetGenericParameters().Count; if (!MatchesTypeParameterCount(typeParameters, typeDef.GetGenericParameters(), declaringTypeParameterCount)) { return -1; } var qualifier = qualifiedName.Qualifier; if (declaringTypeHandle.IsNil) { // Compare namespace. return MatchesNamespace(typeDef, qualifier) ? 0 : -1; } else { // Compare declaring type. return CompareToTypeDefinition(declaringType, qualifier); } } private bool MatchesNamespace(TypeDefinition typeDef, Name signature) { if (signature == null) { return true; } var namespaceName = _reader.GetString(typeDef.Namespace); if (string.IsNullOrEmpty(namespaceName)) { return false; } var parts = namespaceName.Split('.'); for (int index = parts.Length - 1; index >= 0; index--) { if (signature == null) { return true; } var qualifiedName = signature as QualifiedName; if (qualifiedName == null) { return false; } var part = parts[index]; if (!_stringComparer.Equals(qualifiedName.Name, part)) { return false; } signature = qualifiedName.Qualifier; } return signature == null; } private bool MatchesTypeName(TypeDefinition typeDef, string name) { var typeName = RemoveAritySeparatorIfAny(_reader.GetString(typeDef.Name)); return _stringComparer.Equals(typeName, name); } private bool MatchesMethod( TypeDefinition typeDef, MethodDefinition methodDef, Name typeName, string methodName, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<string> methodTypeParameters, ImmutableArray<ParameterSignature> methodParameters) { if ((methodDef.Attributes & MethodAttributes.RTSpecialName) != 0) { if (!_reader.StringComparer.Equals(methodDef.Name, ".ctor", ignoreCase: false)) { // Unhandled special name. return false; } if (!MatchesTypeName(typeDef, methodName)) { return false; } } else if (!_reader.StringComparer.Equals(methodDef.Name, methodName, _ignoreCase)) { return false; } if (!MatchesTypeParameterCount(methodTypeParameters, methodDef.GetGenericParameters(), offset: 0)) { return false; } if (methodParameters.IsDefault) { return true; } return MatchesParameters(methodDef, allTypeParameters, containingArity, methodTypeParameters, methodParameters); } private bool MatchesProperty( TypeDefinition typeDef, PropertyDefinition propertyDef, Name typeName, string propertyName, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<ParameterSignature> propertyParameters) { if (!_reader.StringComparer.Equals(propertyDef.Name, propertyName, _ignoreCase)) { return false; } if (propertyParameters.IsDefault) { return true; } if (propertyParameters.Length == 0) { // Parameter-less properties should be specified // with no parameter list. return false; } // Match parameters against getter. Not supporting // matching against setter for write-only properties. var methodHandle = propertyDef.GetAccessors().Getter; if (methodHandle.IsNil) { return false; } var methodDef = _reader.GetMethodDefinition(methodHandle); return MatchesParameters(methodDef, allTypeParameters, containingArity, ImmutableArray<string>.Empty, propertyParameters); } private ImmutableArray<string> GetAllGenericTypeParameters(Name typeName) { var builder = ImmutableArray.CreateBuilder<string>(); GetAllGenericTypeParameters(typeName, builder); return builder.ToImmutable(); } private void GetAllGenericTypeParameters(Name typeName, ImmutableArray<string>.Builder builder) { if (typeName == null) { return; } QualifiedName qualifiedName; ImmutableArray<string> typeParameters; GetNameAndTypeParameters(typeName, out qualifiedName, out typeParameters); GetAllGenericTypeParameters(qualifiedName.Qualifier, builder); builder.AddRange(typeParameters); } private bool MatchesParameters( MethodDefinition methodDef, ImmutableArray<string> allTypeParameters, int containingArity, ImmutableArray<string> methodTypeParameters, ImmutableArray<ParameterSignature> methodParameters) { ImmutableArray<ParameterSignature> parameters; try { var decoder = new MetadataDecoder(_reader, allTypeParameters, containingArity, methodTypeParameters); parameters = decoder.DecodeParameters(methodDef); } catch (NotSupportedException) { return false; } catch (BadImageFormatException) { return false; } return methodParameters.SequenceEqual(parameters, MatchesParameter); } private void OnFunctionResolved( TRequest request, MethodDefinitionHandle handle) { Debug.Assert(!handle.IsNil); _onFunctionResolved(_module, request, token: MetadataTokens.GetToken(handle), version: 1, ilOffset: 0); } private void OnAccessorResolved( TRequest request, MethodDefinitionHandle handle) { if (handle.IsNil) { return; } var methodDef = _reader.GetMethodDefinition(handle); if (IsResolvableMethod(methodDef)) { OnFunctionResolved(request, handle); } } private static bool MatchesTypeParameterCount(ImmutableArray<string> typeArguments, GenericParameterHandleCollection typeParameters, int offset) { return typeArguments.Length == typeParameters.Count - offset; } // parameterA from string signature, parameterB from metadata. private bool MatchesParameter(ParameterSignature parameterA, ParameterSignature parameterB) { return MatchesType(parameterA.Type, parameterB.Type) && parameterA.IsByRef == parameterB.IsByRef; } // typeA from string signature, typeB from metadata. private bool MatchesType(TypeSignature typeA, TypeSignature typeB) { if (typeA.Kind != typeB.Kind) { return false; } switch (typeA.Kind) { case TypeSignatureKind.GenericType: { var genericA = (GenericTypeSignature)typeA; var genericB = (GenericTypeSignature)typeB; return MatchesType(genericA.QualifiedName, genericB.QualifiedName) && genericA.TypeArguments.SequenceEqual(genericB.TypeArguments, MatchesType); } case TypeSignatureKind.QualifiedType: { var qualifiedA = (QualifiedTypeSignature)typeA; var qualifiedB = (QualifiedTypeSignature)typeB; // Metadata signature may be more qualified than the // string signature but still considered a match // (e.g.: "B<U>.C" should match N.A<T>.B<U>.C). return (qualifiedA.Qualifier == null || (qualifiedB.Qualifier != null && MatchesType(qualifiedA.Qualifier, qualifiedB.Qualifier))) && _stringComparer.Equals(qualifiedA.Name, qualifiedB.Name); } case TypeSignatureKind.ArrayType: { var arrayA = (ArrayTypeSignature)typeA; var arrayB = (ArrayTypeSignature)typeB; return MatchesType(arrayA.ElementType, arrayB.ElementType) && arrayA.Rank == arrayB.Rank; } case TypeSignatureKind.PointerType: { var pointerA = (PointerTypeSignature)typeA; var pointerB = (PointerTypeSignature)typeB; return MatchesType(pointerA.PointedAtType, pointerB.PointedAtType); } default: throw ExceptionUtilities.UnexpectedValue(typeA.Kind); } } private static void GetNameAndTypeParameters( Name name, out QualifiedName qualifiedName, out ImmutableArray<string> typeParameters) { switch (name.Kind) { case NameKind.GenericName: { var genericName = (GenericName)name; qualifiedName = genericName.QualifiedName; typeParameters = genericName.TypeParameters; } break; case NameKind.QualifiedName: { qualifiedName = (QualifiedName)name; typeParameters = ImmutableArray<string>.Empty; } break; default: throw ExceptionUtilities.UnexpectedValue(name.Kind); } } private static bool IsResolvableMethod(MethodDefinition methodDef) { return (methodDef.Attributes & (MethodAttributes.Abstract | MethodAttributes.PinvokeImpl)) == 0; } private static string RemoveAritySeparatorIfAny(string typeName) { int index = typeName.LastIndexOf('`'); return (index < 0) ? typeName : typeName.Substring(0, index); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/ChangeSignature/Parameter.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; namespace Microsoft.CodeAnalysis.ChangeSignature { /// <summary> /// Base type for Parameter information, whether the parameter /// is preexisting or new. /// </summary> internal abstract class Parameter { public abstract bool HasDefaultValue { get; } public abstract string Name { get; } } internal sealed class ExistingParameter : Parameter { public IParameterSymbol Symbol { get; } public ExistingParameter(IParameterSymbol param) { Symbol = param; } public override bool HasDefaultValue => Symbol.HasExplicitDefaultValue; public override string Name => Symbol.Name; } internal sealed class AddedParameter : Parameter { public AddedParameter( ITypeSymbol type, string typeName, string name, CallSiteKind callSiteKind, string callSiteValue = "", bool isRequired = true, string defaultValue = "", bool typeBinds = true) { Type = type; TypeBinds = typeBinds; TypeName = typeName; Name = name; CallSiteValue = callSiteValue; IsRequired = isRequired; DefaultValue = defaultValue; CallSiteKind = callSiteKind; // Populate the call site text for the UI switch (CallSiteKind) { case CallSiteKind.Value: case CallSiteKind.ValueWithName: CallSiteValue = callSiteValue; break; case CallSiteKind.Todo: CallSiteValue = FeaturesResources.ChangeSignature_NewParameterIntroduceTODOVariable; break; case CallSiteKind.Omitted: CallSiteValue = FeaturesResources.ChangeSignature_NewParameterOmitValue; break; case CallSiteKind.Inferred: CallSiteValue = FeaturesResources.ChangeSignature_NewParameterInferValue; break; default: throw ExceptionUtilities.Unreachable; } } public override string Name { get; } public override bool HasDefaultValue => !string.IsNullOrWhiteSpace(DefaultValue); public ITypeSymbol Type { get; } public string TypeName { get; } public bool TypeBinds { get; } public CallSiteKind CallSiteKind { get; } /// <summary> /// Display string for the Call Site column in the Change Signature dialog. /// </summary> public string CallSiteValue { get; } /// <summary> /// True if required, false if optional with a default value. /// </summary> public bool IsRequired { get; } /// <summary> /// Value to use in the declaration of an optional parameter. /// E.g. the "3" in M(int x = 3); /// </summary> public string DefaultValue { get; } // For test purposes: to display assert failure details in tests. public override string ToString() => $"{Type.ToDisplayString(new SymbolDisplayFormat(genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters))} {Name} ({CallSiteValue})"; } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.ChangeSignature { /// <summary> /// Base type for Parameter information, whether the parameter /// is preexisting or new. /// </summary> internal abstract class Parameter { public abstract bool HasDefaultValue { get; } public abstract string Name { get; } } internal sealed class ExistingParameter : Parameter { public IParameterSymbol Symbol { get; } public ExistingParameter(IParameterSymbol param) { Symbol = param; } public override bool HasDefaultValue => Symbol.HasExplicitDefaultValue; public override string Name => Symbol.Name; } internal sealed class AddedParameter : Parameter { public AddedParameter( ITypeSymbol type, string typeName, string name, CallSiteKind callSiteKind, string callSiteValue = "", bool isRequired = true, string defaultValue = "", bool typeBinds = true) { Type = type; TypeBinds = typeBinds; TypeName = typeName; Name = name; CallSiteValue = callSiteValue; IsRequired = isRequired; DefaultValue = defaultValue; CallSiteKind = callSiteKind; // Populate the call site text for the UI switch (CallSiteKind) { case CallSiteKind.Value: case CallSiteKind.ValueWithName: CallSiteValue = callSiteValue; break; case CallSiteKind.Todo: CallSiteValue = FeaturesResources.ChangeSignature_NewParameterIntroduceTODOVariable; break; case CallSiteKind.Omitted: CallSiteValue = FeaturesResources.ChangeSignature_NewParameterOmitValue; break; case CallSiteKind.Inferred: CallSiteValue = FeaturesResources.ChangeSignature_NewParameterInferValue; break; default: throw ExceptionUtilities.Unreachable; } } public override string Name { get; } public override bool HasDefaultValue => !string.IsNullOrWhiteSpace(DefaultValue); public ITypeSymbol Type { get; } public string TypeName { get; } public bool TypeBinds { get; } public CallSiteKind CallSiteKind { get; } /// <summary> /// Display string for the Call Site column in the Change Signature dialog. /// </summary> public string CallSiteValue { get; } /// <summary> /// True if required, false if optional with a default value. /// </summary> public bool IsRequired { get; } /// <summary> /// Value to use in the declaration of an optional parameter. /// E.g. the "3" in M(int x = 3); /// </summary> public string DefaultValue { get; } // For test purposes: to display assert failure details in tests. public override string ToString() => $"{Type.ToDisplayString(new SymbolDisplayFormat(genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters))} {Name} ({CallSiteValue})"; } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/CodeGen/SequencePointList.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 Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// Maintains a list of sequence points in a space efficient way. Most of the time sequence points /// occur in the same syntax tree, so optimize for that case. Store a sequence point as an offset, and /// position in a syntax tree, then translate to CCI format only on demand. /// /// Use a ArrayBuilder{RawSequencePoint} to create. /// </summary> internal class SequencePointList { private readonly SyntaxTree _tree; private readonly OffsetAndSpan[] _points; private SequencePointList _next; // Linked list of all points. // No sequence points. private static readonly SequencePointList s_empty = new SequencePointList(); // Construct a list with no sequence points. private SequencePointList() { _points = Array.Empty<OffsetAndSpan>(); } // Construct a list with sequence points from exactly one syntax tree. private SequencePointList(SyntaxTree tree, OffsetAndSpan[] points) { _tree = tree; _points = points; } /// <summary> /// Create a SequencePointList with the raw sequence points from an ArrayBuilder. /// A linked list of instances for each syntax tree is created (almost always of length one). /// </summary> public static SequencePointList Create(ArrayBuilder<RawSequencePoint> seqPointBuilder, ILBuilder builder) { if (seqPointBuilder.Count == 0) { return SequencePointList.s_empty; } SequencePointList first = null, current = null; int totalPoints = seqPointBuilder.Count; int last = 0; for (int i = 1; i <= totalPoints; ++i) { if (i == totalPoints || seqPointBuilder[i].SyntaxTree != seqPointBuilder[i - 1].SyntaxTree) { // Create a new list SequencePointList next = new SequencePointList(seqPointBuilder[i - 1].SyntaxTree, GetSubArray(seqPointBuilder, last, i - last, builder)); last = i; // Link together with any additional. if (current == null) { first = current = next; } else { current._next = next; current = next; } } } return first; } public bool IsEmpty { get { return _next == null && _points.Length == 0; } } private static OffsetAndSpan[] GetSubArray(ArrayBuilder<RawSequencePoint> seqPointBuilder, int start, int length, ILBuilder builder) { OffsetAndSpan[] result = new OffsetAndSpan[length]; for (int i = 0; i < result.Length; i++) { RawSequencePoint point = seqPointBuilder[i + start]; int ilOffset = builder.GetILOffsetFromMarker(point.ILMarker); Debug.Assert(ilOffset >= 0); result[i] = new OffsetAndSpan(ilOffset, point.Span); } return result; } /// <summary> /// Get all the sequence points, possibly mapping them using #line/ExternalSource directives, and mapping /// file names to debug documents with the given mapping function. /// </summary> /// <param name="documentProvider">Function that maps file paths to CCI debug documents</param> /// <param name="builder">where sequence points should be deposited</param> public void GetSequencePoints( DebugDocumentProvider documentProvider, ArrayBuilder<Cci.SequencePoint> builder) { bool lastPathIsMapped = false; string lastPath = null; Cci.DebugSourceDocument lastDebugDocument = null; FileLinePositionSpan? firstReal = FindFirstRealSequencePoint(); if (!firstReal.HasValue) { return; } lastPath = firstReal.Value.Path; lastPathIsMapped = firstReal.Value.HasMappedPath; lastDebugDocument = documentProvider(lastPath, basePath: lastPathIsMapped ? this._tree.FilePath : null); SequencePointList current = this; while (current != null) { SyntaxTree currentTree = current._tree; foreach (var offsetAndSpan in current._points) { TextSpan span = offsetAndSpan.Span; // if it's a hidden sequence point, or a sequence point with syntax that points to a position that is inside // of a hidden region (can be defined with #line hidden (C#) or implicitly by #ExternalSource (VB), make it // a hidden sequence point. bool isHidden = span == RawSequencePoint.HiddenSequencePointSpan; FileLinePositionSpan fileLinePositionSpan = default; if (!isHidden) { fileLinePositionSpan = currentTree.GetMappedLineSpanAndVisibility(span, out isHidden); } if (isHidden) { if (lastPath == null) { lastPath = currentTree.FilePath; lastDebugDocument = documentProvider(lastPath, basePath: null); } if (lastDebugDocument != null) { builder.Add(new Cci.SequencePoint( lastDebugDocument, offset: offsetAndSpan.Offset, startLine: Cci.SequencePoint.HiddenLine, startColumn: 0, endLine: Cci.SequencePoint.HiddenLine, endColumn: 0)); } } else { if (lastPath != fileLinePositionSpan.Path || lastPathIsMapped != fileLinePositionSpan.HasMappedPath) { lastPath = fileLinePositionSpan.Path; lastPathIsMapped = fileLinePositionSpan.HasMappedPath; lastDebugDocument = documentProvider(lastPath, basePath: lastPathIsMapped ? currentTree.FilePath : null); } if (lastDebugDocument != null) { int startLine = (fileLinePositionSpan.StartLinePosition.Line == -1) ? 0 : fileLinePositionSpan.StartLinePosition.Line + 1; int endLine = (fileLinePositionSpan.EndLinePosition.Line == -1) ? 0 : fileLinePositionSpan.EndLinePosition.Line + 1; int startColumn = fileLinePositionSpan.StartLinePosition.Character + 1; int endColumn = fileLinePositionSpan.EndLinePosition.Character + 1; // Trim column number if necessary. // Column must be in range [0, 0xffff) and end column must be greater than start column if on the same line. // The Portable PDB specifies 0x10000, but System.Reflection.Metadata reader has an off-by-one error. // Windows PDBs allow the same range. const int MaxColumn = ushort.MaxValue - 1; if (startColumn > MaxColumn) { startColumn = (startLine == endLine) ? MaxColumn - 1 : MaxColumn; } if (endColumn > MaxColumn) { endColumn = MaxColumn; } builder.Add(new Cci.SequencePoint( lastDebugDocument, offset: offsetAndSpan.Offset, startLine: startLine, startColumn: (ushort)startColumn, endLine: endLine, endColumn: (ushort)endColumn )); } } } current = current._next; } } // Find the document for the first non-hidden sequence point (issue #4370) // Returns null if a real sequence point was not found. private FileLinePositionSpan? FindFirstRealSequencePoint() { SequencePointList current = this; while (current != null) { foreach (var offsetAndSpan in current._points) { TextSpan span = offsetAndSpan.Span; bool isHidden = span == RawSequencePoint.HiddenSequencePointSpan; if (!isHidden) { FileLinePositionSpan fileLinePositionSpan = current._tree.GetMappedLineSpanAndVisibility(span, out isHidden); if (!isHidden) { return fileLinePositionSpan; } } } current = current._next; } return null; } /// <summary> /// Represents the combination of an IL offset and a source text span. /// </summary> private struct OffsetAndSpan { public readonly int Offset; public readonly TextSpan Span; public OffsetAndSpan(int offset, TextSpan span) { this.Offset = offset; this.Span = span; } } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeGen { /// <summary> /// Maintains a list of sequence points in a space efficient way. Most of the time sequence points /// occur in the same syntax tree, so optimize for that case. Store a sequence point as an offset, and /// position in a syntax tree, then translate to CCI format only on demand. /// /// Use a ArrayBuilder{RawSequencePoint} to create. /// </summary> internal class SequencePointList { private readonly SyntaxTree _tree; private readonly OffsetAndSpan[] _points; private SequencePointList _next; // Linked list of all points. // No sequence points. private static readonly SequencePointList s_empty = new SequencePointList(); // Construct a list with no sequence points. private SequencePointList() { _points = Array.Empty<OffsetAndSpan>(); } // Construct a list with sequence points from exactly one syntax tree. private SequencePointList(SyntaxTree tree, OffsetAndSpan[] points) { _tree = tree; _points = points; } /// <summary> /// Create a SequencePointList with the raw sequence points from an ArrayBuilder. /// A linked list of instances for each syntax tree is created (almost always of length one). /// </summary> public static SequencePointList Create(ArrayBuilder<RawSequencePoint> seqPointBuilder, ILBuilder builder) { if (seqPointBuilder.Count == 0) { return SequencePointList.s_empty; } SequencePointList first = null, current = null; int totalPoints = seqPointBuilder.Count; int last = 0; for (int i = 1; i <= totalPoints; ++i) { if (i == totalPoints || seqPointBuilder[i].SyntaxTree != seqPointBuilder[i - 1].SyntaxTree) { // Create a new list SequencePointList next = new SequencePointList(seqPointBuilder[i - 1].SyntaxTree, GetSubArray(seqPointBuilder, last, i - last, builder)); last = i; // Link together with any additional. if (current == null) { first = current = next; } else { current._next = next; current = next; } } } return first; } public bool IsEmpty { get { return _next == null && _points.Length == 0; } } private static OffsetAndSpan[] GetSubArray(ArrayBuilder<RawSequencePoint> seqPointBuilder, int start, int length, ILBuilder builder) { OffsetAndSpan[] result = new OffsetAndSpan[length]; for (int i = 0; i < result.Length; i++) { RawSequencePoint point = seqPointBuilder[i + start]; int ilOffset = builder.GetILOffsetFromMarker(point.ILMarker); Debug.Assert(ilOffset >= 0); result[i] = new OffsetAndSpan(ilOffset, point.Span); } return result; } /// <summary> /// Get all the sequence points, possibly mapping them using #line/ExternalSource directives, and mapping /// file names to debug documents with the given mapping function. /// </summary> /// <param name="documentProvider">Function that maps file paths to CCI debug documents</param> /// <param name="builder">where sequence points should be deposited</param> public void GetSequencePoints( DebugDocumentProvider documentProvider, ArrayBuilder<Cci.SequencePoint> builder) { bool lastPathIsMapped = false; string lastPath = null; Cci.DebugSourceDocument lastDebugDocument = null; FileLinePositionSpan? firstReal = FindFirstRealSequencePoint(); if (!firstReal.HasValue) { return; } lastPath = firstReal.Value.Path; lastPathIsMapped = firstReal.Value.HasMappedPath; lastDebugDocument = documentProvider(lastPath, basePath: lastPathIsMapped ? this._tree.FilePath : null); SequencePointList current = this; while (current != null) { SyntaxTree currentTree = current._tree; foreach (var offsetAndSpan in current._points) { TextSpan span = offsetAndSpan.Span; // if it's a hidden sequence point, or a sequence point with syntax that points to a position that is inside // of a hidden region (can be defined with #line hidden (C#) or implicitly by #ExternalSource (VB), make it // a hidden sequence point. bool isHidden = span == RawSequencePoint.HiddenSequencePointSpan; FileLinePositionSpan fileLinePositionSpan = default; if (!isHidden) { fileLinePositionSpan = currentTree.GetMappedLineSpanAndVisibility(span, out isHidden); } if (isHidden) { if (lastPath == null) { lastPath = currentTree.FilePath; lastDebugDocument = documentProvider(lastPath, basePath: null); } if (lastDebugDocument != null) { builder.Add(new Cci.SequencePoint( lastDebugDocument, offset: offsetAndSpan.Offset, startLine: Cci.SequencePoint.HiddenLine, startColumn: 0, endLine: Cci.SequencePoint.HiddenLine, endColumn: 0)); } } else { if (lastPath != fileLinePositionSpan.Path || lastPathIsMapped != fileLinePositionSpan.HasMappedPath) { lastPath = fileLinePositionSpan.Path; lastPathIsMapped = fileLinePositionSpan.HasMappedPath; lastDebugDocument = documentProvider(lastPath, basePath: lastPathIsMapped ? currentTree.FilePath : null); } if (lastDebugDocument != null) { int startLine = (fileLinePositionSpan.StartLinePosition.Line == -1) ? 0 : fileLinePositionSpan.StartLinePosition.Line + 1; int endLine = (fileLinePositionSpan.EndLinePosition.Line == -1) ? 0 : fileLinePositionSpan.EndLinePosition.Line + 1; int startColumn = fileLinePositionSpan.StartLinePosition.Character + 1; int endColumn = fileLinePositionSpan.EndLinePosition.Character + 1; // Trim column number if necessary. // Column must be in range [0, 0xffff) and end column must be greater than start column if on the same line. // The Portable PDB specifies 0x10000, but System.Reflection.Metadata reader has an off-by-one error. // Windows PDBs allow the same range. const int MaxColumn = ushort.MaxValue - 1; if (startColumn > MaxColumn) { startColumn = (startLine == endLine) ? MaxColumn - 1 : MaxColumn; } if (endColumn > MaxColumn) { endColumn = MaxColumn; } builder.Add(new Cci.SequencePoint( lastDebugDocument, offset: offsetAndSpan.Offset, startLine: startLine, startColumn: (ushort)startColumn, endLine: endLine, endColumn: (ushort)endColumn )); } } } current = current._next; } } // Find the document for the first non-hidden sequence point (issue #4370) // Returns null if a real sequence point was not found. private FileLinePositionSpan? FindFirstRealSequencePoint() { SequencePointList current = this; while (current != null) { foreach (var offsetAndSpan in current._points) { TextSpan span = offsetAndSpan.Span; bool isHidden = span == RawSequencePoint.HiddenSequencePointSpan; if (!isHidden) { FileLinePositionSpan fileLinePositionSpan = current._tree.GetMappedLineSpanAndVisibility(span, out isHidden); if (!isHidden) { return fileLinePositionSpan; } } } current = current._next; } return null; } /// <summary> /// Represents the combination of an IL offset and a source text span. /// </summary> private struct OffsetAndSpan { public readonly int Offset; public readonly TextSpan Span; public OffsetAndSpan(int offset, TextSpan span) { this.Offset = offset; this.Span = span; } } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./docs/README.md
README ====== This file is a placeholder. This directory will contain public documentation.
README ====== This file is a placeholder. This directory will contain public documentation.
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Symbols/Attributes/EarlyDecodeWellKnownAttributeArguments.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 Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Contains common arguments to Symbol.EarlyDecodeWellKnownAttribute method in both the language compilers. /// </summary> internal struct EarlyDecodeWellKnownAttributeArguments<TEarlyBinder, TNamedTypeSymbol, TAttributeSyntax, TAttributeLocation> where TNamedTypeSymbol : INamedTypeSymbolInternal where TAttributeSyntax : SyntaxNode { /// <summary> /// Object to store the decoded data from early bound well-known attributes. /// Created lazily only when some decoded data needs to be stored, null otherwise. /// </summary> private EarlyWellKnownAttributeData _lazyDecodeData; /// <summary> /// Gets or creates the decoded data object. /// </summary> /// <remarks> /// This method must be called only when some decoded data will be stored into it subsequently. /// </remarks> public T GetOrCreateData<T>() where T : EarlyWellKnownAttributeData, new() { if (_lazyDecodeData == null) { _lazyDecodeData = new T(); } return (T)_lazyDecodeData; } /// <summary> /// Returns true if some decoded data has been stored into <see cref="_lazyDecodeData"/>. /// </summary> public bool HasDecodedData { get { if (_lazyDecodeData != null) { _lazyDecodeData.VerifyDataStored(expected: true); return true; } return false; } } /// <summary> /// Gets the stored decoded data. /// </summary> /// <remarks> /// Assumes <see cref="HasDecodedData"/> is true. /// </remarks> public EarlyWellKnownAttributeData DecodedData { get { Debug.Assert(this.HasDecodedData); return _lazyDecodeData; } } /// <summary> /// Binder to bind early well-known attributes. /// </summary> public TEarlyBinder Binder { get; set; } /// <summary> /// Bound type of the attribute to decode. /// </summary> public TNamedTypeSymbol AttributeType { get; set; } /// <summary> /// Syntax of the attribute to decode. /// </summary> public TAttributeSyntax AttributeSyntax { get; set; } /// <summary> /// Specific part of the symbol to which the attributes apply, or AttributeLocation.None if the attributes apply to the symbol itself. /// Used e.g. for return type attributes of a method symbol. /// </summary> public TAttributeLocation SymbolPart { get; set; } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Contains common arguments to Symbol.EarlyDecodeWellKnownAttribute method in both the language compilers. /// </summary> internal struct EarlyDecodeWellKnownAttributeArguments<TEarlyBinder, TNamedTypeSymbol, TAttributeSyntax, TAttributeLocation> where TNamedTypeSymbol : INamedTypeSymbolInternal where TAttributeSyntax : SyntaxNode { /// <summary> /// Object to store the decoded data from early bound well-known attributes. /// Created lazily only when some decoded data needs to be stored, null otherwise. /// </summary> private EarlyWellKnownAttributeData _lazyDecodeData; /// <summary> /// Gets or creates the decoded data object. /// </summary> /// <remarks> /// This method must be called only when some decoded data will be stored into it subsequently. /// </remarks> public T GetOrCreateData<T>() where T : EarlyWellKnownAttributeData, new() { if (_lazyDecodeData == null) { _lazyDecodeData = new T(); } return (T)_lazyDecodeData; } /// <summary> /// Returns true if some decoded data has been stored into <see cref="_lazyDecodeData"/>. /// </summary> public bool HasDecodedData { get { if (_lazyDecodeData != null) { _lazyDecodeData.VerifyDataStored(expected: true); return true; } return false; } } /// <summary> /// Gets the stored decoded data. /// </summary> /// <remarks> /// Assumes <see cref="HasDecodedData"/> is true. /// </remarks> public EarlyWellKnownAttributeData DecodedData { get { Debug.Assert(this.HasDecodedData); return _lazyDecodeData; } } /// <summary> /// Binder to bind early well-known attributes. /// </summary> public TEarlyBinder Binder { get; set; } /// <summary> /// Bound type of the attribute to decode. /// </summary> public TNamedTypeSymbol AttributeType { get; set; } /// <summary> /// Syntax of the attribute to decode. /// </summary> public TAttributeSyntax AttributeSyntax { get; set; } /// <summary> /// Specific part of the symbol to which the attributes apply, or AttributeLocation.None if the attributes apply to the symbol itself. /// Used e.g. for return type attributes of a method symbol. /// </summary> public TAttributeLocation SymbolPart { get; set; } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/Resources.cs.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="cs" original="../Resources.resx"> <body> <trans-unit id="CanNotCreateWindow"> <source>Can not create tool window.</source> <target state="translated">Nejde vytvořit okno nástroje.</target> <note /> </trans-unit> <trans-unit id="ToolWindowTitle"> <source>Roslyn Diagnostics</source> <target state="translated">Diagnostika Roslyn</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="cs" original="../Resources.resx"> <body> <trans-unit id="CanNotCreateWindow"> <source>Can not create tool window.</source> <target state="translated">Nejde vytvořit okno nástroje.</target> <note /> </trans-unit> <trans-unit id="ToolWindowTitle"> <source>Roslyn Diagnostics</source> <target state="translated">Diagnostika Roslyn</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/Extensions/SnapshotSpanExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.Text; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Extensions { internal static class SnapshotSpanExtensions { public static VsTextSpan ToVsTextSpan(this SnapshotSpan snapshotSpan) { snapshotSpan.GetLinesAndCharacters(out var startLine, out var startCharacterIndex, out var endLine, out var endCharacterIndex); return new VsTextSpan() { iStartLine = startLine, iStartIndex = startCharacterIndex, iEndLine = endLine, iEndIndex = endCharacterIndex }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.VisualStudio.Text; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Extensions { internal static class SnapshotSpanExtensions { public static VsTextSpan ToVsTextSpan(this SnapshotSpan snapshotSpan) { snapshotSpan.GetLinesAndCharacters(out var startLine, out var startCharacterIndex, out var endLine, out var endCharacterIndex); return new VsTextSpan() { iStartLine = startLine, iStartIndex = startCharacterIndex, iEndLine = endLine, iEndIndex = endCharacterIndex }; } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Resources/Core/SymbolsTests/MultiTargeting/Source4Module.netmodule
MZ@ !L!This program cannot be run in DOS mode. $PEL)L " @@ `@!S@  H.text  `.reloc @@B!HX `( *BSJB v4.0.30319l#~D#Strings8#US@#GUIDP#BlobG%3*P $  $  <Module>mscorlibC4SystemObject.ctorSource4Module.netmodule ?EK;VG'=z\V4 !! !_CorExeMainmscoree.dll% @ 2
MZ@ !L!This program cannot be run in DOS mode. $PEL)L " @@ `@!S@  H.text  `.reloc @@B!HX `( *BSJB v4.0.30319l#~D#Strings8#US@#GUIDP#BlobG%3*P $  $  <Module>mscorlibC4SystemObject.ctorSource4Module.netmodule ?EK;VG'=z\V4 !! !_CorExeMainmscoree.dll% @ 2
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core.Wpf/xlf/EditorFeaturesWpfResources.de.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="de" original="../EditorFeaturesWpfResources.resx"> <body> <trans-unit id="Building_Project"> <source>Building Project</source> <target state="translated">Projekt wird erstellt</target> <note /> </trans-unit> <trans-unit id="Copying_selection_to_Interactive_Window"> <source>Copying selection to Interactive Window.</source> <target state="translated">Die Auswahl wird in Interactive-Fenster kopiert.</target> <note /> </trans-unit> <trans-unit id="Error_performing_rename_0"> <source>Error performing rename: '{0}'</source> <target state="translated">Fehler beim Umbenennen: "{0}"</target> <note /> </trans-unit> <trans-unit id="Executing_selection_in_Interactive_Window"> <source>Executing selection in Interactive Window.</source> <target state="translated">Die Auswahl wird im Interactive-Fenster ausgeführt.</target> <note /> </trans-unit> <trans-unit id="Interactive_host_process_platform"> <source>Interactive host process platform</source> <target state="translated">Interaktive Hostprozessplattform</target> <note /> </trans-unit> <trans-unit id="Print_a_list_of_referenced_assemblies"> <source>Print a list of referenced assemblies.</source> <target state="translated">Gibt eine Liste der Assemblys aus, auf die verwiesen wird.</target> <note /> </trans-unit> <trans-unit id="Regex_Comment"> <source>Regex - Comment</source> <target state="translated">RegEx - Kommentar</target> <note /> </trans-unit> <trans-unit id="Regex_Character_Class"> <source>Regex - Character Class</source> <target state="translated">RegEx - Zeichenklasse</target> <note /> </trans-unit> <trans-unit id="Regex_Alternation"> <source>Regex - Alternation</source> <target state="translated">RegEx - Wechsel</target> <note /> </trans-unit> <trans-unit id="Regex_Anchor"> <source>Regex - Anchor</source> <target state="translated">RegEx - Anker</target> <note /> </trans-unit> <trans-unit id="Regex_Quantifier"> <source>Regex - Quantifier</source> <target state="translated">RegEx - Quantifizierer</target> <note /> </trans-unit> <trans-unit id="Regex_SelfEscapedCharacter"> <source>Regex - Self Escaped Character</source> <target state="translated">RegEx - Selbstständiges Escapezeichen</target> <note /> </trans-unit> <trans-unit id="Regex_Grouping"> <source>Regex - Grouping</source> <target state="translated">RegEx - Gruppierung</target> <note /> </trans-unit> <trans-unit id="Regex_Text"> <source>Regex - Text</source> <target state="translated">RegEx - Text</target> <note /> </trans-unit> <trans-unit id="Regex_OtherEscape"> <source>Regex - Other Escape</source> <target state="translated">RegEx - Anderes Escapezeichen</target> <note /> </trans-unit> <trans-unit id="Reset_the_execution_environment_to_the_initial_state_keep_history"> <source>Reset the execution environment to the initial state, keep history.</source> <target state="translated">Setzt die Ausführungsumgebung in den ursprünglichen Zustand zurück. Der Verlauf wird beibehalten.</target> <note /> </trans-unit> <trans-unit id="Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script"> <source>Reset to a clean environment (only mscorlib referenced), do not run initialization script.</source> <target state="translated">Setzt auf eine saubere Umgebung zurück (nur Verweis auf "mscorlib") und führt das Initialisierungsskript nicht aus.</target> <note /> </trans-unit> <trans-unit id="Resetting_Interactive"> <source>Resetting Interactive</source> <target state="translated">Interactives Element wird zurückgesetzt</target> <note /> </trans-unit> <trans-unit id="Resetting_execution_engine"> <source>Resetting execution engine.</source> <target state="translated">Das Ausführungsmodul wird zurückgesetzt.</target> <note /> </trans-unit> <trans-unit id="The_CurrentWindow_property_may_only_be_assigned_once"> <source>The CurrentWindow property may only be assigned once.</source> <target state="translated">Die Eigenschaft "CurrentWindow" kann nur ein Mal zugewiesen werden.</target> <note /> </trans-unit> <trans-unit id="The_references_command_is_not_supported_in_this_Interactive_Window_implementation"> <source>The references command is not supported in this Interactive Window implementation.</source> <target state="translated">Der Befehl "references" wird in dieser Implementierung von Interactive-Fenster nicht unterstützt.</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="de" original="../EditorFeaturesWpfResources.resx"> <body> <trans-unit id="Building_Project"> <source>Building Project</source> <target state="translated">Projekt wird erstellt</target> <note /> </trans-unit> <trans-unit id="Copying_selection_to_Interactive_Window"> <source>Copying selection to Interactive Window.</source> <target state="translated">Die Auswahl wird in Interactive-Fenster kopiert.</target> <note /> </trans-unit> <trans-unit id="Error_performing_rename_0"> <source>Error performing rename: '{0}'</source> <target state="translated">Fehler beim Umbenennen: "{0}"</target> <note /> </trans-unit> <trans-unit id="Executing_selection_in_Interactive_Window"> <source>Executing selection in Interactive Window.</source> <target state="translated">Die Auswahl wird im Interactive-Fenster ausgeführt.</target> <note /> </trans-unit> <trans-unit id="Interactive_host_process_platform"> <source>Interactive host process platform</source> <target state="translated">Interaktive Hostprozessplattform</target> <note /> </trans-unit> <trans-unit id="Print_a_list_of_referenced_assemblies"> <source>Print a list of referenced assemblies.</source> <target state="translated">Gibt eine Liste der Assemblys aus, auf die verwiesen wird.</target> <note /> </trans-unit> <trans-unit id="Regex_Comment"> <source>Regex - Comment</source> <target state="translated">RegEx - Kommentar</target> <note /> </trans-unit> <trans-unit id="Regex_Character_Class"> <source>Regex - Character Class</source> <target state="translated">RegEx - Zeichenklasse</target> <note /> </trans-unit> <trans-unit id="Regex_Alternation"> <source>Regex - Alternation</source> <target state="translated">RegEx - Wechsel</target> <note /> </trans-unit> <trans-unit id="Regex_Anchor"> <source>Regex - Anchor</source> <target state="translated">RegEx - Anker</target> <note /> </trans-unit> <trans-unit id="Regex_Quantifier"> <source>Regex - Quantifier</source> <target state="translated">RegEx - Quantifizierer</target> <note /> </trans-unit> <trans-unit id="Regex_SelfEscapedCharacter"> <source>Regex - Self Escaped Character</source> <target state="translated">RegEx - Selbstständiges Escapezeichen</target> <note /> </trans-unit> <trans-unit id="Regex_Grouping"> <source>Regex - Grouping</source> <target state="translated">RegEx - Gruppierung</target> <note /> </trans-unit> <trans-unit id="Regex_Text"> <source>Regex - Text</source> <target state="translated">RegEx - Text</target> <note /> </trans-unit> <trans-unit id="Regex_OtherEscape"> <source>Regex - Other Escape</source> <target state="translated">RegEx - Anderes Escapezeichen</target> <note /> </trans-unit> <trans-unit id="Reset_the_execution_environment_to_the_initial_state_keep_history"> <source>Reset the execution environment to the initial state, keep history.</source> <target state="translated">Setzt die Ausführungsumgebung in den ursprünglichen Zustand zurück. Der Verlauf wird beibehalten.</target> <note /> </trans-unit> <trans-unit id="Reset_to_a_clean_environment_only_mscorlib_referenced_do_not_run_initialization_script"> <source>Reset to a clean environment (only mscorlib referenced), do not run initialization script.</source> <target state="translated">Setzt auf eine saubere Umgebung zurück (nur Verweis auf "mscorlib") und führt das Initialisierungsskript nicht aus.</target> <note /> </trans-unit> <trans-unit id="Resetting_Interactive"> <source>Resetting Interactive</source> <target state="translated">Interactives Element wird zurückgesetzt</target> <note /> </trans-unit> <trans-unit id="Resetting_execution_engine"> <source>Resetting execution engine.</source> <target state="translated">Das Ausführungsmodul wird zurückgesetzt.</target> <note /> </trans-unit> <trans-unit id="The_CurrentWindow_property_may_only_be_assigned_once"> <source>The CurrentWindow property may only be assigned once.</source> <target state="translated">Die Eigenschaft "CurrentWindow" kann nur ein Mal zugewiesen werden.</target> <note /> </trans-unit> <trans-unit id="The_references_command_is_not_supported_in_this_Interactive_Window_implementation"> <source>The references command is not supported in this Interactive Window implementation.</source> <target state="translated">Der Befehl "references" wird in dieser Implementierung von Interactive-Fenster nicht unterstützt.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/CodeRefactorings/AbstractRefactoringHelpersService.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.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeRefactorings { internal abstract class AbstractRefactoringHelpersService<TExpressionSyntax, TArgumentSyntax, TExpressionStatementSyntax> : IRefactoringHelpersService where TExpressionSyntax : SyntaxNode where TArgumentSyntax : SyntaxNode where TExpressionStatementSyntax : SyntaxNode { public async Task<ImmutableArray<TSyntaxNode>> GetRelevantNodesAsync<TSyntaxNode>( Document document, TextSpan selectionRaw, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { // Given selection is trimmed first to enable over-selection that spans multiple lines. Since trailing whitespace ends // at newline boundary over-selection to e.g. a line after LocalFunctionStatement would cause FindNode to find enclosing // block's Node. That is because in addition to LocalFunctionStatement the selection would also contain trailing trivia // (whitespace) of following statement. var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (root == null) { return ImmutableArray<TSyntaxNode>.Empty; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var selectionTrimmed = await CodeRefactoringHelpers.GetTrimmedTextSpanAsync(document, selectionRaw, cancellationToken).ConfigureAwait(false); // If user selected only whitespace we don't want to return anything. We could do following: // 1) Consider token that owns (as its trivia) the whitespace. // 2) Consider start/beginning of whitespace as location (empty selection) // Option 1) can't be used all the time and 2) can be confusing for users. Therefore bailing out is the // most consistent option. if (selectionTrimmed.IsEmpty && !selectionRaw.IsEmpty) { return ImmutableArray<TSyntaxNode>.Empty; } using var relevantNodesBuilderDisposer = ArrayBuilder<TSyntaxNode>.GetInstance(out var relevantNodesBuilder); // Every time a Node is considered an extractNodes method is called to add all nodes around the original one // that should also be considered. // // That enables us to e.g. return node `b` when Node `var a = b;` is being considered without a complex (and potentially // lang. & situation dependent) into Children descending code here. We can't just try extracted Node because we might // want the whole node `var a = b;` // Handle selections: // - Most/the whole wanted Node is selected (e.g. `C [|Fun() {}|]` // - The smallest node whose FullSpan includes the whole (trimmed) selection // - Using FullSpan is important because it handles over-selection with comments // - Travels upwards through same-sized (FullSpan) nodes, extracting // - Token with wanted Node as direct parent is selected (e.g. IdentifierToken for LocalFunctionStatement: `C [|Fun|]() {}`) // Note: Whether we have selection or location has to be checked against original selection because selecting just // whitespace could collapse selectionTrimmed into and empty Location. But we don't want `[| |]token` // registering as ` [||]token`. if (!selectionTrimmed.IsEmpty) { AddRelevantNodesForSelection(syntaxFacts, root, selectionTrimmed, relevantNodesBuilder, cancellationToken); } else { // No more selection -> Handle what current selection is touching: // // Consider touching only for empty selections. Otherwise `[|C|] methodName(){}` would be considered as // touching the Method's Node (through the left edge, see below) which is something the user probably // didn't want since they specifically selected only the return type. // // What the selection is touching is used in two ways. // - Firstly, it is used to handle situation where it touches a Token whose direct ancestor is wanted Node. // While having the (even empty) selection inside such token or to left of such Token is already handle // by code above touching it from right `C methodName[||](){}` isn't (the FindNode for that returns Args node). // - Secondly, it is used for left/right edge climbing. E.g. `[||]C methodName(){}` the touching token's direct // ancestor is TypeNode for the return type but it is still reasonable to expect that the user might want to // be given refactorings for the whole method (as he has caret on the edge of it). Therefore we travel the // Node tree upwards and as long as we're on the left edge of a Node's span we consider such node & potentially // continue traveling upwards. The situation for right edge (`C methodName(){}[||]`) is analogical. // E.g. for right edge `C methodName(){}[||]`: CloseBraceToken -> BlockSyntax -> LocalFunctionStatement -> null (higher // node doesn't end on position anymore) // Note: left-edge climbing needs to handle AttributeLists explicitly, see below for more information. // - Thirdly, if location isn't touching anything, we move the location to the token in whose trivia location is in. // more about that below. // - Fourthly, if we're in an expression / argument we consider touching a parent expression whenever we're within it // as long as it is on the first line of such expression (arbitrary heuristic). // First we need to get tokens we might potentially be touching, tokenToRightOrIn and tokenToLeft. var (tokenToRightOrIn, tokenToLeft, location) = await GetTokensToRightOrInToLeftAndUpdatedLocationAsync( document, root, selectionTrimmed, cancellationToken).ConfigureAwait(false); // In addition to per-node extr also check if current location (if selection is empty) is in a header of higher level // desired node once. We do that only for locations because otherwise `[|int|] A { get; set; }) would trigger all refactorings for // Property Decl. // We cannot check this any sooner because the above code could've changed current location. AddNonHiddenCorrectTypeNodes(ExtractNodesInHeader(root, location, syntaxFacts), relevantNodesBuilder, cancellationToken); // Add Nodes for touching tokens as described above. AddNodesForTokenToRightOrIn(syntaxFacts, root, relevantNodesBuilder, location, tokenToRightOrIn, cancellationToken); AddNodesForTokenToLeft(syntaxFacts, relevantNodesBuilder, location, tokenToLeft, cancellationToken); // If the wanted node is an expression syntax -> traverse upwards even if location is deep within a SyntaxNode. // We want to treat more types like expressions, e.g.: ArgumentSyntax should still trigger even if deep-in. if (IsWantedTypeExpressionLike<TSyntaxNode>()) { // Reason to treat Arguments (and potentially others) as Expression-like: // https://github.com/dotnet/roslyn/pull/37295#issuecomment-516145904 await AddNodesDeepInAsync(document, location, relevantNodesBuilder, cancellationToken).ConfigureAwait(false); } } return relevantNodesBuilder.ToImmutable(); } private static bool IsWantedTypeExpressionLike<TSyntaxNode>() where TSyntaxNode : SyntaxNode { var wantedType = typeof(TSyntaxNode); var expressionType = typeof(TExpressionSyntax); var argumentType = typeof(TArgumentSyntax); var expressionStatementType = typeof(TExpressionStatementSyntax); return IsAEqualOrSubclassOfB(wantedType, expressionType) || IsAEqualOrSubclassOfB(wantedType, argumentType) || IsAEqualOrSubclassOfB(wantedType, expressionStatementType); static bool IsAEqualOrSubclassOfB(Type a, Type b) { return a.IsSubclassOf(b) || a == b; } } private static async Task<(SyntaxToken tokenToRightOrIn, SyntaxToken tokenToLeft, int location)> GetTokensToRightOrInToLeftAndUpdatedLocationAsync( Document document, SyntaxNode root, TextSpan selectionTrimmed, CancellationToken cancellationToken) { // get Token for current location var location = selectionTrimmed.Start; var tokenOnLocation = root.FindToken(location); // Gets a token that is directly to the right of current location or that encompasses current location (`[||]tokenToRightOrIn` or `tok[||]enToRightOrIn`) var tokenToRightOrIn = tokenOnLocation.Span.Contains(location) ? tokenOnLocation : default; // A token can be to the left only when there's either no tokenDirectlyToRightOrIn or there's one directly starting at current location. // Otherwise (otherwise tokenToRightOrIn is also left from location, e.g: `tok[||]enToRightOrIn`) var tokenToLeft = default(SyntaxToken); if (tokenToRightOrIn == default || tokenToRightOrIn.FullSpan.Start == location) { var tokenPreLocation = (tokenOnLocation.Span.End == location) ? tokenOnLocation : tokenOnLocation.GetPreviousToken(includeZeroWidth: true); tokenToLeft = (tokenPreLocation.Span.End == location) ? tokenPreLocation : default; } // If both tokens directly to left & right are empty -> we're somewhere in the middle of whitespace. // Since there wouldn't be (m)any other refactorings we can try to offer at least the ones for (semantically) // closest token/Node. Thus, we move the location to the token in whose `.FullSpan` the original location was. if (tokenToLeft == default && tokenToRightOrIn == default) { var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (IsAcceptableLineDistanceAway(sourceText, tokenOnLocation, location)) { // tokenOnLocation: token in whose trivia location is at if (tokenOnLocation.Span.Start >= location) { tokenToRightOrIn = tokenOnLocation; location = tokenToRightOrIn.Span.Start; } else { tokenToLeft = tokenOnLocation; location = tokenToLeft.Span.End; } } } return (tokenToRightOrIn, tokenToLeft, location); static bool IsAcceptableLineDistanceAway( SourceText sourceText, SyntaxToken tokenOnLocation, int location) { // assume non-trivia token can't span multiple lines var tokenLine = sourceText.Lines.GetLineFromPosition(tokenOnLocation.Span.Start); var locationLine = sourceText.Lines.GetLineFromPosition(location); // Change location to nearest token only if the token is off by one line or less var lineDistance = tokenLine.LineNumber - locationLine.LineNumber; if (lineDistance is not 0 and not 1) return false; // Note: being a line below a tokenOnLocation is impossible in current model as whitespace // trailing trivia ends on new line. Which is fine because if you're a line _after_ some node // you usually don't want refactorings for what's above you. if (lineDistance == 1) { // position is one line above the node of interest. This is fine if that // line is blank. Otherwise, if it isn't (i.e. it contains comments, // directives, or other trivia), then it's not likely the user is selecting // this entry. return locationLine.IsEmptyOrWhitespace(); } // On hte same line. This position is acceptable. return true; } } private void AddNodesForTokenToLeft<TSyntaxNode>(ISyntaxFactsService syntaxFacts, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, int location, SyntaxToken tokenToLeft, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { // there could be multiple (n) tokens to the left if first n-1 are Empty -> iterate over all of them while (tokenToLeft != default) { var leftNode = tokenToLeft.Parent!; do { // Consider either a Node that is: // - Ancestor Node of such Token as long as their span ends on location (it's still on the edge) AddNonHiddenCorrectTypeNodes(ExtractNodesSimple(leftNode, syntaxFacts), relevantNodesBuilder, cancellationToken); leftNode = leftNode.Parent; if (leftNode == null || !(leftNode.GetLastToken().Span.End == location || leftNode.Span.End == location)) { break; } } while (true); // as long as current tokenToLeft is empty -> its previous token is also tokenToLeft tokenToLeft = tokenToLeft.Span.IsEmpty ? tokenToLeft.GetPreviousToken(includeZeroWidth: true) : default; } } private void AddNodesForTokenToRightOrIn<TSyntaxNode>(ISyntaxFactsService syntaxFacts, SyntaxNode root, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, int location, SyntaxToken tokenToRightOrIn, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { if (tokenToRightOrIn != default) { var rightNode = tokenToRightOrIn.Parent!; do { // Consider either a Node that is: // - Parent of touched Token (location can be within) // - Ancestor Node of such Token as long as their span starts on location (it's still on the edge) AddNonHiddenCorrectTypeNodes(ExtractNodesSimple(rightNode, syntaxFacts), relevantNodesBuilder, cancellationToken); rightNode = rightNode.Parent; if (rightNode == null) { break; } // The edge climbing for node to the right needs to handle Attributes e.g.: // [Test1] // //Comment1 // [||]object Property1 { get; set; } // In essence: // - On the left edge of the node (-> left edge of first AttributeLists) // - On the left edge of the node sans AttributeLists (& as everywhere comments) if (rightNode.Span.Start != location) { var rightNodeSpanWithoutAttributes = syntaxFacts.GetSpanWithoutAttributes(root, rightNode); if (rightNodeSpanWithoutAttributes.Start != location) { break; } } } while (true); } } private void AddRelevantNodesForSelection<TSyntaxNode>(ISyntaxFactsService syntaxFacts, SyntaxNode root, TextSpan selectionTrimmed, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { var selectionNode = root.FindNode(selectionTrimmed, getInnermostNodeForTie: true); var prevNode = selectionNode; do { var nonHiddenExtractedSelectedNodes = ExtractNodesSimple(selectionNode, syntaxFacts).OfType<TSyntaxNode>().Where(n => !n.OverlapsHiddenPosition(cancellationToken)); foreach (var nonHiddenExtractedNode in nonHiddenExtractedSelectedNodes) { // For selections we need to handle an edge case where only AttributeLists are within selection (e.g. `Func([|[in][out]|] arg1);`). // In that case the smallest encompassing node is still the whole argument node but it's hard to justify showing refactorings for it // if user selected only its attributes. // Selection contains only AttributeLists -> don't consider current Node var spanWithoutAttributes = syntaxFacts.GetSpanWithoutAttributes(root, nonHiddenExtractedNode); if (!selectionTrimmed.IntersectsWith(spanWithoutAttributes)) { break; } relevantNodesBuilder.Add(nonHiddenExtractedNode); } prevNode = selectionNode; selectionNode = selectionNode.Parent; } while (selectionNode != null && prevNode.FullWidth() == selectionNode.FullWidth()); } /// <summary> /// Extractor function that retrieves all nodes that should be considered for extraction of given current node. /// <para> /// The rationale is that when user selects e.g. entire local declaration statement [|var a = b;|] it is reasonable /// to provide refactoring for `b` node. Similarly for other types of refactorings. /// </para> /// </summary> /// <remark> /// Should also return given node. /// </remark> protected virtual IEnumerable<SyntaxNode> ExtractNodesSimple(SyntaxNode? node, ISyntaxFactsService syntaxFacts) { if (node == null) { yield break; } // First return the node itself so that it is considered yield return node; // REMARKS: // The set of currently attempted extractions is in no way exhaustive and covers only cases // that were found to be relevant for refactorings that were moved to `TryGetSelectedNodeAsync`. // Feel free to extend it / refine current heuristics. // `var a = b;` | `var a = b`; if (syntaxFacts.IsLocalDeclarationStatement(node) || syntaxFacts.IsLocalDeclarationStatement(node.Parent)) { var localDeclarationStatement = syntaxFacts.IsLocalDeclarationStatement(node) ? node : node.Parent!; // Check if there's only one variable being declared, otherwise following transformation // would go through which isn't reasonable since we can't say the first one specifically // is wanted. // `var a = 1, `c = 2, d = 3`; // -> `var a = 1`, c = 2, d = 3; var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclarationStatement); if (variables.Count == 1) { var declaredVariable = variables.First(); // -> `a = b` yield return declaredVariable; // -> `b` var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(declaredVariable); if (initializer != null) { var value = syntaxFacts.GetValueOfEqualsValueClause(initializer); if (value != null) { yield return value; } } } } // var `a = b`; if (syntaxFacts.IsVariableDeclarator(node)) { // -> `b` var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(node); if (initializer != null) { var value = syntaxFacts.GetValueOfEqualsValueClause(initializer); if (value != null) { yield return value; } } } // `a = b;` // -> `b` if (syntaxFacts.IsSimpleAssignmentStatement(node)) { syntaxFacts.GetPartsOfAssignmentExpressionOrStatement(node, out _, out _, out var rightSide); yield return rightSide; } // `a();` // -> a() if (syntaxFacts.IsExpressionStatement(node)) { yield return syntaxFacts.GetExpressionOfExpressionStatement(node); } // `a()`; // -> `a();` if (syntaxFacts.IsExpressionStatement(node.Parent)) { yield return node.Parent; } } /// <summary> /// Extractor function that checks and retrieves all nodes current location is in a header. /// </summary> protected virtual IEnumerable<SyntaxNode> ExtractNodesInHeader(SyntaxNode root, int location, ISyntaxFactsService syntaxFacts) { // Header: [Test] `public int a` { get; set; } if (syntaxFacts.IsOnPropertyDeclarationHeader(root, location, out var propertyDeclaration)) { yield return propertyDeclaration; } // Header: public C([Test]`int a = 42`) {} if (syntaxFacts.IsOnParameterHeader(root, location, out var parameter)) { yield return parameter; } // Header: `public I.C([Test]int a = 42)` {} if (syntaxFacts.IsOnMethodHeader(root, location, out var method)) { yield return method; } // Header: `static C([Test]int a = 42)` {} if (syntaxFacts.IsOnLocalFunctionHeader(root, location, out var localFunction)) { yield return localFunction; } // Header: `var a = `3,` b = `5,` c = `7 + 3``; if (syntaxFacts.IsOnLocalDeclarationHeader(root, location, out var localDeclaration)) { yield return localDeclaration; } // Header: `if(...)`{ }; if (syntaxFacts.IsOnIfStatementHeader(root, location, out var ifStatement)) { yield return ifStatement; } // Header: `foreach (var a in b)` { } if (syntaxFacts.IsOnForeachHeader(root, location, out var foreachStatement)) { yield return foreachStatement; } if (syntaxFacts.IsOnTypeHeader(root, location, out var typeDeclaration)) { yield return typeDeclaration; } } protected virtual async Task AddNodesDeepInAsync<TSyntaxNode>( Document document, int position, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { // If we're deep inside we don't have to deal with being on edges (that gets dealt by TryGetSelectedNodeAsync) // -> can simply FindToken -> proceed testing its ancestors var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (root is null) { throw new NotSupportedException(WorkspacesResources.Document_does_not_support_syntax_trees); } var token = root.FindTokenOnRightOfPosition(position, true); // traverse upwards and add all parents if of correct type var ancestor = token.Parent; while (ancestor != null) { if (ancestor is TSyntaxNode correctTypeNode) { var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var argumentStartLine = sourceText.Lines.GetLineFromPosition(correctTypeNode.Span.Start).LineNumber; var caretLine = sourceText.Lines.GetLineFromPosition(position).LineNumber; if (argumentStartLine == caretLine && !correctTypeNode.OverlapsHiddenPosition(cancellationToken)) { relevantNodesBuilder.Add(correctTypeNode); } else if (argumentStartLine < caretLine) { // higher level nodes will have Span starting at least on the same line -> can bail out return; } } ancestor = ancestor.Parent; } } private static void AddNonHiddenCorrectTypeNodes<TSyntaxNode>(IEnumerable<SyntaxNode> nodes, ArrayBuilder<TSyntaxNode> resultBuilder, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { var correctTypeNonHiddenNodes = nodes.OfType<TSyntaxNode>().Where(n => !n.OverlapsHiddenPosition(cancellationToken)); foreach (var nodeToBeAdded in correctTypeNonHiddenNodes) { resultBuilder.Add(nodeToBeAdded); } } } }
// Licensed to the .NET Foundation under one or more 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.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeRefactorings { internal abstract class AbstractRefactoringHelpersService<TExpressionSyntax, TArgumentSyntax, TExpressionStatementSyntax> : IRefactoringHelpersService where TExpressionSyntax : SyntaxNode where TArgumentSyntax : SyntaxNode where TExpressionStatementSyntax : SyntaxNode { public async Task<ImmutableArray<TSyntaxNode>> GetRelevantNodesAsync<TSyntaxNode>( Document document, TextSpan selectionRaw, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { // Given selection is trimmed first to enable over-selection that spans multiple lines. Since trailing whitespace ends // at newline boundary over-selection to e.g. a line after LocalFunctionStatement would cause FindNode to find enclosing // block's Node. That is because in addition to LocalFunctionStatement the selection would also contain trailing trivia // (whitespace) of following statement. var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (root == null) { return ImmutableArray<TSyntaxNode>.Empty; } var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var selectionTrimmed = await CodeRefactoringHelpers.GetTrimmedTextSpanAsync(document, selectionRaw, cancellationToken).ConfigureAwait(false); // If user selected only whitespace we don't want to return anything. We could do following: // 1) Consider token that owns (as its trivia) the whitespace. // 2) Consider start/beginning of whitespace as location (empty selection) // Option 1) can't be used all the time and 2) can be confusing for users. Therefore bailing out is the // most consistent option. if (selectionTrimmed.IsEmpty && !selectionRaw.IsEmpty) { return ImmutableArray<TSyntaxNode>.Empty; } using var relevantNodesBuilderDisposer = ArrayBuilder<TSyntaxNode>.GetInstance(out var relevantNodesBuilder); // Every time a Node is considered an extractNodes method is called to add all nodes around the original one // that should also be considered. // // That enables us to e.g. return node `b` when Node `var a = b;` is being considered without a complex (and potentially // lang. & situation dependent) into Children descending code here. We can't just try extracted Node because we might // want the whole node `var a = b;` // Handle selections: // - Most/the whole wanted Node is selected (e.g. `C [|Fun() {}|]` // - The smallest node whose FullSpan includes the whole (trimmed) selection // - Using FullSpan is important because it handles over-selection with comments // - Travels upwards through same-sized (FullSpan) nodes, extracting // - Token with wanted Node as direct parent is selected (e.g. IdentifierToken for LocalFunctionStatement: `C [|Fun|]() {}`) // Note: Whether we have selection or location has to be checked against original selection because selecting just // whitespace could collapse selectionTrimmed into and empty Location. But we don't want `[| |]token` // registering as ` [||]token`. if (!selectionTrimmed.IsEmpty) { AddRelevantNodesForSelection(syntaxFacts, root, selectionTrimmed, relevantNodesBuilder, cancellationToken); } else { // No more selection -> Handle what current selection is touching: // // Consider touching only for empty selections. Otherwise `[|C|] methodName(){}` would be considered as // touching the Method's Node (through the left edge, see below) which is something the user probably // didn't want since they specifically selected only the return type. // // What the selection is touching is used in two ways. // - Firstly, it is used to handle situation where it touches a Token whose direct ancestor is wanted Node. // While having the (even empty) selection inside such token or to left of such Token is already handle // by code above touching it from right `C methodName[||](){}` isn't (the FindNode for that returns Args node). // - Secondly, it is used for left/right edge climbing. E.g. `[||]C methodName(){}` the touching token's direct // ancestor is TypeNode for the return type but it is still reasonable to expect that the user might want to // be given refactorings for the whole method (as he has caret on the edge of it). Therefore we travel the // Node tree upwards and as long as we're on the left edge of a Node's span we consider such node & potentially // continue traveling upwards. The situation for right edge (`C methodName(){}[||]`) is analogical. // E.g. for right edge `C methodName(){}[||]`: CloseBraceToken -> BlockSyntax -> LocalFunctionStatement -> null (higher // node doesn't end on position anymore) // Note: left-edge climbing needs to handle AttributeLists explicitly, see below for more information. // - Thirdly, if location isn't touching anything, we move the location to the token in whose trivia location is in. // more about that below. // - Fourthly, if we're in an expression / argument we consider touching a parent expression whenever we're within it // as long as it is on the first line of such expression (arbitrary heuristic). // First we need to get tokens we might potentially be touching, tokenToRightOrIn and tokenToLeft. var (tokenToRightOrIn, tokenToLeft, location) = await GetTokensToRightOrInToLeftAndUpdatedLocationAsync( document, root, selectionTrimmed, cancellationToken).ConfigureAwait(false); // In addition to per-node extr also check if current location (if selection is empty) is in a header of higher level // desired node once. We do that only for locations because otherwise `[|int|] A { get; set; }) would trigger all refactorings for // Property Decl. // We cannot check this any sooner because the above code could've changed current location. AddNonHiddenCorrectTypeNodes(ExtractNodesInHeader(root, location, syntaxFacts), relevantNodesBuilder, cancellationToken); // Add Nodes for touching tokens as described above. AddNodesForTokenToRightOrIn(syntaxFacts, root, relevantNodesBuilder, location, tokenToRightOrIn, cancellationToken); AddNodesForTokenToLeft(syntaxFacts, relevantNodesBuilder, location, tokenToLeft, cancellationToken); // If the wanted node is an expression syntax -> traverse upwards even if location is deep within a SyntaxNode. // We want to treat more types like expressions, e.g.: ArgumentSyntax should still trigger even if deep-in. if (IsWantedTypeExpressionLike<TSyntaxNode>()) { // Reason to treat Arguments (and potentially others) as Expression-like: // https://github.com/dotnet/roslyn/pull/37295#issuecomment-516145904 await AddNodesDeepInAsync(document, location, relevantNodesBuilder, cancellationToken).ConfigureAwait(false); } } return relevantNodesBuilder.ToImmutable(); } private static bool IsWantedTypeExpressionLike<TSyntaxNode>() where TSyntaxNode : SyntaxNode { var wantedType = typeof(TSyntaxNode); var expressionType = typeof(TExpressionSyntax); var argumentType = typeof(TArgumentSyntax); var expressionStatementType = typeof(TExpressionStatementSyntax); return IsAEqualOrSubclassOfB(wantedType, expressionType) || IsAEqualOrSubclassOfB(wantedType, argumentType) || IsAEqualOrSubclassOfB(wantedType, expressionStatementType); static bool IsAEqualOrSubclassOfB(Type a, Type b) { return a.IsSubclassOf(b) || a == b; } } private static async Task<(SyntaxToken tokenToRightOrIn, SyntaxToken tokenToLeft, int location)> GetTokensToRightOrInToLeftAndUpdatedLocationAsync( Document document, SyntaxNode root, TextSpan selectionTrimmed, CancellationToken cancellationToken) { // get Token for current location var location = selectionTrimmed.Start; var tokenOnLocation = root.FindToken(location); // Gets a token that is directly to the right of current location or that encompasses current location (`[||]tokenToRightOrIn` or `tok[||]enToRightOrIn`) var tokenToRightOrIn = tokenOnLocation.Span.Contains(location) ? tokenOnLocation : default; // A token can be to the left only when there's either no tokenDirectlyToRightOrIn or there's one directly starting at current location. // Otherwise (otherwise tokenToRightOrIn is also left from location, e.g: `tok[||]enToRightOrIn`) var tokenToLeft = default(SyntaxToken); if (tokenToRightOrIn == default || tokenToRightOrIn.FullSpan.Start == location) { var tokenPreLocation = (tokenOnLocation.Span.End == location) ? tokenOnLocation : tokenOnLocation.GetPreviousToken(includeZeroWidth: true); tokenToLeft = (tokenPreLocation.Span.End == location) ? tokenPreLocation : default; } // If both tokens directly to left & right are empty -> we're somewhere in the middle of whitespace. // Since there wouldn't be (m)any other refactorings we can try to offer at least the ones for (semantically) // closest token/Node. Thus, we move the location to the token in whose `.FullSpan` the original location was. if (tokenToLeft == default && tokenToRightOrIn == default) { var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); if (IsAcceptableLineDistanceAway(sourceText, tokenOnLocation, location)) { // tokenOnLocation: token in whose trivia location is at if (tokenOnLocation.Span.Start >= location) { tokenToRightOrIn = tokenOnLocation; location = tokenToRightOrIn.Span.Start; } else { tokenToLeft = tokenOnLocation; location = tokenToLeft.Span.End; } } } return (tokenToRightOrIn, tokenToLeft, location); static bool IsAcceptableLineDistanceAway( SourceText sourceText, SyntaxToken tokenOnLocation, int location) { // assume non-trivia token can't span multiple lines var tokenLine = sourceText.Lines.GetLineFromPosition(tokenOnLocation.Span.Start); var locationLine = sourceText.Lines.GetLineFromPosition(location); // Change location to nearest token only if the token is off by one line or less var lineDistance = tokenLine.LineNumber - locationLine.LineNumber; if (lineDistance is not 0 and not 1) return false; // Note: being a line below a tokenOnLocation is impossible in current model as whitespace // trailing trivia ends on new line. Which is fine because if you're a line _after_ some node // you usually don't want refactorings for what's above you. if (lineDistance == 1) { // position is one line above the node of interest. This is fine if that // line is blank. Otherwise, if it isn't (i.e. it contains comments, // directives, or other trivia), then it's not likely the user is selecting // this entry. return locationLine.IsEmptyOrWhitespace(); } // On hte same line. This position is acceptable. return true; } } private void AddNodesForTokenToLeft<TSyntaxNode>(ISyntaxFactsService syntaxFacts, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, int location, SyntaxToken tokenToLeft, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { // there could be multiple (n) tokens to the left if first n-1 are Empty -> iterate over all of them while (tokenToLeft != default) { var leftNode = tokenToLeft.Parent!; do { // Consider either a Node that is: // - Ancestor Node of such Token as long as their span ends on location (it's still on the edge) AddNonHiddenCorrectTypeNodes(ExtractNodesSimple(leftNode, syntaxFacts), relevantNodesBuilder, cancellationToken); leftNode = leftNode.Parent; if (leftNode == null || !(leftNode.GetLastToken().Span.End == location || leftNode.Span.End == location)) { break; } } while (true); // as long as current tokenToLeft is empty -> its previous token is also tokenToLeft tokenToLeft = tokenToLeft.Span.IsEmpty ? tokenToLeft.GetPreviousToken(includeZeroWidth: true) : default; } } private void AddNodesForTokenToRightOrIn<TSyntaxNode>(ISyntaxFactsService syntaxFacts, SyntaxNode root, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, int location, SyntaxToken tokenToRightOrIn, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { if (tokenToRightOrIn != default) { var rightNode = tokenToRightOrIn.Parent!; do { // Consider either a Node that is: // - Parent of touched Token (location can be within) // - Ancestor Node of such Token as long as their span starts on location (it's still on the edge) AddNonHiddenCorrectTypeNodes(ExtractNodesSimple(rightNode, syntaxFacts), relevantNodesBuilder, cancellationToken); rightNode = rightNode.Parent; if (rightNode == null) { break; } // The edge climbing for node to the right needs to handle Attributes e.g.: // [Test1] // //Comment1 // [||]object Property1 { get; set; } // In essence: // - On the left edge of the node (-> left edge of first AttributeLists) // - On the left edge of the node sans AttributeLists (& as everywhere comments) if (rightNode.Span.Start != location) { var rightNodeSpanWithoutAttributes = syntaxFacts.GetSpanWithoutAttributes(root, rightNode); if (rightNodeSpanWithoutAttributes.Start != location) { break; } } } while (true); } } private void AddRelevantNodesForSelection<TSyntaxNode>(ISyntaxFactsService syntaxFacts, SyntaxNode root, TextSpan selectionTrimmed, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { var selectionNode = root.FindNode(selectionTrimmed, getInnermostNodeForTie: true); var prevNode = selectionNode; do { var nonHiddenExtractedSelectedNodes = ExtractNodesSimple(selectionNode, syntaxFacts).OfType<TSyntaxNode>().Where(n => !n.OverlapsHiddenPosition(cancellationToken)); foreach (var nonHiddenExtractedNode in nonHiddenExtractedSelectedNodes) { // For selections we need to handle an edge case where only AttributeLists are within selection (e.g. `Func([|[in][out]|] arg1);`). // In that case the smallest encompassing node is still the whole argument node but it's hard to justify showing refactorings for it // if user selected only its attributes. // Selection contains only AttributeLists -> don't consider current Node var spanWithoutAttributes = syntaxFacts.GetSpanWithoutAttributes(root, nonHiddenExtractedNode); if (!selectionTrimmed.IntersectsWith(spanWithoutAttributes)) { break; } relevantNodesBuilder.Add(nonHiddenExtractedNode); } prevNode = selectionNode; selectionNode = selectionNode.Parent; } while (selectionNode != null && prevNode.FullWidth() == selectionNode.FullWidth()); } /// <summary> /// Extractor function that retrieves all nodes that should be considered for extraction of given current node. /// <para> /// The rationale is that when user selects e.g. entire local declaration statement [|var a = b;|] it is reasonable /// to provide refactoring for `b` node. Similarly for other types of refactorings. /// </para> /// </summary> /// <remark> /// Should also return given node. /// </remark> protected virtual IEnumerable<SyntaxNode> ExtractNodesSimple(SyntaxNode? node, ISyntaxFactsService syntaxFacts) { if (node == null) { yield break; } // First return the node itself so that it is considered yield return node; // REMARKS: // The set of currently attempted extractions is in no way exhaustive and covers only cases // that were found to be relevant for refactorings that were moved to `TryGetSelectedNodeAsync`. // Feel free to extend it / refine current heuristics. // `var a = b;` | `var a = b`; if (syntaxFacts.IsLocalDeclarationStatement(node) || syntaxFacts.IsLocalDeclarationStatement(node.Parent)) { var localDeclarationStatement = syntaxFacts.IsLocalDeclarationStatement(node) ? node : node.Parent!; // Check if there's only one variable being declared, otherwise following transformation // would go through which isn't reasonable since we can't say the first one specifically // is wanted. // `var a = 1, `c = 2, d = 3`; // -> `var a = 1`, c = 2, d = 3; var variables = syntaxFacts.GetVariablesOfLocalDeclarationStatement(localDeclarationStatement); if (variables.Count == 1) { var declaredVariable = variables.First(); // -> `a = b` yield return declaredVariable; // -> `b` var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(declaredVariable); if (initializer != null) { var value = syntaxFacts.GetValueOfEqualsValueClause(initializer); if (value != null) { yield return value; } } } } // var `a = b`; if (syntaxFacts.IsVariableDeclarator(node)) { // -> `b` var initializer = syntaxFacts.GetInitializerOfVariableDeclarator(node); if (initializer != null) { var value = syntaxFacts.GetValueOfEqualsValueClause(initializer); if (value != null) { yield return value; } } } // `a = b;` // -> `b` if (syntaxFacts.IsSimpleAssignmentStatement(node)) { syntaxFacts.GetPartsOfAssignmentExpressionOrStatement(node, out _, out _, out var rightSide); yield return rightSide; } // `a();` // -> a() if (syntaxFacts.IsExpressionStatement(node)) { yield return syntaxFacts.GetExpressionOfExpressionStatement(node); } // `a()`; // -> `a();` if (syntaxFacts.IsExpressionStatement(node.Parent)) { yield return node.Parent; } } /// <summary> /// Extractor function that checks and retrieves all nodes current location is in a header. /// </summary> protected virtual IEnumerable<SyntaxNode> ExtractNodesInHeader(SyntaxNode root, int location, ISyntaxFactsService syntaxFacts) { // Header: [Test] `public int a` { get; set; } if (syntaxFacts.IsOnPropertyDeclarationHeader(root, location, out var propertyDeclaration)) { yield return propertyDeclaration; } // Header: public C([Test]`int a = 42`) {} if (syntaxFacts.IsOnParameterHeader(root, location, out var parameter)) { yield return parameter; } // Header: `public I.C([Test]int a = 42)` {} if (syntaxFacts.IsOnMethodHeader(root, location, out var method)) { yield return method; } // Header: `static C([Test]int a = 42)` {} if (syntaxFacts.IsOnLocalFunctionHeader(root, location, out var localFunction)) { yield return localFunction; } // Header: `var a = `3,` b = `5,` c = `7 + 3``; if (syntaxFacts.IsOnLocalDeclarationHeader(root, location, out var localDeclaration)) { yield return localDeclaration; } // Header: `if(...)`{ }; if (syntaxFacts.IsOnIfStatementHeader(root, location, out var ifStatement)) { yield return ifStatement; } // Header: `foreach (var a in b)` { } if (syntaxFacts.IsOnForeachHeader(root, location, out var foreachStatement)) { yield return foreachStatement; } if (syntaxFacts.IsOnTypeHeader(root, location, out var typeDeclaration)) { yield return typeDeclaration; } } protected virtual async Task AddNodesDeepInAsync<TSyntaxNode>( Document document, int position, ArrayBuilder<TSyntaxNode> relevantNodesBuilder, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { // If we're deep inside we don't have to deal with being on edges (that gets dealt by TryGetSelectedNodeAsync) // -> can simply FindToken -> proceed testing its ancestors var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (root is null) { throw new NotSupportedException(WorkspacesResources.Document_does_not_support_syntax_trees); } var token = root.FindTokenOnRightOfPosition(position, true); // traverse upwards and add all parents if of correct type var ancestor = token.Parent; while (ancestor != null) { if (ancestor is TSyntaxNode correctTypeNode) { var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var argumentStartLine = sourceText.Lines.GetLineFromPosition(correctTypeNode.Span.Start).LineNumber; var caretLine = sourceText.Lines.GetLineFromPosition(position).LineNumber; if (argumentStartLine == caretLine && !correctTypeNode.OverlapsHiddenPosition(cancellationToken)) { relevantNodesBuilder.Add(correctTypeNode); } else if (argumentStartLine < caretLine) { // higher level nodes will have Span starting at least on the same line -> can bail out return; } } ancestor = ancestor.Parent; } } private static void AddNonHiddenCorrectTypeNodes<TSyntaxNode>(IEnumerable<SyntaxNode> nodes, ArrayBuilder<TSyntaxNode> resultBuilder, CancellationToken cancellationToken) where TSyntaxNode : SyntaxNode { var correctTypeNonHiddenNodes = nodes.OfType<TSyntaxNode>().Where(n => !n.OverlapsHiddenPosition(cancellationToken)); foreach (var nodeToBeAdded in correctTypeNonHiddenNodes) { resultBuilder.Add(nodeToBeAdded); } } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ParamsKeywordRecommender.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 ParamsKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ParamsKeywordRecommender() : base(SyntaxKind.ParamsKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.SyntaxTree.IsParamsModifierContext(context.Position, context.LeftToken); } }
// Licensed to the .NET Foundation under one or more 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 ParamsKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public ParamsKeywordRecommender() : base(SyntaxKind.ParamsKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.SyntaxTree.IsParamsModifierContext(context.Position, context.LeftToken); } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Test/Semantic/Compilation/SymbolSearchTests.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.VisualBasic.UnitTests Public Class SymbolSearchTests Inherits BasicTestBase <Fact> Public Sub TestSymbolFilterNone() Assert.Throws(Of ArgumentException)(Sub() Dim compilation = GetTestCompilation() compilation.ContainsSymbolsWithName(Function(n) True, SymbolFilter.None) End Sub) Assert.Throws(Of ArgumentException)(Sub() Dim compilation = GetTestCompilation() compilation.GetSymbolsWithName(Function(n) True, SymbolFilter.None) End Sub) Assert.Throws(Of ArgumentException)(Sub() Dim compilation = GetTestCompilation() compilation.ContainsSymbolsWithName("", SymbolFilter.None) End Sub) Assert.Throws(Of ArgumentException)(Sub() Dim compilation = GetTestCompilation() compilation.GetSymbolsWithName("", SymbolFilter.None) End Sub) End Sub <Fact> Public Sub TestPredicateNull() Assert.Throws(Of ArgumentNullException)(Sub() Dim compilation = GetTestCompilation() compilation.ContainsSymbolsWithName(predicate:=Nothing) End Sub) Assert.Throws(Of ArgumentNullException)(Sub() Dim compilation = GetTestCompilation() compilation.GetSymbolsWithName(predicate:=Nothing) End Sub) End Sub <Fact> Public Sub TestStringNull() Assert.Throws(Of ArgumentNullException)(Sub() Dim compilation = GetTestCompilation() compilation.ContainsSymbolsWithName(name:=Nothing) End Sub) Assert.Throws(Of ArgumentNullException)(Sub() Dim compilation = GetTestCompilation() compilation.GetSymbolsWithName(name:=Nothing) End Sub) End Sub <Fact> Public Sub TestMergedNamespace() Dim compilation = GetTestCompilation() TestNameAndPredicate(compilation, "System", includeNamespace:=True, includeType:=False, includeMember:=False, count:=1) TestNameAndPredicate(compilation, "System", includeNamespace:=True, includeType:=True, includeMember:=False, count:=1) TestNameAndPredicate(compilation, "System", includeNamespace:=True, includeType:=False, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "System", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "System", includeNamespace:=False, includeType:=False, includeMember:=True, count:=0) TestNameAndPredicate(compilation, "System", includeNamespace:=False, includeType:=True, includeMember:=False, count:=0) TestNameAndPredicate(compilation, "System", includeNamespace:=False, includeType:=True, includeMember:=True, count:=0) End Sub <Fact> Public Sub TestSourceNamespace() Dim compilation = GetTestCompilation() TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=True, includeType:=False, includeMember:=False, count:=1) TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=True, includeType:=True, includeMember:=False, count:=1) TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=True, includeType:=False, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=False, includeType:=False, includeMember:=True, count:=0) TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=False, includeType:=True, includeMember:=False, count:=0) TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=False, includeType:=True, includeMember:=True, count:=0) End Sub <Fact> Public Sub TestClassInMergedNamespace() Dim compilation = GetTestCompilation() TestNameAndPredicate(compilation, "Test", includeNamespace:=False, includeType:=True, includeMember:=False, count:=1) TestNameAndPredicate(compilation, "Test", includeNamespace:=False, includeType:=True, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "Test", includeNamespace:=True, includeType:=True, includeMember:=False, count:=1) TestNameAndPredicate(compilation, "Test", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "Test", includeNamespace:=False, includeType:=False, includeMember:=True, count:=0) TestNameAndPredicate(compilation, "Test", includeNamespace:=True, includeType:=False, includeMember:=False, count:=0) TestNameAndPredicate(compilation, "Test", includeNamespace:=True, includeType:=False, includeMember:=True, count:=0) End Sub <Fact> Public Sub TestClassInSourceNamespace() Dim compilation = GetTestCompilation() TestNameAndPredicate(compilation, "Test1", includeNamespace:=False, includeType:=True, includeMember:=False, count:=1) TestNameAndPredicate(compilation, "Test1", includeNamespace:=False, includeType:=True, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "Test1", includeNamespace:=True, includeType:=True, includeMember:=False, count:=1) TestNameAndPredicate(compilation, "Test1", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "Test1", includeNamespace:=False, includeType:=False, includeMember:=True, count:=0) TestNameAndPredicate(compilation, "Test1", includeNamespace:=True, includeType:=False, includeMember:=False, count:=0) TestNameAndPredicate(compilation, "Test1", includeNamespace:=True, includeType:=False, includeMember:=True, count:=0) End Sub <Fact> Public Sub TestMembers() Dim compilation = GetTestCompilation() TestNameAndPredicate(compilation, "myField", includeNamespace:=False, includeType:=False, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "myField", includeNamespace:=False, includeType:=True, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "myField", includeNamespace:=True, includeType:=False, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "myField", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "myField", includeNamespace:=False, includeType:=True, includeMember:=False, count:=0) TestNameAndPredicate(compilation, "myField", includeNamespace:=True, includeType:=False, includeMember:=False, count:=0) TestNameAndPredicate(compilation, "myField", includeNamespace:=True, includeType:=True, includeMember:=False, count:=0) End Sub <Fact> Public Sub TestCaseInsensitivity() Dim compilation = GetTestCompilation() TestName(compilation, "system", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestName(Compilation, "mynamespace", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestName(Compilation, "test", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestName(Compilation, "test1", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestName(Compilation, "myfield", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) End Sub <Fact> Public Sub TestPartialSearch() Dim compilation = GetTestCompilation() TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=False, includeType:=False, includeMember:=True, count:=4) TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=False, includeType:=True, includeMember:=False, count:=4) TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=False, includeType:=True, includeMember:=True, count:=8) TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=False, includeMember:=False, count:=1) TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=False, includeMember:=True, count:=5) TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=True, includeMember:=False, count:=5) TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=True, includeMember:=True, count:=9) TestPredicate(compilation, Function(n) n.IndexOf("enum", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=True, includeMember:=True, count:=2) End Sub Private Shared Function GetTestCompilation() As VisualBasicCompilation Dim source As String = <text> Namespace System Public Class Test End Class End Namespace Namespace MyNamespace Public Class Test1 End Class End Namespace Public Class [MyClass] Private myField As Integer Friend Property MyProperty As Integer Sub MyMethod() End Sub Public Event MyEvent As EventHandler Delegate Function MyDelegate(i As Integer) As String End Class Structure MyStruct End Structure Interface MyInterface End Interface Enum [Enum] EnumValue End Enum </text>.Value Return CreateCompilationWithMscorlib40({source}) End Function Private Shared Sub TestNameAndPredicate(compilation As VisualBasicCompilation, name As String, includeNamespace As Boolean, includeType As Boolean, includeMember As Boolean, count As Integer) TestName(compilation, name, includeNamespace, includeType, includeMember, count) TestPredicate(compilation, Function(n) n = name, includeNamespace, includeType, includeMember, count) End Sub Private Shared Sub TestName(compilation As VisualBasicCompilation, name As String, includeNamespace As Boolean, includeType As Boolean, includeMember As Boolean, count As Integer) Dim filter = ComputeFilter(includeNamespace, includeType, includeMember) Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(name, filter)) Assert.Equal(count, compilation.GetSymbolsWithName(name, filter).Count()) End Sub Private Shared Sub TestPredicate(compilation As VisualBasicCompilation, predicate As Func(Of String, Boolean), includeNamespace As Boolean, includeType As Boolean, includeMember As Boolean, count As Integer) Dim filter = ComputeFilter(includeNamespace, includeType, includeMember) Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(predicate, filter)) Assert.Equal(count, compilation.GetSymbolsWithName(predicate, filter).Count()) End Sub Private Shared Function ComputeFilter(includeNamespace As Boolean, includeType As Boolean, includeMember As Boolean) As SymbolFilter Dim filter = SymbolFilter.None filter = If(includeNamespace, filter Or SymbolFilter.Namespace, filter) filter = If(includeType, filter Or SymbolFilter.Type, filter) filter = If(includeMember, filter Or SymbolFilter.Member, filter) Return filter 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.VisualBasic.UnitTests Public Class SymbolSearchTests Inherits BasicTestBase <Fact> Public Sub TestSymbolFilterNone() Assert.Throws(Of ArgumentException)(Sub() Dim compilation = GetTestCompilation() compilation.ContainsSymbolsWithName(Function(n) True, SymbolFilter.None) End Sub) Assert.Throws(Of ArgumentException)(Sub() Dim compilation = GetTestCompilation() compilation.GetSymbolsWithName(Function(n) True, SymbolFilter.None) End Sub) Assert.Throws(Of ArgumentException)(Sub() Dim compilation = GetTestCompilation() compilation.ContainsSymbolsWithName("", SymbolFilter.None) End Sub) Assert.Throws(Of ArgumentException)(Sub() Dim compilation = GetTestCompilation() compilation.GetSymbolsWithName("", SymbolFilter.None) End Sub) End Sub <Fact> Public Sub TestPredicateNull() Assert.Throws(Of ArgumentNullException)(Sub() Dim compilation = GetTestCompilation() compilation.ContainsSymbolsWithName(predicate:=Nothing) End Sub) Assert.Throws(Of ArgumentNullException)(Sub() Dim compilation = GetTestCompilation() compilation.GetSymbolsWithName(predicate:=Nothing) End Sub) End Sub <Fact> Public Sub TestStringNull() Assert.Throws(Of ArgumentNullException)(Sub() Dim compilation = GetTestCompilation() compilation.ContainsSymbolsWithName(name:=Nothing) End Sub) Assert.Throws(Of ArgumentNullException)(Sub() Dim compilation = GetTestCompilation() compilation.GetSymbolsWithName(name:=Nothing) End Sub) End Sub <Fact> Public Sub TestMergedNamespace() Dim compilation = GetTestCompilation() TestNameAndPredicate(compilation, "System", includeNamespace:=True, includeType:=False, includeMember:=False, count:=1) TestNameAndPredicate(compilation, "System", includeNamespace:=True, includeType:=True, includeMember:=False, count:=1) TestNameAndPredicate(compilation, "System", includeNamespace:=True, includeType:=False, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "System", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "System", includeNamespace:=False, includeType:=False, includeMember:=True, count:=0) TestNameAndPredicate(compilation, "System", includeNamespace:=False, includeType:=True, includeMember:=False, count:=0) TestNameAndPredicate(compilation, "System", includeNamespace:=False, includeType:=True, includeMember:=True, count:=0) End Sub <Fact> Public Sub TestSourceNamespace() Dim compilation = GetTestCompilation() TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=True, includeType:=False, includeMember:=False, count:=1) TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=True, includeType:=True, includeMember:=False, count:=1) TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=True, includeType:=False, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=False, includeType:=False, includeMember:=True, count:=0) TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=False, includeType:=True, includeMember:=False, count:=0) TestNameAndPredicate(compilation, "MyNamespace", includeNamespace:=False, includeType:=True, includeMember:=True, count:=0) End Sub <Fact> Public Sub TestClassInMergedNamespace() Dim compilation = GetTestCompilation() TestNameAndPredicate(compilation, "Test", includeNamespace:=False, includeType:=True, includeMember:=False, count:=1) TestNameAndPredicate(compilation, "Test", includeNamespace:=False, includeType:=True, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "Test", includeNamespace:=True, includeType:=True, includeMember:=False, count:=1) TestNameAndPredicate(compilation, "Test", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "Test", includeNamespace:=False, includeType:=False, includeMember:=True, count:=0) TestNameAndPredicate(compilation, "Test", includeNamespace:=True, includeType:=False, includeMember:=False, count:=0) TestNameAndPredicate(compilation, "Test", includeNamespace:=True, includeType:=False, includeMember:=True, count:=0) End Sub <Fact> Public Sub TestClassInSourceNamespace() Dim compilation = GetTestCompilation() TestNameAndPredicate(compilation, "Test1", includeNamespace:=False, includeType:=True, includeMember:=False, count:=1) TestNameAndPredicate(compilation, "Test1", includeNamespace:=False, includeType:=True, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "Test1", includeNamespace:=True, includeType:=True, includeMember:=False, count:=1) TestNameAndPredicate(compilation, "Test1", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "Test1", includeNamespace:=False, includeType:=False, includeMember:=True, count:=0) TestNameAndPredicate(compilation, "Test1", includeNamespace:=True, includeType:=False, includeMember:=False, count:=0) TestNameAndPredicate(compilation, "Test1", includeNamespace:=True, includeType:=False, includeMember:=True, count:=0) End Sub <Fact> Public Sub TestMembers() Dim compilation = GetTestCompilation() TestNameAndPredicate(compilation, "myField", includeNamespace:=False, includeType:=False, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "myField", includeNamespace:=False, includeType:=True, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "myField", includeNamespace:=True, includeType:=False, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "myField", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestNameAndPredicate(compilation, "myField", includeNamespace:=False, includeType:=True, includeMember:=False, count:=0) TestNameAndPredicate(compilation, "myField", includeNamespace:=True, includeType:=False, includeMember:=False, count:=0) TestNameAndPredicate(compilation, "myField", includeNamespace:=True, includeType:=True, includeMember:=False, count:=0) End Sub <Fact> Public Sub TestCaseInsensitivity() Dim compilation = GetTestCompilation() TestName(compilation, "system", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestName(Compilation, "mynamespace", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestName(Compilation, "test", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestName(Compilation, "test1", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) TestName(Compilation, "myfield", includeNamespace:=True, includeType:=True, includeMember:=True, count:=1) End Sub <Fact> Public Sub TestPartialSearch() Dim compilation = GetTestCompilation() TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=False, includeType:=False, includeMember:=True, count:=4) TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=False, includeType:=True, includeMember:=False, count:=4) TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=False, includeType:=True, includeMember:=True, count:=8) TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=False, includeMember:=False, count:=1) TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=False, includeMember:=True, count:=5) TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=True, includeMember:=False, count:=5) TestPredicate(compilation, Function(n) n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=True, includeMember:=True, count:=9) TestPredicate(compilation, Function(n) n.IndexOf("enum", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace:=True, includeType:=True, includeMember:=True, count:=2) End Sub Private Shared Function GetTestCompilation() As VisualBasicCompilation Dim source As String = <text> Namespace System Public Class Test End Class End Namespace Namespace MyNamespace Public Class Test1 End Class End Namespace Public Class [MyClass] Private myField As Integer Friend Property MyProperty As Integer Sub MyMethod() End Sub Public Event MyEvent As EventHandler Delegate Function MyDelegate(i As Integer) As String End Class Structure MyStruct End Structure Interface MyInterface End Interface Enum [Enum] EnumValue End Enum </text>.Value Return CreateCompilationWithMscorlib40({source}) End Function Private Shared Sub TestNameAndPredicate(compilation As VisualBasicCompilation, name As String, includeNamespace As Boolean, includeType As Boolean, includeMember As Boolean, count As Integer) TestName(compilation, name, includeNamespace, includeType, includeMember, count) TestPredicate(compilation, Function(n) n = name, includeNamespace, includeType, includeMember, count) End Sub Private Shared Sub TestName(compilation As VisualBasicCompilation, name As String, includeNamespace As Boolean, includeType As Boolean, includeMember As Boolean, count As Integer) Dim filter = ComputeFilter(includeNamespace, includeType, includeMember) Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(name, filter)) Assert.Equal(count, compilation.GetSymbolsWithName(name, filter).Count()) End Sub Private Shared Sub TestPredicate(compilation As VisualBasicCompilation, predicate As Func(Of String, Boolean), includeNamespace As Boolean, includeType As Boolean, includeMember As Boolean, count As Integer) Dim filter = ComputeFilter(includeNamespace, includeType, includeMember) Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(predicate, filter)) Assert.Equal(count, compilation.GetSymbolsWithName(predicate, filter).Count()) End Sub Private Shared Function ComputeFilter(includeNamespace As Boolean, includeType As Boolean, includeMember As Boolean) As SymbolFilter Dim filter = SymbolFilter.None filter = If(includeNamespace, filter Or SymbolFilter.Namespace, filter) filter = If(includeType, filter Or SymbolFilter.Type, filter) filter = If(includeMember, filter Or SymbolFilter.Member, filter) Return filter End Function End Class End Namespace
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/GenerateMember/GenerateConstructor/AbstractGenerateConstructorService.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.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor { internal abstract partial class AbstractGenerateConstructorService<TService, TExpressionSyntax> : IGenerateConstructorService where TService : AbstractGenerateConstructorService<TService, TExpressionSyntax> where TExpressionSyntax : SyntaxNode { protected abstract bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType); protected abstract bool IsSimpleNameGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken); protected abstract bool IsConstructorInitializerGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken); protected abstract bool IsImplicitObjectCreation(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken); protected abstract bool TryInitializeImplicitObjectCreation(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn); protected abstract bool TryInitializeSimpleNameGenerationState(SemanticDocument document, SyntaxNode simpleName, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn); protected abstract bool TryInitializeConstructorInitializerGeneration(SemanticDocument document, SyntaxNode constructorInitializer, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn); protected abstract bool TryInitializeSimpleAttributeNameGenerationState(SemanticDocument document, SyntaxNode simpleName, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn); protected abstract ITypeSymbol GetArgumentType(SemanticModel semanticModel, Argument argument, CancellationToken cancellationToken); protected abstract string GenerateNameForExpression(SemanticModel semanticModel, TExpressionSyntax expression, CancellationToken cancellationToken); protected abstract bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType); protected abstract IMethodSymbol GetCurrentConstructor(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken); protected abstract IMethodSymbol GetDelegatedConstructor(SemanticModel semanticModel, IMethodSymbol constructor, CancellationToken cancellationToken); protected bool WillCauseConstructorCycle(State state, SemanticDocument document, IMethodSymbol delegatedConstructor, CancellationToken cancellationToken) { // Check if we're in a constructor. If not, then we can always have our new constructor delegate to // another, as it can't cause a cycle. var currentConstructor = GetCurrentConstructor(document.SemanticModel, state.Token, cancellationToken); if (currentConstructor == null) return false; // If we're delegating to the constructor we're currently in, that would cause a cycle. if (currentConstructor.Equals(delegatedConstructor)) return true; // Delegating to a constructor in the base type can't cause a cycle if (!delegatedConstructor.ContainingType.Equals(currentConstructor.ContainingType)) return false; // We need ensure that delegating constructor won't cause circular dependency. // The chain of dependency can not exceed the number for constructors var constructorsCount = delegatedConstructor.ContainingType.InstanceConstructors.Length; for (var i = 0; i < constructorsCount; i++) { delegatedConstructor = GetDelegatedConstructor(document.SemanticModel, delegatedConstructor, cancellationToken); if (delegatedConstructor == null) return false; if (delegatedConstructor.Equals(currentConstructor)) return true; } return true; } public async Task<ImmutableArray<CodeAction>> GenerateConstructorAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Refactoring_GenerateMember_GenerateConstructor, cancellationToken)) { var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false); var state = await State.GenerateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false); if (state != null) { Contract.ThrowIfNull(state.TypeToGenerateIn); using var _ = ArrayBuilder<CodeAction>.GetInstance(out var result); // If we have any fields we'd like to generate, offer a code action to do that. if (state.ParameterToNewFieldMap.Count > 0) { result.Add(new MyCodeAction( string.Format(FeaturesResources.Generate_constructor_in_0_with_fields, state.TypeToGenerateIn.Name), c => state.GetChangedDocumentAsync(document, withFields: true, withProperties: false, c))); } // Same with a version that generates properties instead. if (state.ParameterToNewPropertyMap.Count > 0) { result.Add(new MyCodeAction( string.Format(FeaturesResources.Generate_constructor_in_0_with_properties, state.TypeToGenerateIn.Name), c => state.GetChangedDocumentAsync(document, withFields: false, withProperties: true, c))); } // Always offer to just generate the constructor and nothing else. result.Add(new MyCodeAction( string.Format(FeaturesResources.Generate_constructor_in_0, state.TypeToGenerateIn.Name), c => state.GetChangedDocumentAsync(document, withFields: false, withProperties: false, c))); return result.ToImmutable(); } } return ImmutableArray<CodeAction>.Empty; } protected static bool IsSymbolAccessible(ISymbol? symbol, SemanticDocument document) { if (symbol == null) { return false; } if (symbol.Kind == SymbolKind.Property) { if (!IsSymbolAccessible(((IPropertySymbol)symbol).SetMethod, document)) { return false; } } // Public and protected constructors are accessible. Internal constructors are // accessible if we have friend access. We can't call the normal accessibility // checkers since they will think that a protected constructor isn't accessible // (since we don't have the destination type that would have access to them yet). switch (symbol.DeclaredAccessibility) { case Accessibility.ProtectedOrInternal: case Accessibility.Protected: case Accessibility.Public: return true; case Accessibility.ProtectedAndInternal: case Accessibility.Internal: return document.SemanticModel.Compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo( symbol.ContainingAssembly); default: return false; } } protected string GenerateNameForArgument(SemanticModel semanticModel, Argument argument, CancellationToken cancellationToken) { // If it named argument then we use the name provided. if (argument.IsNamed) return argument.Name; if (argument.Expression is null) return ITypeSymbolExtensions.DefaultParameterName; var name = this.GenerateNameForExpression(semanticModel, argument.Expression, cancellationToken); return string.IsNullOrEmpty(name) ? ITypeSymbolExtensions.DefaultParameterName : name; } private ImmutableArray<ParameterName> GenerateParameterNames( SemanticDocument document, IEnumerable<Argument> arguments, IList<string> reservedNames, NamingRule parameterNamingRule, CancellationToken cancellationToken) { reservedNames ??= SpecializedCollections.EmptyList<string>(); // We can't change the names of named parameters. Any other names we're flexible on. var isFixed = reservedNames.Select(s => true).Concat( arguments.Select(a => a.IsNamed)).ToImmutableArray(); var parameterNames = reservedNames.Concat( arguments.Select(a => this.GenerateNameForArgument(document.SemanticModel, a, cancellationToken))).ToImmutableArray(); var syntaxFacts = document.Document.GetRequiredLanguageService<ISyntaxFactsService>(); var comparer = syntaxFacts.StringComparer; return NameGenerator.EnsureUniqueness(parameterNames, isFixed, canUse: s => !reservedNames.Any(n => comparer.Equals(s, n))) .Select((name, index) => new ParameterName(name, isFixed[index], parameterNamingRule)) .Skip(reservedNames.Count).ToImmutableArray(); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor { internal abstract partial class AbstractGenerateConstructorService<TService, TExpressionSyntax> : IGenerateConstructorService where TService : AbstractGenerateConstructorService<TService, TExpressionSyntax> where TExpressionSyntax : SyntaxNode { protected abstract bool ContainingTypesOrSelfHasUnsafeKeyword(INamedTypeSymbol containingType); protected abstract bool IsSimpleNameGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken); protected abstract bool IsConstructorInitializerGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken); protected abstract bool IsImplicitObjectCreation(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken); protected abstract bool TryInitializeImplicitObjectCreation(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn); protected abstract bool TryInitializeSimpleNameGenerationState(SemanticDocument document, SyntaxNode simpleName, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn); protected abstract bool TryInitializeConstructorInitializerGeneration(SemanticDocument document, SyntaxNode constructorInitializer, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn); protected abstract bool TryInitializeSimpleAttributeNameGenerationState(SemanticDocument document, SyntaxNode simpleName, CancellationToken cancellationToken, out SyntaxToken token, out ImmutableArray<Argument> arguments, out INamedTypeSymbol typeToGenerateIn); protected abstract ITypeSymbol GetArgumentType(SemanticModel semanticModel, Argument argument, CancellationToken cancellationToken); protected abstract string GenerateNameForExpression(SemanticModel semanticModel, TExpressionSyntax expression, CancellationToken cancellationToken); protected abstract bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType); protected abstract IMethodSymbol GetCurrentConstructor(SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken); protected abstract IMethodSymbol GetDelegatedConstructor(SemanticModel semanticModel, IMethodSymbol constructor, CancellationToken cancellationToken); protected bool WillCauseConstructorCycle(State state, SemanticDocument document, IMethodSymbol delegatedConstructor, CancellationToken cancellationToken) { // Check if we're in a constructor. If not, then we can always have our new constructor delegate to // another, as it can't cause a cycle. var currentConstructor = GetCurrentConstructor(document.SemanticModel, state.Token, cancellationToken); if (currentConstructor == null) return false; // If we're delegating to the constructor we're currently in, that would cause a cycle. if (currentConstructor.Equals(delegatedConstructor)) return true; // Delegating to a constructor in the base type can't cause a cycle if (!delegatedConstructor.ContainingType.Equals(currentConstructor.ContainingType)) return false; // We need ensure that delegating constructor won't cause circular dependency. // The chain of dependency can not exceed the number for constructors var constructorsCount = delegatedConstructor.ContainingType.InstanceConstructors.Length; for (var i = 0; i < constructorsCount; i++) { delegatedConstructor = GetDelegatedConstructor(document.SemanticModel, delegatedConstructor, cancellationToken); if (delegatedConstructor == null) return false; if (delegatedConstructor.Equals(currentConstructor)) return true; } return true; } public async Task<ImmutableArray<CodeAction>> GenerateConstructorAsync(Document document, SyntaxNode node, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Refactoring_GenerateMember_GenerateConstructor, cancellationToken)) { var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false); var state = await State.GenerateAsync((TService)this, semanticDocument, node, cancellationToken).ConfigureAwait(false); if (state != null) { Contract.ThrowIfNull(state.TypeToGenerateIn); using var _ = ArrayBuilder<CodeAction>.GetInstance(out var result); // If we have any fields we'd like to generate, offer a code action to do that. if (state.ParameterToNewFieldMap.Count > 0) { result.Add(new MyCodeAction( string.Format(FeaturesResources.Generate_constructor_in_0_with_fields, state.TypeToGenerateIn.Name), c => state.GetChangedDocumentAsync(document, withFields: true, withProperties: false, c))); } // Same with a version that generates properties instead. if (state.ParameterToNewPropertyMap.Count > 0) { result.Add(new MyCodeAction( string.Format(FeaturesResources.Generate_constructor_in_0_with_properties, state.TypeToGenerateIn.Name), c => state.GetChangedDocumentAsync(document, withFields: false, withProperties: true, c))); } // Always offer to just generate the constructor and nothing else. result.Add(new MyCodeAction( string.Format(FeaturesResources.Generate_constructor_in_0, state.TypeToGenerateIn.Name), c => state.GetChangedDocumentAsync(document, withFields: false, withProperties: false, c))); return result.ToImmutable(); } } return ImmutableArray<CodeAction>.Empty; } protected static bool IsSymbolAccessible(ISymbol? symbol, SemanticDocument document) { if (symbol == null) { return false; } if (symbol.Kind == SymbolKind.Property) { if (!IsSymbolAccessible(((IPropertySymbol)symbol).SetMethod, document)) { return false; } } // Public and protected constructors are accessible. Internal constructors are // accessible if we have friend access. We can't call the normal accessibility // checkers since they will think that a protected constructor isn't accessible // (since we don't have the destination type that would have access to them yet). switch (symbol.DeclaredAccessibility) { case Accessibility.ProtectedOrInternal: case Accessibility.Protected: case Accessibility.Public: return true; case Accessibility.ProtectedAndInternal: case Accessibility.Internal: return document.SemanticModel.Compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo( symbol.ContainingAssembly); default: return false; } } protected string GenerateNameForArgument(SemanticModel semanticModel, Argument argument, CancellationToken cancellationToken) { // If it named argument then we use the name provided. if (argument.IsNamed) return argument.Name; if (argument.Expression is null) return ITypeSymbolExtensions.DefaultParameterName; var name = this.GenerateNameForExpression(semanticModel, argument.Expression, cancellationToken); return string.IsNullOrEmpty(name) ? ITypeSymbolExtensions.DefaultParameterName : name; } private ImmutableArray<ParameterName> GenerateParameterNames( SemanticDocument document, IEnumerable<Argument> arguments, IList<string> reservedNames, NamingRule parameterNamingRule, CancellationToken cancellationToken) { reservedNames ??= SpecializedCollections.EmptyList<string>(); // We can't change the names of named parameters. Any other names we're flexible on. var isFixed = reservedNames.Select(s => true).Concat( arguments.Select(a => a.IsNamed)).ToImmutableArray(); var parameterNames = reservedNames.Concat( arguments.Select(a => this.GenerateNameForArgument(document.SemanticModel, a, cancellationToken))).ToImmutableArray(); var syntaxFacts = document.Document.GetRequiredLanguageService<ISyntaxFactsService>(); var comparer = syntaxFacts.StringComparer; return NameGenerator.EnsureUniqueness(parameterNames, isFixed, canUse: s => !reservedNames.Any(n => comparer.Equals(s, n))) .Select((name, index) => new ParameterName(name, isFixed[index], parameterNamingRule)) .Skip(reservedNames.Count).ToImmutableArray(); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument) : base(title, createChangedDocument, title) { } } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Binder/Semantics/Operators/OperatorKindExtensions.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.Linq.Expressions; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal static partial class OperatorKindExtensions { public static int OperatorIndex(this UnaryOperatorKind kind) { return ((int)kind.Operator() >> 8) - 16; } public static UnaryOperatorKind Operator(this UnaryOperatorKind kind) { return kind & UnaryOperatorKind.OpMask; } public static UnaryOperatorKind Unlifted(this UnaryOperatorKind kind) { return kind & ~UnaryOperatorKind.Lifted; } public static bool IsLifted(this UnaryOperatorKind kind) { return 0 != (kind & UnaryOperatorKind.Lifted); } public static bool IsChecked(this UnaryOperatorKind kind) { return 0 != (kind & UnaryOperatorKind.Checked); } public static bool IsUserDefined(this UnaryOperatorKind kind) { return (kind & UnaryOperatorKind.TypeMask) == UnaryOperatorKind.UserDefined; } public static UnaryOperatorKind OverflowChecks(this UnaryOperatorKind kind) { return kind & UnaryOperatorKind.Checked; } public static UnaryOperatorKind WithOverflowChecksIfApplicable(this UnaryOperatorKind kind, bool enabled) { if (enabled) { // If it's dynamic and we're in a checked context then just mark it as checked, // regardless of whether it is +x -x !x ~x ++x --x x++ or x--. Let the lowering // pass sort out what to do with it. if (kind.IsDynamic()) { return kind | UnaryOperatorKind.Checked; } if (kind.IsIntegral()) { switch (kind.Operator()) { case UnaryOperatorKind.PrefixIncrement: case UnaryOperatorKind.PostfixIncrement: case UnaryOperatorKind.PrefixDecrement: case UnaryOperatorKind.PostfixDecrement: case UnaryOperatorKind.UnaryMinus: return kind | UnaryOperatorKind.Checked; } } return kind; } else { return kind & ~UnaryOperatorKind.Checked; } } public static UnaryOperatorKind OperandTypes(this UnaryOperatorKind kind) { return kind & UnaryOperatorKind.TypeMask; } public static bool IsDynamic(this UnaryOperatorKind kind) { return kind.OperandTypes() == UnaryOperatorKind.Dynamic; } public static bool IsIntegral(this UnaryOperatorKind kind) { switch (kind.OperandTypes()) { case UnaryOperatorKind.SByte: case UnaryOperatorKind.Byte: case UnaryOperatorKind.Short: case UnaryOperatorKind.UShort: case UnaryOperatorKind.Int: case UnaryOperatorKind.UInt: case UnaryOperatorKind.Long: case UnaryOperatorKind.ULong: case UnaryOperatorKind.NInt: case UnaryOperatorKind.NUInt: case UnaryOperatorKind.Char: case UnaryOperatorKind.Enum: case UnaryOperatorKind.Pointer: return true; } return false; } public static UnaryOperatorKind WithType(this UnaryOperatorKind kind, UnaryOperatorKind type) { Debug.Assert(kind == (kind & ~UnaryOperatorKind.TypeMask)); Debug.Assert(type == (type & UnaryOperatorKind.TypeMask)); return kind | type; } public static int OperatorIndex(this BinaryOperatorKind kind) { return ((int)kind.Operator() >> 8) - 16; } public static BinaryOperatorKind Operator(this BinaryOperatorKind kind) { return kind & BinaryOperatorKind.OpMask; } public static BinaryOperatorKind Unlifted(this BinaryOperatorKind kind) { return kind & ~BinaryOperatorKind.Lifted; } public static BinaryOperatorKind OperatorWithLogical(this BinaryOperatorKind kind) { return kind & (BinaryOperatorKind.OpMask | BinaryOperatorKind.Logical); } public static BinaryOperatorKind WithType(this BinaryOperatorKind kind, SpecialType type) { Debug.Assert(kind == (kind & ~BinaryOperatorKind.TypeMask)); switch (type) { case SpecialType.System_Int32: return kind | BinaryOperatorKind.Int; case SpecialType.System_UInt32: return kind | BinaryOperatorKind.UInt; case SpecialType.System_Int64: return kind | BinaryOperatorKind.Long; case SpecialType.System_UInt64: return kind | BinaryOperatorKind.ULong; default: throw ExceptionUtilities.UnexpectedValue(type); } } public static UnaryOperatorKind WithType(this UnaryOperatorKind kind, SpecialType type) { Debug.Assert(kind == (kind & ~UnaryOperatorKind.TypeMask)); switch (type) { case SpecialType.System_Int32: return kind | UnaryOperatorKind.Int; case SpecialType.System_UInt32: return kind | UnaryOperatorKind.UInt; case SpecialType.System_Int64: return kind | UnaryOperatorKind.Long; case SpecialType.System_UInt64: return kind | UnaryOperatorKind.ULong; default: throw ExceptionUtilities.UnexpectedValue(type); } } public static BinaryOperatorKind WithType(this BinaryOperatorKind kind, BinaryOperatorKind type) { Debug.Assert(kind == (kind & ~BinaryOperatorKind.TypeMask)); Debug.Assert(type == (type & BinaryOperatorKind.TypeMask)); return kind | type; } public static bool IsLifted(this BinaryOperatorKind kind) { return 0 != (kind & BinaryOperatorKind.Lifted); } public static bool IsDynamic(this BinaryOperatorKind kind) { return kind.OperandTypes() == BinaryOperatorKind.Dynamic; } public static bool IsComparison(this BinaryOperatorKind kind) { switch (kind.Operator()) { case BinaryOperatorKind.Equal: case BinaryOperatorKind.NotEqual: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.GreaterThanOrEqual: case BinaryOperatorKind.LessThan: case BinaryOperatorKind.LessThanOrEqual: return true; } return false; } public static bool IsChecked(this BinaryOperatorKind kind) { return 0 != (kind & BinaryOperatorKind.Checked); } public static bool EmitsAsCheckedInstruction(this BinaryOperatorKind kind) { if (!kind.IsChecked()) { return false; } switch (kind.Operator()) { case BinaryOperatorKind.Addition: case BinaryOperatorKind.Subtraction: case BinaryOperatorKind.Multiplication: return true; } return false; } public static BinaryOperatorKind WithOverflowChecksIfApplicable(this BinaryOperatorKind kind, bool enabled) { if (enabled) { // If it's a dynamic binop then make it checked. Let the lowering // pass sort out what to do with it. if (kind.IsDynamic()) { return kind | BinaryOperatorKind.Checked; } if (kind.IsIntegral()) { switch (kind.Operator()) { case BinaryOperatorKind.Addition: case BinaryOperatorKind.Subtraction: case BinaryOperatorKind.Multiplication: case BinaryOperatorKind.Division: return kind | BinaryOperatorKind.Checked; } } return kind; } else { return kind & ~BinaryOperatorKind.Checked; } } public static bool IsEnum(this BinaryOperatorKind kind) { switch (kind.OperandTypes()) { case BinaryOperatorKind.Enum: case BinaryOperatorKind.EnumAndUnderlying: case BinaryOperatorKind.UnderlyingAndEnum: return true; } return false; } public static bool IsEnum(this UnaryOperatorKind kind) { return kind.OperandTypes() == UnaryOperatorKind.Enum; } public static bool IsIntegral(this BinaryOperatorKind kind) { switch (kind.OperandTypes()) { case BinaryOperatorKind.Int: case BinaryOperatorKind.UInt: case BinaryOperatorKind.Long: case BinaryOperatorKind.ULong: case BinaryOperatorKind.NInt: case BinaryOperatorKind.NUInt: case BinaryOperatorKind.Char: case BinaryOperatorKind.Enum: case BinaryOperatorKind.EnumAndUnderlying: case BinaryOperatorKind.UnderlyingAndEnum: case BinaryOperatorKind.Pointer: case BinaryOperatorKind.PointerAndInt: case BinaryOperatorKind.PointerAndUInt: case BinaryOperatorKind.PointerAndLong: case BinaryOperatorKind.PointerAndULong: case BinaryOperatorKind.IntAndPointer: case BinaryOperatorKind.UIntAndPointer: case BinaryOperatorKind.LongAndPointer: case BinaryOperatorKind.ULongAndPointer: return true; } return false; } public static bool IsLogical(this BinaryOperatorKind kind) { return 0 != (kind & BinaryOperatorKind.Logical); } public static BinaryOperatorKind OperandTypes(this BinaryOperatorKind kind) { return kind & BinaryOperatorKind.TypeMask; } public static bool IsUserDefined(this BinaryOperatorKind kind) { return (kind & BinaryOperatorKind.TypeMask) == BinaryOperatorKind.UserDefined; } public static bool IsShift(this BinaryOperatorKind kind) { BinaryOperatorKind type = kind.Operator(); return type == BinaryOperatorKind.LeftShift || type == BinaryOperatorKind.RightShift; } public static ExpressionType ToExpressionType(this BinaryOperatorKind kind, bool isCompoundAssignment) { if (isCompoundAssignment) { switch (kind.Operator()) { case BinaryOperatorKind.Multiplication: return ExpressionType.MultiplyAssign; case BinaryOperatorKind.Addition: return ExpressionType.AddAssign; case BinaryOperatorKind.Subtraction: return ExpressionType.SubtractAssign; case BinaryOperatorKind.Division: return ExpressionType.DivideAssign; case BinaryOperatorKind.Remainder: return ExpressionType.ModuloAssign; case BinaryOperatorKind.LeftShift: return ExpressionType.LeftShiftAssign; case BinaryOperatorKind.RightShift: return ExpressionType.RightShiftAssign; case BinaryOperatorKind.And: return ExpressionType.AndAssign; case BinaryOperatorKind.Xor: return ExpressionType.ExclusiveOrAssign; case BinaryOperatorKind.Or: return ExpressionType.OrAssign; } } else { switch (kind.Operator()) { case BinaryOperatorKind.Multiplication: return ExpressionType.Multiply; case BinaryOperatorKind.Addition: return ExpressionType.Add; case BinaryOperatorKind.Subtraction: return ExpressionType.Subtract; case BinaryOperatorKind.Division: return ExpressionType.Divide; case BinaryOperatorKind.Remainder: return ExpressionType.Modulo; case BinaryOperatorKind.LeftShift: return ExpressionType.LeftShift; case BinaryOperatorKind.RightShift: return ExpressionType.RightShift; case BinaryOperatorKind.Equal: return ExpressionType.Equal; case BinaryOperatorKind.NotEqual: return ExpressionType.NotEqual; case BinaryOperatorKind.GreaterThan: return ExpressionType.GreaterThan; case BinaryOperatorKind.LessThan: return ExpressionType.LessThan; case BinaryOperatorKind.GreaterThanOrEqual: return ExpressionType.GreaterThanOrEqual; case BinaryOperatorKind.LessThanOrEqual: return ExpressionType.LessThanOrEqual; case BinaryOperatorKind.And: return ExpressionType.And; case BinaryOperatorKind.Xor: return ExpressionType.ExclusiveOr; case BinaryOperatorKind.Or: return ExpressionType.Or; } } throw ExceptionUtilities.UnexpectedValue(kind.Operator()); } public static ExpressionType ToExpressionType(this UnaryOperatorKind kind) { switch (kind.Operator()) { case UnaryOperatorKind.PrefixIncrement: case UnaryOperatorKind.PostfixIncrement: return ExpressionType.Increment; case UnaryOperatorKind.PostfixDecrement: case UnaryOperatorKind.PrefixDecrement: return ExpressionType.Decrement; case UnaryOperatorKind.UnaryPlus: return ExpressionType.UnaryPlus; case UnaryOperatorKind.UnaryMinus: return ExpressionType.Negate; case UnaryOperatorKind.LogicalNegation: return ExpressionType.Not; case UnaryOperatorKind.BitwiseComplement: return ExpressionType.OnesComplement; case UnaryOperatorKind.True: return ExpressionType.IsTrue; case UnaryOperatorKind.False: return ExpressionType.IsFalse; default: throw ExceptionUtilities.UnexpectedValue(kind.Operator()); } } #if DEBUG public static string Dump(this BinaryOperatorKind kind) { var b = new StringBuilder(); if ((kind & BinaryOperatorKind.Lifted) != 0) b.Append("Lifted"); if ((kind & BinaryOperatorKind.Logical) != 0) b.Append("Logical"); if ((kind & BinaryOperatorKind.Checked) != 0) b.Append("Checked"); var type = kind & BinaryOperatorKind.TypeMask; if (type != 0) b.Append(type.ToString()); var op = kind & BinaryOperatorKind.OpMask; if (op != 0) b.Append(op.ToString()); return b.ToString(); } public static string Dump(this UnaryOperatorKind kind) { var b = new StringBuilder(); if ((kind & UnaryOperatorKind.Lifted) != 0) b.Append("Lifted"); if ((kind & UnaryOperatorKind.Checked) != 0) b.Append("Checked"); var type = kind & UnaryOperatorKind.TypeMask; if (type != 0) b.Append(type.ToString()); var op = kind & UnaryOperatorKind.OpMask; if (op != 0) b.Append(op.ToString()); return b.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. #nullable disable using System.Diagnostics; using System.Linq.Expressions; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal static partial class OperatorKindExtensions { public static int OperatorIndex(this UnaryOperatorKind kind) { return ((int)kind.Operator() >> 8) - 16; } public static UnaryOperatorKind Operator(this UnaryOperatorKind kind) { return kind & UnaryOperatorKind.OpMask; } public static UnaryOperatorKind Unlifted(this UnaryOperatorKind kind) { return kind & ~UnaryOperatorKind.Lifted; } public static bool IsLifted(this UnaryOperatorKind kind) { return 0 != (kind & UnaryOperatorKind.Lifted); } public static bool IsChecked(this UnaryOperatorKind kind) { return 0 != (kind & UnaryOperatorKind.Checked); } public static bool IsUserDefined(this UnaryOperatorKind kind) { return (kind & UnaryOperatorKind.TypeMask) == UnaryOperatorKind.UserDefined; } public static UnaryOperatorKind OverflowChecks(this UnaryOperatorKind kind) { return kind & UnaryOperatorKind.Checked; } public static UnaryOperatorKind WithOverflowChecksIfApplicable(this UnaryOperatorKind kind, bool enabled) { if (enabled) { // If it's dynamic and we're in a checked context then just mark it as checked, // regardless of whether it is +x -x !x ~x ++x --x x++ or x--. Let the lowering // pass sort out what to do with it. if (kind.IsDynamic()) { return kind | UnaryOperatorKind.Checked; } if (kind.IsIntegral()) { switch (kind.Operator()) { case UnaryOperatorKind.PrefixIncrement: case UnaryOperatorKind.PostfixIncrement: case UnaryOperatorKind.PrefixDecrement: case UnaryOperatorKind.PostfixDecrement: case UnaryOperatorKind.UnaryMinus: return kind | UnaryOperatorKind.Checked; } } return kind; } else { return kind & ~UnaryOperatorKind.Checked; } } public static UnaryOperatorKind OperandTypes(this UnaryOperatorKind kind) { return kind & UnaryOperatorKind.TypeMask; } public static bool IsDynamic(this UnaryOperatorKind kind) { return kind.OperandTypes() == UnaryOperatorKind.Dynamic; } public static bool IsIntegral(this UnaryOperatorKind kind) { switch (kind.OperandTypes()) { case UnaryOperatorKind.SByte: case UnaryOperatorKind.Byte: case UnaryOperatorKind.Short: case UnaryOperatorKind.UShort: case UnaryOperatorKind.Int: case UnaryOperatorKind.UInt: case UnaryOperatorKind.Long: case UnaryOperatorKind.ULong: case UnaryOperatorKind.NInt: case UnaryOperatorKind.NUInt: case UnaryOperatorKind.Char: case UnaryOperatorKind.Enum: case UnaryOperatorKind.Pointer: return true; } return false; } public static UnaryOperatorKind WithType(this UnaryOperatorKind kind, UnaryOperatorKind type) { Debug.Assert(kind == (kind & ~UnaryOperatorKind.TypeMask)); Debug.Assert(type == (type & UnaryOperatorKind.TypeMask)); return kind | type; } public static int OperatorIndex(this BinaryOperatorKind kind) { return ((int)kind.Operator() >> 8) - 16; } public static BinaryOperatorKind Operator(this BinaryOperatorKind kind) { return kind & BinaryOperatorKind.OpMask; } public static BinaryOperatorKind Unlifted(this BinaryOperatorKind kind) { return kind & ~BinaryOperatorKind.Lifted; } public static BinaryOperatorKind OperatorWithLogical(this BinaryOperatorKind kind) { return kind & (BinaryOperatorKind.OpMask | BinaryOperatorKind.Logical); } public static BinaryOperatorKind WithType(this BinaryOperatorKind kind, SpecialType type) { Debug.Assert(kind == (kind & ~BinaryOperatorKind.TypeMask)); switch (type) { case SpecialType.System_Int32: return kind | BinaryOperatorKind.Int; case SpecialType.System_UInt32: return kind | BinaryOperatorKind.UInt; case SpecialType.System_Int64: return kind | BinaryOperatorKind.Long; case SpecialType.System_UInt64: return kind | BinaryOperatorKind.ULong; default: throw ExceptionUtilities.UnexpectedValue(type); } } public static UnaryOperatorKind WithType(this UnaryOperatorKind kind, SpecialType type) { Debug.Assert(kind == (kind & ~UnaryOperatorKind.TypeMask)); switch (type) { case SpecialType.System_Int32: return kind | UnaryOperatorKind.Int; case SpecialType.System_UInt32: return kind | UnaryOperatorKind.UInt; case SpecialType.System_Int64: return kind | UnaryOperatorKind.Long; case SpecialType.System_UInt64: return kind | UnaryOperatorKind.ULong; default: throw ExceptionUtilities.UnexpectedValue(type); } } public static BinaryOperatorKind WithType(this BinaryOperatorKind kind, BinaryOperatorKind type) { Debug.Assert(kind == (kind & ~BinaryOperatorKind.TypeMask)); Debug.Assert(type == (type & BinaryOperatorKind.TypeMask)); return kind | type; } public static bool IsLifted(this BinaryOperatorKind kind) { return 0 != (kind & BinaryOperatorKind.Lifted); } public static bool IsDynamic(this BinaryOperatorKind kind) { return kind.OperandTypes() == BinaryOperatorKind.Dynamic; } public static bool IsComparison(this BinaryOperatorKind kind) { switch (kind.Operator()) { case BinaryOperatorKind.Equal: case BinaryOperatorKind.NotEqual: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.GreaterThanOrEqual: case BinaryOperatorKind.LessThan: case BinaryOperatorKind.LessThanOrEqual: return true; } return false; } public static bool IsChecked(this BinaryOperatorKind kind) { return 0 != (kind & BinaryOperatorKind.Checked); } public static bool EmitsAsCheckedInstruction(this BinaryOperatorKind kind) { if (!kind.IsChecked()) { return false; } switch (kind.Operator()) { case BinaryOperatorKind.Addition: case BinaryOperatorKind.Subtraction: case BinaryOperatorKind.Multiplication: return true; } return false; } public static BinaryOperatorKind WithOverflowChecksIfApplicable(this BinaryOperatorKind kind, bool enabled) { if (enabled) { // If it's a dynamic binop then make it checked. Let the lowering // pass sort out what to do with it. if (kind.IsDynamic()) { return kind | BinaryOperatorKind.Checked; } if (kind.IsIntegral()) { switch (kind.Operator()) { case BinaryOperatorKind.Addition: case BinaryOperatorKind.Subtraction: case BinaryOperatorKind.Multiplication: case BinaryOperatorKind.Division: return kind | BinaryOperatorKind.Checked; } } return kind; } else { return kind & ~BinaryOperatorKind.Checked; } } public static bool IsEnum(this BinaryOperatorKind kind) { switch (kind.OperandTypes()) { case BinaryOperatorKind.Enum: case BinaryOperatorKind.EnumAndUnderlying: case BinaryOperatorKind.UnderlyingAndEnum: return true; } return false; } public static bool IsEnum(this UnaryOperatorKind kind) { return kind.OperandTypes() == UnaryOperatorKind.Enum; } public static bool IsIntegral(this BinaryOperatorKind kind) { switch (kind.OperandTypes()) { case BinaryOperatorKind.Int: case BinaryOperatorKind.UInt: case BinaryOperatorKind.Long: case BinaryOperatorKind.ULong: case BinaryOperatorKind.NInt: case BinaryOperatorKind.NUInt: case BinaryOperatorKind.Char: case BinaryOperatorKind.Enum: case BinaryOperatorKind.EnumAndUnderlying: case BinaryOperatorKind.UnderlyingAndEnum: case BinaryOperatorKind.Pointer: case BinaryOperatorKind.PointerAndInt: case BinaryOperatorKind.PointerAndUInt: case BinaryOperatorKind.PointerAndLong: case BinaryOperatorKind.PointerAndULong: case BinaryOperatorKind.IntAndPointer: case BinaryOperatorKind.UIntAndPointer: case BinaryOperatorKind.LongAndPointer: case BinaryOperatorKind.ULongAndPointer: return true; } return false; } public static bool IsLogical(this BinaryOperatorKind kind) { return 0 != (kind & BinaryOperatorKind.Logical); } public static BinaryOperatorKind OperandTypes(this BinaryOperatorKind kind) { return kind & BinaryOperatorKind.TypeMask; } public static bool IsUserDefined(this BinaryOperatorKind kind) { return (kind & BinaryOperatorKind.TypeMask) == BinaryOperatorKind.UserDefined; } public static bool IsShift(this BinaryOperatorKind kind) { BinaryOperatorKind type = kind.Operator(); return type == BinaryOperatorKind.LeftShift || type == BinaryOperatorKind.RightShift; } public static ExpressionType ToExpressionType(this BinaryOperatorKind kind, bool isCompoundAssignment) { if (isCompoundAssignment) { switch (kind.Operator()) { case BinaryOperatorKind.Multiplication: return ExpressionType.MultiplyAssign; case BinaryOperatorKind.Addition: return ExpressionType.AddAssign; case BinaryOperatorKind.Subtraction: return ExpressionType.SubtractAssign; case BinaryOperatorKind.Division: return ExpressionType.DivideAssign; case BinaryOperatorKind.Remainder: return ExpressionType.ModuloAssign; case BinaryOperatorKind.LeftShift: return ExpressionType.LeftShiftAssign; case BinaryOperatorKind.RightShift: return ExpressionType.RightShiftAssign; case BinaryOperatorKind.And: return ExpressionType.AndAssign; case BinaryOperatorKind.Xor: return ExpressionType.ExclusiveOrAssign; case BinaryOperatorKind.Or: return ExpressionType.OrAssign; } } else { switch (kind.Operator()) { case BinaryOperatorKind.Multiplication: return ExpressionType.Multiply; case BinaryOperatorKind.Addition: return ExpressionType.Add; case BinaryOperatorKind.Subtraction: return ExpressionType.Subtract; case BinaryOperatorKind.Division: return ExpressionType.Divide; case BinaryOperatorKind.Remainder: return ExpressionType.Modulo; case BinaryOperatorKind.LeftShift: return ExpressionType.LeftShift; case BinaryOperatorKind.RightShift: return ExpressionType.RightShift; case BinaryOperatorKind.Equal: return ExpressionType.Equal; case BinaryOperatorKind.NotEqual: return ExpressionType.NotEqual; case BinaryOperatorKind.GreaterThan: return ExpressionType.GreaterThan; case BinaryOperatorKind.LessThan: return ExpressionType.LessThan; case BinaryOperatorKind.GreaterThanOrEqual: return ExpressionType.GreaterThanOrEqual; case BinaryOperatorKind.LessThanOrEqual: return ExpressionType.LessThanOrEqual; case BinaryOperatorKind.And: return ExpressionType.And; case BinaryOperatorKind.Xor: return ExpressionType.ExclusiveOr; case BinaryOperatorKind.Or: return ExpressionType.Or; } } throw ExceptionUtilities.UnexpectedValue(kind.Operator()); } public static ExpressionType ToExpressionType(this UnaryOperatorKind kind) { switch (kind.Operator()) { case UnaryOperatorKind.PrefixIncrement: case UnaryOperatorKind.PostfixIncrement: return ExpressionType.Increment; case UnaryOperatorKind.PostfixDecrement: case UnaryOperatorKind.PrefixDecrement: return ExpressionType.Decrement; case UnaryOperatorKind.UnaryPlus: return ExpressionType.UnaryPlus; case UnaryOperatorKind.UnaryMinus: return ExpressionType.Negate; case UnaryOperatorKind.LogicalNegation: return ExpressionType.Not; case UnaryOperatorKind.BitwiseComplement: return ExpressionType.OnesComplement; case UnaryOperatorKind.True: return ExpressionType.IsTrue; case UnaryOperatorKind.False: return ExpressionType.IsFalse; default: throw ExceptionUtilities.UnexpectedValue(kind.Operator()); } } #if DEBUG public static string Dump(this BinaryOperatorKind kind) { var b = new StringBuilder(); if ((kind & BinaryOperatorKind.Lifted) != 0) b.Append("Lifted"); if ((kind & BinaryOperatorKind.Logical) != 0) b.Append("Logical"); if ((kind & BinaryOperatorKind.Checked) != 0) b.Append("Checked"); var type = kind & BinaryOperatorKind.TypeMask; if (type != 0) b.Append(type.ToString()); var op = kind & BinaryOperatorKind.OpMask; if (op != 0) b.Append(op.ToString()); return b.ToString(); } public static string Dump(this UnaryOperatorKind kind) { var b = new StringBuilder(); if ((kind & UnaryOperatorKind.Lifted) != 0) b.Append("Lifted"); if ((kind & UnaryOperatorKind.Checked) != 0) b.Append("Checked"); var type = kind & UnaryOperatorKind.TypeMask; if (type != 0) b.Append(type.ToString()); var op = kind & UnaryOperatorKind.OpMask; if (op != 0) b.Append(op.ToString()); return b.ToString(); } #endif } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasicTest/Structure/MultilineLambdaStructureTests.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.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class MultilineLambdaStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of MultiLineLambdaExpressionSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New MultilineLambdaStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestInClassScope() As Task Const code = " Class C Dim r = {|span:$$Sub() End Sub|} End Class " Await VerifyBlockSpansAsync(code, Region("span", "Sub() ...", autoCollapse:=False)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestInMethodScope() As Task Const code = " Class C Sub M() Dim r = {|span:$$Sub() End Sub|} End Sub End Class " Await VerifyBlockSpansAsync(code, Region("span", "Sub() ...", autoCollapse:=False)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestFunction() As Task Const code = " Class C Dim r = {|span:$$Function(x As Integer, y As List(Of String)) As Func(Of Integer, Func(Of String, Integer)) End Function|} End Class " Await VerifyBlockSpansAsync(code, Region("span", "Function(x As Integer, y As List(Of String)) As Func(Of Integer, Func(Of String, Integer)) ...", autoCollapse:=False)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestInArgumentContext() As Task Const code = " Class C Sub M() MethodCall({|span:$$Function(x As Integer, y As List(Of String)) As List(Of List(Of String)) Return Nothing End Function|}) End Sub End Class " Await VerifyBlockSpansAsync(code, Region("span", "Function(x As Integer, y As List(Of String)) As List(Of List(Of String)) ...", autoCollapse:=False)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestLambdaWithReturnType() As Task Const code = " Class C Sub M() Dim f = {|span:$$Function(x) As Integer Return x End Function|} End Sub End Class " Await VerifyBlockSpansAsync(code, Region("span", "Function(x) As Integer ...", autoCollapse:=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 Microsoft.CodeAnalysis.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Structure Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Outlining Public Class MultilineLambdaStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of MultiLineLambdaExpressionSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New MultilineLambdaStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestInClassScope() As Task Const code = " Class C Dim r = {|span:$$Sub() End Sub|} End Class " Await VerifyBlockSpansAsync(code, Region("span", "Sub() ...", autoCollapse:=False)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestInMethodScope() As Task Const code = " Class C Sub M() Dim r = {|span:$$Sub() End Sub|} End Sub End Class " Await VerifyBlockSpansAsync(code, Region("span", "Sub() ...", autoCollapse:=False)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestFunction() As Task Const code = " Class C Dim r = {|span:$$Function(x As Integer, y As List(Of String)) As Func(Of Integer, Func(Of String, Integer)) End Function|} End Class " Await VerifyBlockSpansAsync(code, Region("span", "Function(x As Integer, y As List(Of String)) As Func(Of Integer, Func(Of String, Integer)) ...", autoCollapse:=False)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestInArgumentContext() As Task Const code = " Class C Sub M() MethodCall({|span:$$Function(x As Integer, y As List(Of String)) As List(Of List(Of String)) Return Nothing End Function|}) End Sub End Class " Await VerifyBlockSpansAsync(code, Region("span", "Function(x As Integer, y As List(Of String)) As List(Of List(Of String)) ...", autoCollapse:=False)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestLambdaWithReturnType() As Task Const code = " Class C Sub M() Dim f = {|span:$$Function(x) As Integer Return x End Function|} End Sub End Class " Await VerifyBlockSpansAsync(code, Region("span", "Function(x) As Integer ...", autoCollapse:=False)) End Function End Class End Namespace
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/VisualBasic/Impl/ProjectSystemShim/Interop/IVbCompilerHost.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.InteropServices Imports Microsoft.VisualStudio.Shell.Interop Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop <Guid("782CB503-84B1-4b8f-9AAD-A12B75905015"), ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> Friend Interface IVbCompilerHost ''' <summary> ''' Output a string to the standard output (console, file, pane, etc.) ''' </summary> Sub OutputString(<MarshalAs(UnmanagedType.LPWStr)> [string] As String) ''' <summary> ''' Returns the system SDK directory, where mscorlib.dll and Microsoft.VisualBasic.dll is ''' located. ''' </summary> <PreserveSig> Function GetSdkPath(<MarshalAs(UnmanagedType.BStr), Out> ByRef sdkPath As String) As Integer ''' <summary> ''' Get the target library type. ''' </summary> Function GetTargetLibraryType() As VBTargetLibraryType End Interface End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.InteropServices Imports Microsoft.VisualStudio.Shell.Interop Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.ProjectSystemShim.Interop <Guid("782CB503-84B1-4b8f-9AAD-A12B75905015"), ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)> Friend Interface IVbCompilerHost ''' <summary> ''' Output a string to the standard output (console, file, pane, etc.) ''' </summary> Sub OutputString(<MarshalAs(UnmanagedType.LPWStr)> [string] As String) ''' <summary> ''' Returns the system SDK directory, where mscorlib.dll and Microsoft.VisualBasic.dll is ''' located. ''' </summary> <PreserveSig> Function GetSdkPath(<MarshalAs(UnmanagedType.BStr), Out> ByRef sdkPath As String) As Integer ''' <summary> ''' Get the target library type. ''' </summary> Function GetTargetLibraryType() As VBTargetLibraryType End Interface End Namespace
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/Core/Analyzers/RemoveUnnecessaryCast/AbstractRemoveUnnecessaryCastDiagnosticAnalyzer.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 Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryCast { internal abstract class AbstractRemoveUnnecessaryCastDiagnosticAnalyzer< TLanguageKindEnum, TCastExpression> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TLanguageKindEnum : struct where TCastExpression : SyntaxNode { protected AbstractRemoveUnnecessaryCastDiagnosticAnalyzer() : base(IDEDiagnosticIds.RemoveUnnecessaryCastDiagnosticId, EnforceOnBuildValues.RemoveUnnecessaryCast, option: null, new LocalizableResourceString(nameof(AnalyzersResources.Remove_Unnecessary_Cast), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(CompilerExtensionsResources.Cast_is_redundant), CompilerExtensionsResources.ResourceManager, typeof(CompilerExtensionsResources)), isUnnecessary: true) { } protected abstract ImmutableArray<TLanguageKindEnum> SyntaxKindsOfInterest { get; } protected abstract TextSpan GetFadeSpan(TCastExpression node); protected abstract bool IsUnnecessaryCast(SemanticModel model, TCastExpression node, CancellationToken cancellationToken); public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKindsOfInterest); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var diagnostic = TryRemoveCastExpression( context.SemanticModel, (TCastExpression)context.Node, context.CancellationToken); if (diagnostic != null) { context.ReportDiagnostic(diagnostic); } } private Diagnostic? TryRemoveCastExpression(SemanticModel model, TCastExpression node, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!IsUnnecessaryCast(model, node, cancellationToken)) { return null; } var tree = model.SyntaxTree; if (tree.OverlapsHiddenPosition(node.Span, cancellationToken)) { return null; } return Diagnostic.Create( Descriptor, node.SyntaxTree.GetLocation(GetFadeSpan(node)), ImmutableArray.Create(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. using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryCast { internal abstract class AbstractRemoveUnnecessaryCastDiagnosticAnalyzer< TLanguageKindEnum, TCastExpression> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TLanguageKindEnum : struct where TCastExpression : SyntaxNode { protected AbstractRemoveUnnecessaryCastDiagnosticAnalyzer() : base(IDEDiagnosticIds.RemoveUnnecessaryCastDiagnosticId, EnforceOnBuildValues.RemoveUnnecessaryCast, option: null, new LocalizableResourceString(nameof(AnalyzersResources.Remove_Unnecessary_Cast), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(CompilerExtensionsResources.Cast_is_redundant), CompilerExtensionsResources.ResourceManager, typeof(CompilerExtensionsResources)), isUnnecessary: true) { } protected abstract ImmutableArray<TLanguageKindEnum> SyntaxKindsOfInterest { get; } protected abstract TextSpan GetFadeSpan(TCastExpression node); protected abstract bool IsUnnecessaryCast(SemanticModel model, TCastExpression node, CancellationToken cancellationToken); public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, SyntaxKindsOfInterest); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var diagnostic = TryRemoveCastExpression( context.SemanticModel, (TCastExpression)context.Node, context.CancellationToken); if (diagnostic != null) { context.ReportDiagnostic(diagnostic); } } private Diagnostic? TryRemoveCastExpression(SemanticModel model, TCastExpression node, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!IsUnnecessaryCast(model, node, cancellationToken)) { return null; } var tree = model.SyntaxTree; if (tree.OverlapsHiddenPosition(node.Span, cancellationToken)) { return null; } return Diagnostic.Create( Descriptor, node.SyntaxTree.GetLocation(GetFadeSpan(node)), ImmutableArray.Create(node.GetLocation())); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Diagnostics/NamingStyles/EditorConfigNamingStyleParserTests.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 Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.EditorConfigNamingStyleParser; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.NamingStyles { public class EditorConfigNamingStyleParserTests { [Fact] public static void TestPascalCaseRule() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.severity"] = "warning", ["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.symbols"] = "method_and_property_symbols", ["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.style"] = "pascal_case_style", ["dotnet_naming_symbols.method_and_property_symbols.applicable_kinds"] = "method,property", ["dotnet_naming_symbols.method_and_property_symbols.applicable_accessibilities"] = "*", ["dotnet_naming_style.pascal_case_style.capitalization"] = "pascal_case" }; var result = ParseDictionary(dictionary); Assert.Single(result.NamingRules); var namingRule = result.NamingRules.Single(); Assert.Single(result.NamingStyles); var namingStyle = result.NamingStyles.Single(); Assert.Single(result.SymbolSpecifications); var symbolSpec = result.SymbolSpecifications.Single(); Assert.Equal(namingStyle.ID, namingRule.NamingStyleID); Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID); Assert.Equal(ReportDiagnostic.Warn, namingRule.EnforcementLevel); Assert.Equal("method_and_property_symbols", symbolSpec.Name); var expectedApplicableSymbolKindList = new[] { new SymbolKindOrTypeKind(MethodKind.Ordinary), new SymbolKindOrTypeKind(SymbolKind.Property) }; AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList); Assert.Empty(symbolSpec.RequiredModifierList); var expectedApplicableAccessibilityList = new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal }; AssertEx.SetEqual(expectedApplicableAccessibilityList, symbolSpec.ApplicableAccessibilityList); Assert.Equal("pascal_case_style", namingStyle.Name); Assert.Equal("", namingStyle.Prefix); Assert.Equal("", namingStyle.Suffix); Assert.Equal("", namingStyle.WordSeparator); Assert.Equal(Capitalization.PascalCase, namingStyle.CapitalizationScheme); } [Fact] [WorkItem(40705, "https://github.com/dotnet/roslyn/issues/40705")] public static void TestPascalCaseRuleWithKeyCapitalization() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.severity"] = "warning", ["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.symbols"] = "Method_and_Property_symbols", ["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.style"] = "Pascal_Case_style", ["dotnet_naming_symbols.method_and_property_symbols.applicable_kinds"] = "method,property", ["dotnet_naming_symbols.method_and_property_symbols.applicable_accessibilities"] = "*", ["dotnet_naming_style.pascal_case_style.capitalization"] = "pascal_case" }; var result = ParseDictionary(dictionary); var namingRule = Assert.Single(result.NamingRules); var namingStyle = Assert.Single(result.NamingStyles); var symbolSpec = Assert.Single(result.SymbolSpecifications); Assert.Equal(namingStyle.ID, namingRule.NamingStyleID); Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID); Assert.Equal(ReportDiagnostic.Warn, namingRule.EnforcementLevel); } [Fact] public static void TestAsyncMethodsAndLocalFunctionsRule() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_rule.async_methods_must_end_with_async.severity"] = "error", ["dotnet_naming_rule.async_methods_must_end_with_async.symbols"] = "method_symbols", ["dotnet_naming_rule.async_methods_must_end_with_async.style"] = "end_in_async_style", ["dotnet_naming_symbols.method_symbols.applicable_kinds"] = "method,local_function", ["dotnet_naming_symbols.method_symbols.required_modifiers"] = "async", ["dotnet_naming_style.end_in_async_style.capitalization "] = "pascal_case", ["dotnet_naming_style.end_in_async_style.required_suffix"] = "Async", }; var result = ParseDictionary(dictionary); Assert.Single(result.NamingRules); var namingRule = result.NamingRules.Single(); Assert.Single(result.NamingStyles); var namingStyle = result.NamingStyles.Single(); Assert.Single(result.SymbolSpecifications); var symbolSpec = result.SymbolSpecifications.Single(); Assert.Equal(namingStyle.ID, namingRule.NamingStyleID); Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID); Assert.Equal(ReportDiagnostic.Error, namingRule.EnforcementLevel); Assert.Equal("method_symbols", symbolSpec.Name); var expectedApplicableSymbolKindList = new[] { new SymbolKindOrTypeKind(MethodKind.Ordinary), new SymbolKindOrTypeKind(MethodKind.LocalFunction) }; AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList); Assert.Single(symbolSpec.RequiredModifierList); Assert.Contains(new ModifierKind(ModifierKindEnum.IsAsync), symbolSpec.RequiredModifierList); Assert.Equal( new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal }, symbolSpec.ApplicableAccessibilityList); Assert.Equal("end_in_async_style", namingStyle.Name); Assert.Equal("", namingStyle.Prefix); Assert.Equal("Async", namingStyle.Suffix); Assert.Equal("", namingStyle.WordSeparator); Assert.Equal(Capitalization.PascalCase, namingStyle.CapitalizationScheme); } [Fact] public static void TestRuleWithoutCapitalization() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_rule.async_methods_must_end_with_async.symbols"] = "any_async_methods", ["dotnet_naming_rule.async_methods_must_end_with_async.style"] = "end_in_async", ["dotnet_naming_rule.async_methods_must_end_with_async.severity"] = "suggestion", ["dotnet_naming_symbols.any_async_methods.applicable_kinds"] = "method", ["dotnet_naming_symbols.any_async_methods.applicable_accessibilities"] = "*", ["dotnet_naming_symbols.any_async_methods.required_modifiers"] = "async", ["dotnet_naming_style.end_in_async.required_suffix"] = "Async", }; var result = ParseDictionary(dictionary); Assert.Empty(result.NamingStyles); } [Fact] public static void TestPublicMembersCapitalizedRule() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_rule.public_members_must_be_capitalized.severity"] = "suggestion", ["dotnet_naming_rule.public_members_must_be_capitalized.symbols"] = "public_symbols", ["dotnet_naming_rule.public_members_must_be_capitalized.style"] = "first_word_upper_case_style", ["dotnet_naming_symbols.public_symbols.applicable_kinds"] = "property,method,field,event,delegate", ["dotnet_naming_symbols.public_symbols.applicable_accessibilities"] = "public,internal,protected,protected_internal", ["dotnet_naming_style.first_word_upper_case_style.capitalization"] = "first_word_upper", }; var result = ParseDictionary(dictionary); Assert.Single(result.NamingRules); var namingRule = result.NamingRules.Single(); Assert.Single(result.NamingStyles); var namingStyle = result.NamingStyles.Single(); Assert.Single(result.SymbolSpecifications); var symbolSpec = result.SymbolSpecifications.Single(); Assert.Equal(namingStyle.ID, namingRule.NamingStyleID); Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID); Assert.Equal(ReportDiagnostic.Info, namingRule.EnforcementLevel); Assert.Equal("public_symbols", symbolSpec.Name); var expectedApplicableSymbolKindList = new[] { new SymbolKindOrTypeKind(SymbolKind.Property), new SymbolKindOrTypeKind(MethodKind.Ordinary), new SymbolKindOrTypeKind(SymbolKind.Field), new SymbolKindOrTypeKind(SymbolKind.Event), new SymbolKindOrTypeKind(TypeKind.Delegate) }; AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList); var expectedApplicableAccessibilityList = new[] { Accessibility.Public, Accessibility.Internal, Accessibility.Protected, Accessibility.ProtectedOrInternal }; AssertEx.SetEqual(expectedApplicableAccessibilityList, symbolSpec.ApplicableAccessibilityList); Assert.Empty(symbolSpec.RequiredModifierList); Assert.Equal("first_word_upper_case_style", namingStyle.Name); Assert.Equal("", namingStyle.Prefix); Assert.Equal("", namingStyle.Suffix); Assert.Equal("", namingStyle.WordSeparator); Assert.Equal(Capitalization.FirstUpper, namingStyle.CapitalizationScheme); } [Fact] public static void TestNonPublicMembersLowerCaseRule() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_rule.non_public_members_must_be_lower_case.severity"] = "incorrect", ["dotnet_naming_rule.non_public_members_must_be_lower_case.symbols "] = "non_public_symbols", ["dotnet_naming_rule.non_public_members_must_be_lower_case.style "] = "all_lower_case_style", ["dotnet_naming_symbols.non_public_symbols.applicable_kinds "] = "property,method,field,event,delegate", ["dotnet_naming_symbols.non_public_symbols.applicable_accessibilities"] = "private", ["dotnet_naming_style.all_lower_case_style.capitalization"] = "all_lower", }; var result = ParseDictionary(dictionary); Assert.Single(result.NamingRules); var namingRule = result.NamingRules.Single(); Assert.Single(result.NamingStyles); var namingStyle = result.NamingStyles.Single(); Assert.Single(result.SymbolSpecifications); var symbolSpec = result.SymbolSpecifications.Single(); Assert.Equal(namingStyle.ID, namingRule.NamingStyleID); Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID); Assert.Equal(ReportDiagnostic.Hidden, namingRule.EnforcementLevel); Assert.Equal("non_public_symbols", symbolSpec.Name); var expectedApplicableSymbolKindList = new[] { new SymbolKindOrTypeKind(SymbolKind.Property), new SymbolKindOrTypeKind(MethodKind.Ordinary), new SymbolKindOrTypeKind(SymbolKind.Field), new SymbolKindOrTypeKind(SymbolKind.Event), new SymbolKindOrTypeKind(TypeKind.Delegate) }; AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList); Assert.Single(symbolSpec.ApplicableAccessibilityList); Assert.Contains(Accessibility.Private, symbolSpec.ApplicableAccessibilityList); Assert.Empty(symbolSpec.RequiredModifierList); Assert.Equal("all_lower_case_style", namingStyle.Name); Assert.Equal("", namingStyle.Prefix); Assert.Equal("", namingStyle.Suffix); Assert.Equal("", namingStyle.WordSeparator); Assert.Equal(Capitalization.AllLower, namingStyle.CapitalizationScheme); } [Fact] public static void TestParametersAndLocalsAreCamelCaseRule() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_rule.parameters_and_locals_are_camel_case.severity"] = "suggestion", ["dotnet_naming_rule.parameters_and_locals_are_camel_case.symbols"] = "parameters_and_locals", ["dotnet_naming_rule.parameters_and_locals_are_camel_case.style"] = "camel_case_style", ["dotnet_naming_symbols.parameters_and_locals.applicable_kinds"] = "parameter,local", ["dotnet_naming_style.camel_case_style.capitalization"] = "camel_case", }; var result = ParseDictionary(dictionary); Assert.Single(result.NamingRules); var namingRule = result.NamingRules.Single(); Assert.Single(result.NamingStyles); var namingStyle = result.NamingStyles.Single(); Assert.Single(result.SymbolSpecifications); var symbolSpec = result.SymbolSpecifications.Single(); Assert.Equal(namingStyle.ID, namingRule.NamingStyleID); Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID); Assert.Equal(ReportDiagnostic.Info, namingRule.EnforcementLevel); Assert.Equal("parameters_and_locals", symbolSpec.Name); var expectedApplicableSymbolKindList = new[] { new SymbolKindOrTypeKind(SymbolKind.Parameter), new SymbolKindOrTypeKind(SymbolKind.Local), }; AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList); Assert.Equal( new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal }, symbolSpec.ApplicableAccessibilityList); Assert.Empty(symbolSpec.RequiredModifierList); Assert.Equal("camel_case_style", namingStyle.Name); Assert.Equal("", namingStyle.Prefix); Assert.Equal("", namingStyle.Suffix); Assert.Equal("", namingStyle.WordSeparator); Assert.Equal(Capitalization.CamelCase, namingStyle.CapitalizationScheme); } [Fact] public static void TestLocalFunctionsAreCamelCaseRule() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_rule.local_functions_are_camel_case.severity"] = "suggestion", ["dotnet_naming_rule.local_functions_are_camel_case.symbols"] = "local_functions", ["dotnet_naming_rule.local_functions_are_camel_case.style"] = "camel_case_style", ["dotnet_naming_symbols.local_functions.applicable_kinds"] = "local_function", ["dotnet_naming_style.camel_case_style.capitalization"] = "camel_case", }; var result = ParseDictionary(dictionary); Assert.Single(result.NamingRules); var namingRule = result.NamingRules.Single(); Assert.Single(result.NamingStyles); var namingStyle = result.NamingStyles.Single(); Assert.Single(result.SymbolSpecifications); var symbolSpec = result.SymbolSpecifications.Single(); Assert.Equal(namingStyle.ID, namingRule.NamingStyleID); Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID); Assert.Equal(ReportDiagnostic.Info, namingRule.EnforcementLevel); Assert.Equal("local_functions", symbolSpec.Name); var expectedApplicableSymbolKindList = new[] { new SymbolKindOrTypeKind(MethodKind.LocalFunction) }; AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList); Assert.Equal( new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal }, symbolSpec.ApplicableAccessibilityList); Assert.Empty(symbolSpec.RequiredModifierList); Assert.Equal("camel_case_style", namingStyle.Name); Assert.Equal("", namingStyle.Prefix); Assert.Equal("", namingStyle.Suffix); Assert.Equal("", namingStyle.WordSeparator); Assert.Equal(Capitalization.CamelCase, namingStyle.CapitalizationScheme); } [Fact] public static void TestNoRulesAreReturned() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_symbols.non_public_symbols.applicable_kinds "] = "property,method,field,event,delegate", ["dotnet_naming_symbols.non_public_symbols.applicable_accessibilities"] = "private", ["dotnet_naming_style.all_lower_case_style.capitalization"] = "all_lower", }; var result = ParseDictionary(dictionary); Assert.Empty(result.NamingRules); Assert.Empty(result.NamingStyles); Assert.Empty(result.SymbolSpecifications); } [Theory] [InlineData("property,method", new object[] { SymbolKind.Property, MethodKind.Ordinary })] [InlineData("namespace", new object[] { SymbolKind.Namespace })] [InlineData("type_parameter", new object[] { SymbolKind.TypeParameter })] [InlineData("interface", new object[] { TypeKind.Interface })] [InlineData("*", new object[] { SymbolKind.Namespace, TypeKind.Class, TypeKind.Struct, TypeKind.Interface, TypeKind.Enum, SymbolKind.Property, MethodKind.Ordinary, MethodKind.LocalFunction, SymbolKind.Field, SymbolKind.Event, TypeKind.Delegate, SymbolKind.Parameter, SymbolKind.TypeParameter, SymbolKind.Local })] [InlineData(null, new object[] { SymbolKind.Namespace, TypeKind.Class, TypeKind.Struct, TypeKind.Interface, TypeKind.Enum, SymbolKind.Property, MethodKind.Ordinary, MethodKind.LocalFunction, SymbolKind.Field, SymbolKind.Event, TypeKind.Delegate, SymbolKind.Parameter, SymbolKind.TypeParameter, SymbolKind.Local })] [InlineData("property,method,invalid", new object[] { SymbolKind.Property, MethodKind.Ordinary })] [InlineData("invalid", new object[] { })] [InlineData("", new object[] { })] [WorkItem(20907, "https://github.com/dotnet/roslyn/issues/20907")] public static void TestApplicableKindsParse(string specification, object[] typeOrSymbolKinds) { var rule = new Dictionary<string, string>() { ["dotnet_naming_rule.kinds_parse.severity"] = "error", ["dotnet_naming_rule.kinds_parse.symbols"] = "kinds", ["dotnet_naming_rule.kinds_parse.style"] = "pascal_case", ["dotnet_naming_style.pascal_case.capitalization "] = "pascal_case", }; if (specification != null) { rule["dotnet_naming_symbols.kinds.applicable_kinds"] = specification; } var kinds = typeOrSymbolKinds.Select(NamingStylesTestOptionSets.ToSymbolKindOrTypeKind).ToArray(); var result = ParseDictionary(rule); Assert.Equal(kinds, result.SymbolSpecifications.SelectMany(x => x.ApplicableSymbolKindList)); } [Theory] [InlineData("internal,protected_internal", new[] { Accessibility.Internal, Accessibility.ProtectedOrInternal })] [InlineData("friend,protected_friend", new[] { Accessibility.Friend, Accessibility.ProtectedOrFriend })] [InlineData("private_protected", new[] { Accessibility.ProtectedAndInternal })] [InlineData("local", new[] { Accessibility.NotApplicable })] [InlineData("*", new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal })] [InlineData(null, new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal })] [InlineData("internal,protected,invalid", new[] { Accessibility.Internal, Accessibility.Protected })] [InlineData("invalid", new Accessibility[] { })] [InlineData("", new Accessibility[] { })] [WorkItem(20907, "https://github.com/dotnet/roslyn/issues/20907")] public static void TestApplicableAccessibilitiesParse(string specification, Accessibility[] accessibilities) { var rule = new Dictionary<string, string>() { ["dotnet_naming_rule.accessibilities_parse.severity"] = "error", ["dotnet_naming_rule.accessibilities_parse.symbols"] = "accessibilities", ["dotnet_naming_rule.accessibilities_parse.style"] = "pascal_case", ["dotnet_naming_style.pascal_case.capitalization "] = "pascal_case", }; if (specification != null) { rule["dotnet_naming_symbols.accessibilities.applicable_accessibilities"] = specification; } var result = ParseDictionary(rule); Assert.Equal(accessibilities, result.SymbolSpecifications.SelectMany(x => x.ApplicableAccessibilityList)); } [Fact] public static void TestRequiredModifiersParse() { var charpRule = new Dictionary<string, string>() { ["dotnet_naming_rule.modifiers_parse.severity"] = "error", ["dotnet_naming_rule.modifiers_parse.symbols"] = "modifiers", ["dotnet_naming_rule.modifiers_parse.style"] = "pascal_case", ["dotnet_naming_symbols.modifiers.required_modifiers"] = "abstract,static", ["dotnet_naming_style.pascal_case.capitalization "] = "pascal_case", }; var vbRule = new Dictionary<string, string>() { ["dotnet_naming_rule.modifiers_parse.severity"] = "error", ["dotnet_naming_rule.modifiers_parse.symbols"] = "modifiers", ["dotnet_naming_rule.modifiers_parse.style"] = "pascal_case", ["dotnet_naming_symbols.modifiers.required_modifiers"] = "must_inherit,shared", ["dotnet_naming_style.pascal_case.capitalization "] = "pascal_case", }; var csharpResult = ParseDictionary(charpRule); var vbResult = ParseDictionary(vbRule); Assert.Equal(csharpResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.Modifier)), vbResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.Modifier))); Assert.Equal(csharpResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.ModifierKindWrapper)), vbResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.ModifierKindWrapper))); } [Fact] [WorkItem(38513, "https://github.com/dotnet/roslyn/issues/38513")] public static void TestPrefixParse() { var rule = new Dictionary<string, string>() { ["dotnet_naming_style.pascal_case_and_prefix_style.required_prefix"] = "I", ["dotnet_naming_style.pascal_case_and_prefix_style.capitalization"] = "pascal_case", ["dotnet_naming_symbols.symbols.applicable_kinds"] = "interface", ["dotnet_naming_symbols.symbols.applicable_accessibilities"] = "*", ["dotnet_naming_rule.must_be_pascal_cased_and_prefixed.symbols"] = "symbols", ["dotnet_naming_rule.must_be_pascal_cased_and_prefixed.style"] = "pascal_case_and_prefix_style", ["dotnet_naming_rule.must_be_pascal_cased_and_prefixed.severity"] = "warning", }; var result = ParseDictionary(rule); Assert.Single(result.NamingRules); var namingRule = result.NamingRules.Single(); Assert.Single(result.NamingStyles); var namingStyle = result.NamingStyles.Single(); Assert.Single(result.SymbolSpecifications); var symbolSpec = result.SymbolSpecifications.Single(); Assert.Equal(namingStyle.ID, namingRule.NamingStyleID); Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID); Assert.Equal(ReportDiagnostic.Warn, namingRule.EnforcementLevel); Assert.Equal("symbols", symbolSpec.Name); var expectedApplicableTypeKindList = new[] { new SymbolKindOrTypeKind(TypeKind.Interface) }; AssertEx.SetEqual(expectedApplicableTypeKindList, symbolSpec.ApplicableSymbolKindList); Assert.Equal("pascal_case_and_prefix_style", namingStyle.Name); Assert.Equal("I", namingStyle.Prefix); Assert.Equal("", namingStyle.Suffix); Assert.Equal("", namingStyle.WordSeparator); Assert.Equal(Capitalization.PascalCase, namingStyle.CapitalizationScheme); } [Fact] public static void TestEditorConfigParseForApplicableSymbolKinds() { var symbolSpecifications = CreateDefaultSymbolSpecification(); foreach (var applicableSymbolKind in symbolSpecifications.ApplicableSymbolKindList) { var editorConfigString = EditorConfigNamingStyleParser.ToEditorConfigString(ImmutableArray.Create(applicableSymbolKind)); Assert.True(!string.IsNullOrEmpty(editorConfigString)); } } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.NamingStyles; using Roslyn.Test.Utilities; using Xunit; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.EditorConfigNamingStyleParser; using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.NamingStyles { public class EditorConfigNamingStyleParserTests { [Fact] public static void TestPascalCaseRule() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.severity"] = "warning", ["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.symbols"] = "method_and_property_symbols", ["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.style"] = "pascal_case_style", ["dotnet_naming_symbols.method_and_property_symbols.applicable_kinds"] = "method,property", ["dotnet_naming_symbols.method_and_property_symbols.applicable_accessibilities"] = "*", ["dotnet_naming_style.pascal_case_style.capitalization"] = "pascal_case" }; var result = ParseDictionary(dictionary); Assert.Single(result.NamingRules); var namingRule = result.NamingRules.Single(); Assert.Single(result.NamingStyles); var namingStyle = result.NamingStyles.Single(); Assert.Single(result.SymbolSpecifications); var symbolSpec = result.SymbolSpecifications.Single(); Assert.Equal(namingStyle.ID, namingRule.NamingStyleID); Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID); Assert.Equal(ReportDiagnostic.Warn, namingRule.EnforcementLevel); Assert.Equal("method_and_property_symbols", symbolSpec.Name); var expectedApplicableSymbolKindList = new[] { new SymbolKindOrTypeKind(MethodKind.Ordinary), new SymbolKindOrTypeKind(SymbolKind.Property) }; AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList); Assert.Empty(symbolSpec.RequiredModifierList); var expectedApplicableAccessibilityList = new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal }; AssertEx.SetEqual(expectedApplicableAccessibilityList, symbolSpec.ApplicableAccessibilityList); Assert.Equal("pascal_case_style", namingStyle.Name); Assert.Equal("", namingStyle.Prefix); Assert.Equal("", namingStyle.Suffix); Assert.Equal("", namingStyle.WordSeparator); Assert.Equal(Capitalization.PascalCase, namingStyle.CapitalizationScheme); } [Fact] [WorkItem(40705, "https://github.com/dotnet/roslyn/issues/40705")] public static void TestPascalCaseRuleWithKeyCapitalization() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.severity"] = "warning", ["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.symbols"] = "Method_and_Property_symbols", ["dotnet_naming_rule.methods_and_properties_must_be_pascal_case.style"] = "Pascal_Case_style", ["dotnet_naming_symbols.method_and_property_symbols.applicable_kinds"] = "method,property", ["dotnet_naming_symbols.method_and_property_symbols.applicable_accessibilities"] = "*", ["dotnet_naming_style.pascal_case_style.capitalization"] = "pascal_case" }; var result = ParseDictionary(dictionary); var namingRule = Assert.Single(result.NamingRules); var namingStyle = Assert.Single(result.NamingStyles); var symbolSpec = Assert.Single(result.SymbolSpecifications); Assert.Equal(namingStyle.ID, namingRule.NamingStyleID); Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID); Assert.Equal(ReportDiagnostic.Warn, namingRule.EnforcementLevel); } [Fact] public static void TestAsyncMethodsAndLocalFunctionsRule() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_rule.async_methods_must_end_with_async.severity"] = "error", ["dotnet_naming_rule.async_methods_must_end_with_async.symbols"] = "method_symbols", ["dotnet_naming_rule.async_methods_must_end_with_async.style"] = "end_in_async_style", ["dotnet_naming_symbols.method_symbols.applicable_kinds"] = "method,local_function", ["dotnet_naming_symbols.method_symbols.required_modifiers"] = "async", ["dotnet_naming_style.end_in_async_style.capitalization "] = "pascal_case", ["dotnet_naming_style.end_in_async_style.required_suffix"] = "Async", }; var result = ParseDictionary(dictionary); Assert.Single(result.NamingRules); var namingRule = result.NamingRules.Single(); Assert.Single(result.NamingStyles); var namingStyle = result.NamingStyles.Single(); Assert.Single(result.SymbolSpecifications); var symbolSpec = result.SymbolSpecifications.Single(); Assert.Equal(namingStyle.ID, namingRule.NamingStyleID); Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID); Assert.Equal(ReportDiagnostic.Error, namingRule.EnforcementLevel); Assert.Equal("method_symbols", symbolSpec.Name); var expectedApplicableSymbolKindList = new[] { new SymbolKindOrTypeKind(MethodKind.Ordinary), new SymbolKindOrTypeKind(MethodKind.LocalFunction) }; AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList); Assert.Single(symbolSpec.RequiredModifierList); Assert.Contains(new ModifierKind(ModifierKindEnum.IsAsync), symbolSpec.RequiredModifierList); Assert.Equal( new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal }, symbolSpec.ApplicableAccessibilityList); Assert.Equal("end_in_async_style", namingStyle.Name); Assert.Equal("", namingStyle.Prefix); Assert.Equal("Async", namingStyle.Suffix); Assert.Equal("", namingStyle.WordSeparator); Assert.Equal(Capitalization.PascalCase, namingStyle.CapitalizationScheme); } [Fact] public static void TestRuleWithoutCapitalization() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_rule.async_methods_must_end_with_async.symbols"] = "any_async_methods", ["dotnet_naming_rule.async_methods_must_end_with_async.style"] = "end_in_async", ["dotnet_naming_rule.async_methods_must_end_with_async.severity"] = "suggestion", ["dotnet_naming_symbols.any_async_methods.applicable_kinds"] = "method", ["dotnet_naming_symbols.any_async_methods.applicable_accessibilities"] = "*", ["dotnet_naming_symbols.any_async_methods.required_modifiers"] = "async", ["dotnet_naming_style.end_in_async.required_suffix"] = "Async", }; var result = ParseDictionary(dictionary); Assert.Empty(result.NamingStyles); } [Fact] public static void TestPublicMembersCapitalizedRule() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_rule.public_members_must_be_capitalized.severity"] = "suggestion", ["dotnet_naming_rule.public_members_must_be_capitalized.symbols"] = "public_symbols", ["dotnet_naming_rule.public_members_must_be_capitalized.style"] = "first_word_upper_case_style", ["dotnet_naming_symbols.public_symbols.applicable_kinds"] = "property,method,field,event,delegate", ["dotnet_naming_symbols.public_symbols.applicable_accessibilities"] = "public,internal,protected,protected_internal", ["dotnet_naming_style.first_word_upper_case_style.capitalization"] = "first_word_upper", }; var result = ParseDictionary(dictionary); Assert.Single(result.NamingRules); var namingRule = result.NamingRules.Single(); Assert.Single(result.NamingStyles); var namingStyle = result.NamingStyles.Single(); Assert.Single(result.SymbolSpecifications); var symbolSpec = result.SymbolSpecifications.Single(); Assert.Equal(namingStyle.ID, namingRule.NamingStyleID); Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID); Assert.Equal(ReportDiagnostic.Info, namingRule.EnforcementLevel); Assert.Equal("public_symbols", symbolSpec.Name); var expectedApplicableSymbolKindList = new[] { new SymbolKindOrTypeKind(SymbolKind.Property), new SymbolKindOrTypeKind(MethodKind.Ordinary), new SymbolKindOrTypeKind(SymbolKind.Field), new SymbolKindOrTypeKind(SymbolKind.Event), new SymbolKindOrTypeKind(TypeKind.Delegate) }; AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList); var expectedApplicableAccessibilityList = new[] { Accessibility.Public, Accessibility.Internal, Accessibility.Protected, Accessibility.ProtectedOrInternal }; AssertEx.SetEqual(expectedApplicableAccessibilityList, symbolSpec.ApplicableAccessibilityList); Assert.Empty(symbolSpec.RequiredModifierList); Assert.Equal("first_word_upper_case_style", namingStyle.Name); Assert.Equal("", namingStyle.Prefix); Assert.Equal("", namingStyle.Suffix); Assert.Equal("", namingStyle.WordSeparator); Assert.Equal(Capitalization.FirstUpper, namingStyle.CapitalizationScheme); } [Fact] public static void TestNonPublicMembersLowerCaseRule() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_rule.non_public_members_must_be_lower_case.severity"] = "incorrect", ["dotnet_naming_rule.non_public_members_must_be_lower_case.symbols "] = "non_public_symbols", ["dotnet_naming_rule.non_public_members_must_be_lower_case.style "] = "all_lower_case_style", ["dotnet_naming_symbols.non_public_symbols.applicable_kinds "] = "property,method,field,event,delegate", ["dotnet_naming_symbols.non_public_symbols.applicable_accessibilities"] = "private", ["dotnet_naming_style.all_lower_case_style.capitalization"] = "all_lower", }; var result = ParseDictionary(dictionary); Assert.Single(result.NamingRules); var namingRule = result.NamingRules.Single(); Assert.Single(result.NamingStyles); var namingStyle = result.NamingStyles.Single(); Assert.Single(result.SymbolSpecifications); var symbolSpec = result.SymbolSpecifications.Single(); Assert.Equal(namingStyle.ID, namingRule.NamingStyleID); Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID); Assert.Equal(ReportDiagnostic.Hidden, namingRule.EnforcementLevel); Assert.Equal("non_public_symbols", symbolSpec.Name); var expectedApplicableSymbolKindList = new[] { new SymbolKindOrTypeKind(SymbolKind.Property), new SymbolKindOrTypeKind(MethodKind.Ordinary), new SymbolKindOrTypeKind(SymbolKind.Field), new SymbolKindOrTypeKind(SymbolKind.Event), new SymbolKindOrTypeKind(TypeKind.Delegate) }; AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList); Assert.Single(symbolSpec.ApplicableAccessibilityList); Assert.Contains(Accessibility.Private, symbolSpec.ApplicableAccessibilityList); Assert.Empty(symbolSpec.RequiredModifierList); Assert.Equal("all_lower_case_style", namingStyle.Name); Assert.Equal("", namingStyle.Prefix); Assert.Equal("", namingStyle.Suffix); Assert.Equal("", namingStyle.WordSeparator); Assert.Equal(Capitalization.AllLower, namingStyle.CapitalizationScheme); } [Fact] public static void TestParametersAndLocalsAreCamelCaseRule() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_rule.parameters_and_locals_are_camel_case.severity"] = "suggestion", ["dotnet_naming_rule.parameters_and_locals_are_camel_case.symbols"] = "parameters_and_locals", ["dotnet_naming_rule.parameters_and_locals_are_camel_case.style"] = "camel_case_style", ["dotnet_naming_symbols.parameters_and_locals.applicable_kinds"] = "parameter,local", ["dotnet_naming_style.camel_case_style.capitalization"] = "camel_case", }; var result = ParseDictionary(dictionary); Assert.Single(result.NamingRules); var namingRule = result.NamingRules.Single(); Assert.Single(result.NamingStyles); var namingStyle = result.NamingStyles.Single(); Assert.Single(result.SymbolSpecifications); var symbolSpec = result.SymbolSpecifications.Single(); Assert.Equal(namingStyle.ID, namingRule.NamingStyleID); Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID); Assert.Equal(ReportDiagnostic.Info, namingRule.EnforcementLevel); Assert.Equal("parameters_and_locals", symbolSpec.Name); var expectedApplicableSymbolKindList = new[] { new SymbolKindOrTypeKind(SymbolKind.Parameter), new SymbolKindOrTypeKind(SymbolKind.Local), }; AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList); Assert.Equal( new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal }, symbolSpec.ApplicableAccessibilityList); Assert.Empty(symbolSpec.RequiredModifierList); Assert.Equal("camel_case_style", namingStyle.Name); Assert.Equal("", namingStyle.Prefix); Assert.Equal("", namingStyle.Suffix); Assert.Equal("", namingStyle.WordSeparator); Assert.Equal(Capitalization.CamelCase, namingStyle.CapitalizationScheme); } [Fact] public static void TestLocalFunctionsAreCamelCaseRule() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_rule.local_functions_are_camel_case.severity"] = "suggestion", ["dotnet_naming_rule.local_functions_are_camel_case.symbols"] = "local_functions", ["dotnet_naming_rule.local_functions_are_camel_case.style"] = "camel_case_style", ["dotnet_naming_symbols.local_functions.applicable_kinds"] = "local_function", ["dotnet_naming_style.camel_case_style.capitalization"] = "camel_case", }; var result = ParseDictionary(dictionary); Assert.Single(result.NamingRules); var namingRule = result.NamingRules.Single(); Assert.Single(result.NamingStyles); var namingStyle = result.NamingStyles.Single(); Assert.Single(result.SymbolSpecifications); var symbolSpec = result.SymbolSpecifications.Single(); Assert.Equal(namingStyle.ID, namingRule.NamingStyleID); Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID); Assert.Equal(ReportDiagnostic.Info, namingRule.EnforcementLevel); Assert.Equal("local_functions", symbolSpec.Name); var expectedApplicableSymbolKindList = new[] { new SymbolKindOrTypeKind(MethodKind.LocalFunction) }; AssertEx.SetEqual(expectedApplicableSymbolKindList, symbolSpec.ApplicableSymbolKindList); Assert.Equal( new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal }, symbolSpec.ApplicableAccessibilityList); Assert.Empty(symbolSpec.RequiredModifierList); Assert.Equal("camel_case_style", namingStyle.Name); Assert.Equal("", namingStyle.Prefix); Assert.Equal("", namingStyle.Suffix); Assert.Equal("", namingStyle.WordSeparator); Assert.Equal(Capitalization.CamelCase, namingStyle.CapitalizationScheme); } [Fact] public static void TestNoRulesAreReturned() { var dictionary = new Dictionary<string, string>() { ["dotnet_naming_symbols.non_public_symbols.applicable_kinds "] = "property,method,field,event,delegate", ["dotnet_naming_symbols.non_public_symbols.applicable_accessibilities"] = "private", ["dotnet_naming_style.all_lower_case_style.capitalization"] = "all_lower", }; var result = ParseDictionary(dictionary); Assert.Empty(result.NamingRules); Assert.Empty(result.NamingStyles); Assert.Empty(result.SymbolSpecifications); } [Theory] [InlineData("property,method", new object[] { SymbolKind.Property, MethodKind.Ordinary })] [InlineData("namespace", new object[] { SymbolKind.Namespace })] [InlineData("type_parameter", new object[] { SymbolKind.TypeParameter })] [InlineData("interface", new object[] { TypeKind.Interface })] [InlineData("*", new object[] { SymbolKind.Namespace, TypeKind.Class, TypeKind.Struct, TypeKind.Interface, TypeKind.Enum, SymbolKind.Property, MethodKind.Ordinary, MethodKind.LocalFunction, SymbolKind.Field, SymbolKind.Event, TypeKind.Delegate, SymbolKind.Parameter, SymbolKind.TypeParameter, SymbolKind.Local })] [InlineData(null, new object[] { SymbolKind.Namespace, TypeKind.Class, TypeKind.Struct, TypeKind.Interface, TypeKind.Enum, SymbolKind.Property, MethodKind.Ordinary, MethodKind.LocalFunction, SymbolKind.Field, SymbolKind.Event, TypeKind.Delegate, SymbolKind.Parameter, SymbolKind.TypeParameter, SymbolKind.Local })] [InlineData("property,method,invalid", new object[] { SymbolKind.Property, MethodKind.Ordinary })] [InlineData("invalid", new object[] { })] [InlineData("", new object[] { })] [WorkItem(20907, "https://github.com/dotnet/roslyn/issues/20907")] public static void TestApplicableKindsParse(string specification, object[] typeOrSymbolKinds) { var rule = new Dictionary<string, string>() { ["dotnet_naming_rule.kinds_parse.severity"] = "error", ["dotnet_naming_rule.kinds_parse.symbols"] = "kinds", ["dotnet_naming_rule.kinds_parse.style"] = "pascal_case", ["dotnet_naming_style.pascal_case.capitalization "] = "pascal_case", }; if (specification != null) { rule["dotnet_naming_symbols.kinds.applicable_kinds"] = specification; } var kinds = typeOrSymbolKinds.Select(NamingStylesTestOptionSets.ToSymbolKindOrTypeKind).ToArray(); var result = ParseDictionary(rule); Assert.Equal(kinds, result.SymbolSpecifications.SelectMany(x => x.ApplicableSymbolKindList)); } [Theory] [InlineData("internal,protected_internal", new[] { Accessibility.Internal, Accessibility.ProtectedOrInternal })] [InlineData("friend,protected_friend", new[] { Accessibility.Friend, Accessibility.ProtectedOrFriend })] [InlineData("private_protected", new[] { Accessibility.ProtectedAndInternal })] [InlineData("local", new[] { Accessibility.NotApplicable })] [InlineData("*", new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal })] [InlineData(null, new[] { Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal })] [InlineData("internal,protected,invalid", new[] { Accessibility.Internal, Accessibility.Protected })] [InlineData("invalid", new Accessibility[] { })] [InlineData("", new Accessibility[] { })] [WorkItem(20907, "https://github.com/dotnet/roslyn/issues/20907")] public static void TestApplicableAccessibilitiesParse(string specification, Accessibility[] accessibilities) { var rule = new Dictionary<string, string>() { ["dotnet_naming_rule.accessibilities_parse.severity"] = "error", ["dotnet_naming_rule.accessibilities_parse.symbols"] = "accessibilities", ["dotnet_naming_rule.accessibilities_parse.style"] = "pascal_case", ["dotnet_naming_style.pascal_case.capitalization "] = "pascal_case", }; if (specification != null) { rule["dotnet_naming_symbols.accessibilities.applicable_accessibilities"] = specification; } var result = ParseDictionary(rule); Assert.Equal(accessibilities, result.SymbolSpecifications.SelectMany(x => x.ApplicableAccessibilityList)); } [Fact] public static void TestRequiredModifiersParse() { var charpRule = new Dictionary<string, string>() { ["dotnet_naming_rule.modifiers_parse.severity"] = "error", ["dotnet_naming_rule.modifiers_parse.symbols"] = "modifiers", ["dotnet_naming_rule.modifiers_parse.style"] = "pascal_case", ["dotnet_naming_symbols.modifiers.required_modifiers"] = "abstract,static", ["dotnet_naming_style.pascal_case.capitalization "] = "pascal_case", }; var vbRule = new Dictionary<string, string>() { ["dotnet_naming_rule.modifiers_parse.severity"] = "error", ["dotnet_naming_rule.modifiers_parse.symbols"] = "modifiers", ["dotnet_naming_rule.modifiers_parse.style"] = "pascal_case", ["dotnet_naming_symbols.modifiers.required_modifiers"] = "must_inherit,shared", ["dotnet_naming_style.pascal_case.capitalization "] = "pascal_case", }; var csharpResult = ParseDictionary(charpRule); var vbResult = ParseDictionary(vbRule); Assert.Equal(csharpResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.Modifier)), vbResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.Modifier))); Assert.Equal(csharpResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.ModifierKindWrapper)), vbResult.SymbolSpecifications.SelectMany(x => x.RequiredModifierList.Select(y => y.ModifierKindWrapper))); } [Fact] [WorkItem(38513, "https://github.com/dotnet/roslyn/issues/38513")] public static void TestPrefixParse() { var rule = new Dictionary<string, string>() { ["dotnet_naming_style.pascal_case_and_prefix_style.required_prefix"] = "I", ["dotnet_naming_style.pascal_case_and_prefix_style.capitalization"] = "pascal_case", ["dotnet_naming_symbols.symbols.applicable_kinds"] = "interface", ["dotnet_naming_symbols.symbols.applicable_accessibilities"] = "*", ["dotnet_naming_rule.must_be_pascal_cased_and_prefixed.symbols"] = "symbols", ["dotnet_naming_rule.must_be_pascal_cased_and_prefixed.style"] = "pascal_case_and_prefix_style", ["dotnet_naming_rule.must_be_pascal_cased_and_prefixed.severity"] = "warning", }; var result = ParseDictionary(rule); Assert.Single(result.NamingRules); var namingRule = result.NamingRules.Single(); Assert.Single(result.NamingStyles); var namingStyle = result.NamingStyles.Single(); Assert.Single(result.SymbolSpecifications); var symbolSpec = result.SymbolSpecifications.Single(); Assert.Equal(namingStyle.ID, namingRule.NamingStyleID); Assert.Equal(symbolSpec.ID, namingRule.SymbolSpecificationID); Assert.Equal(ReportDiagnostic.Warn, namingRule.EnforcementLevel); Assert.Equal("symbols", symbolSpec.Name); var expectedApplicableTypeKindList = new[] { new SymbolKindOrTypeKind(TypeKind.Interface) }; AssertEx.SetEqual(expectedApplicableTypeKindList, symbolSpec.ApplicableSymbolKindList); Assert.Equal("pascal_case_and_prefix_style", namingStyle.Name); Assert.Equal("I", namingStyle.Prefix); Assert.Equal("", namingStyle.Suffix); Assert.Equal("", namingStyle.WordSeparator); Assert.Equal(Capitalization.PascalCase, namingStyle.CapitalizationScheme); } [Fact] public static void TestEditorConfigParseForApplicableSymbolKinds() { var symbolSpecifications = CreateDefaultSymbolSpecification(); foreach (var applicableSymbolKind in symbolSpecifications.ApplicableSymbolKindList) { var editorConfigString = EditorConfigNamingStyleParser.ToEditorConfigString(ImmutableArray.Create(applicableSymbolKind)); Assert.True(!string.IsNullOrEmpty(editorConfigString)); } } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/Syntax/Syntax.xsd
<?xml version="1.0" encoding="utf-8"?> <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://schemas.microsoft.com/VisualStudio/Roslyn/Compiler" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="define-parse-tree"> <xs:complexType> <xs:sequence> <xs:element name="definitions"> <xs:complexType> <xs:sequence> <xs:choice maxOccurs="unbounded"> <xs:element maxOccurs="unbounded" name="node-structure"> <xs:complexType> <xs:sequence> <xs:choice maxOccurs="unbounded"> <xs:element name="description" type="xs:string" /> <xs:element maxOccurs="unbounded" name="lm-equiv"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="name" type="xs:string" use="required" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> <xs:element maxOccurs="unbounded" name="native-equiv"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="name" type="xs:string" use="required" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> <xs:element maxOccurs="unbounded" name="spec-section" type="xs:string" /> <xs:element maxOccurs="unbounded" name="grammar" type="xs:string" /> <xs:element maxOccurs="unbounded" name="node-kind"> <xs:complexType mixed="true"> <xs:sequence minOccurs="0"> <xs:element minOccurs="0" name="description" type="xs:string" /> <xs:element minOccurs="0" maxOccurs="unbounded" name="lm-equiv"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="name" type="xs:string" use="required" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> <xs:element minOccurs="0" maxOccurs="unbounded" name="native-equiv"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="name" type="xs:string" use="required" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required" /> <xs:attribute name="token-text" type="xs:string" use="optional" /> </xs:complexType> </xs:element> <xs:element maxOccurs="unbounded" name="child"> <xs:complexType mixed="true"> <xs:sequence minOccurs="0"> <xs:element name="description" type="xs:string" /> <xs:element minOccurs="0" maxOccurs="unbounded" name="lm-equiv"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="name" type="xs:string" use="required" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> <xs:element minOccurs="0" maxOccurs="unbounded" name="native-equiv"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="name" type="xs:string" use="required" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> <xs:element minOccurs="0" maxOccurs="unbounded" name="kind"> <xs:complexType> <xs:attribute name="name" type="xs:string" use="required" /> <xs:attribute name="node-kind" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required" /> <xs:attribute name="kind" type="xs:string" use="optional" /> <xs:attribute name="optional" type="xs:boolean" use="optional" /> <xs:attribute name="list" type="xs:boolean" use="optional" /> <xs:attribute name="separator-kind" type="xs:string" use="optional" /> <xs:attribute name="separator-name" type="xs:string" use="optional" /> <xs:attribute name="min-count" type="xs:unsignedByte" use="optional" /> <xs:attribute name="order" type="xs:byte" use="optional" /> <xs:attribute name="optional-elements" type="xs:boolean" use="optional" /> <xs:attribute name="syntax-facts-internal" type="xs:boolean" use="optional" /> </xs:complexType> </xs:element> <xs:element name="field"> <xs:complexType> <xs:sequence minOccurs="0"> <xs:element name="description" type="xs:string" /> <xs:element minOccurs="0" name="lm-equiv"> <xs:complexType> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> <xs:element minOccurs="0" name="native-equiv"> <xs:complexType> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required" /> <xs:attribute name="type" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:choice> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required" /> <xs:attribute name="abstract" type="xs:boolean" use="optional" /> <xs:attribute name="partial" type="xs:boolean" use="optional" /> <xs:attribute name="predefined" type="xs:boolean" use="optional" /> <xs:attribute name="root" type="xs:boolean" use="optional" /> <xs:attribute name="parent" type="xs:string" use="optional" /> <xs:attribute name="token-root" type="xs:boolean" use="optional" /> <xs:attribute name="default-trailing-trivia" type="xs:string" use="optional" /> <xs:attribute name="has-default-factory" type="xs:boolean" use="optional" /> <xs:attribute name="no-factory" type="xs:boolean" use="optional" /> <xs:attribute name="trivia-root" type="xs:boolean" use="optional" /> <xs:attribute name="syntax-facts-internal" type="xs:boolean" use="optional" /> </xs:complexType> </xs:element> <xs:element maxOccurs="unbounded" name="node-kind-alias"> <xs:complexType> <xs:sequence> <xs:element name="description" type="xs:string" /> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required" /> <xs:attribute name="alias" type="xs:string" use="required" /> </xs:complexType> </xs:element> <xs:element name="enumeration"> <xs:complexType> <xs:sequence> <xs:element name="description" type="xs:string" /> <xs:element minOccurs="0" name="lm-equiv"> <xs:complexType> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> <xs:element maxOccurs="unbounded" name="native-equiv"> <xs:complexType> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> <xs:element name="enumerators"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" name="enumerator"> <xs:complexType> <xs:sequence minOccurs="0"> <xs:element name="description" type="xs:string" /> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:choice> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="namespace" type="xs:string" use="required" /> <xs:attribute name="visitor" type="xs:string" use="required" /> <xs:attribute name="rewrite-visitor" type="xs:string" use="required" /> <xs:attribute name="factory-class" type="xs:string" use="required" /> <xs:attribute name="contextual-factory-class" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:schema>
<?xml version="1.0" encoding="utf-8"?> <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://schemas.microsoft.com/VisualStudio/Roslyn/Compiler" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="define-parse-tree"> <xs:complexType> <xs:sequence> <xs:element name="definitions"> <xs:complexType> <xs:sequence> <xs:choice maxOccurs="unbounded"> <xs:element maxOccurs="unbounded" name="node-structure"> <xs:complexType> <xs:sequence> <xs:choice maxOccurs="unbounded"> <xs:element name="description" type="xs:string" /> <xs:element maxOccurs="unbounded" name="lm-equiv"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="name" type="xs:string" use="required" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> <xs:element maxOccurs="unbounded" name="native-equiv"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="name" type="xs:string" use="required" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> <xs:element maxOccurs="unbounded" name="spec-section" type="xs:string" /> <xs:element maxOccurs="unbounded" name="grammar" type="xs:string" /> <xs:element maxOccurs="unbounded" name="node-kind"> <xs:complexType mixed="true"> <xs:sequence minOccurs="0"> <xs:element minOccurs="0" name="description" type="xs:string" /> <xs:element minOccurs="0" maxOccurs="unbounded" name="lm-equiv"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="name" type="xs:string" use="required" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> <xs:element minOccurs="0" maxOccurs="unbounded" name="native-equiv"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="name" type="xs:string" use="required" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required" /> <xs:attribute name="token-text" type="xs:string" use="optional" /> </xs:complexType> </xs:element> <xs:element maxOccurs="unbounded" name="child"> <xs:complexType mixed="true"> <xs:sequence minOccurs="0"> <xs:element name="description" type="xs:string" /> <xs:element minOccurs="0" maxOccurs="unbounded" name="lm-equiv"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="name" type="xs:string" use="required" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> <xs:element minOccurs="0" maxOccurs="unbounded" name="native-equiv"> <xs:complexType> <xs:simpleContent> <xs:extension base="xs:string"> <xs:attribute name="name" type="xs:string" use="required" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> <xs:element minOccurs="0" maxOccurs="unbounded" name="kind"> <xs:complexType> <xs:attribute name="name" type="xs:string" use="required" /> <xs:attribute name="node-kind" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required" /> <xs:attribute name="kind" type="xs:string" use="optional" /> <xs:attribute name="optional" type="xs:boolean" use="optional" /> <xs:attribute name="list" type="xs:boolean" use="optional" /> <xs:attribute name="separator-kind" type="xs:string" use="optional" /> <xs:attribute name="separator-name" type="xs:string" use="optional" /> <xs:attribute name="min-count" type="xs:unsignedByte" use="optional" /> <xs:attribute name="order" type="xs:byte" use="optional" /> <xs:attribute name="optional-elements" type="xs:boolean" use="optional" /> <xs:attribute name="syntax-facts-internal" type="xs:boolean" use="optional" /> </xs:complexType> </xs:element> <xs:element name="field"> <xs:complexType> <xs:sequence minOccurs="0"> <xs:element name="description" type="xs:string" /> <xs:element minOccurs="0" name="lm-equiv"> <xs:complexType> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> <xs:element minOccurs="0" name="native-equiv"> <xs:complexType> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required" /> <xs:attribute name="type" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:choice> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required" /> <xs:attribute name="abstract" type="xs:boolean" use="optional" /> <xs:attribute name="partial" type="xs:boolean" use="optional" /> <xs:attribute name="predefined" type="xs:boolean" use="optional" /> <xs:attribute name="root" type="xs:boolean" use="optional" /> <xs:attribute name="parent" type="xs:string" use="optional" /> <xs:attribute name="token-root" type="xs:boolean" use="optional" /> <xs:attribute name="default-trailing-trivia" type="xs:string" use="optional" /> <xs:attribute name="has-default-factory" type="xs:boolean" use="optional" /> <xs:attribute name="no-factory" type="xs:boolean" use="optional" /> <xs:attribute name="trivia-root" type="xs:boolean" use="optional" /> <xs:attribute name="syntax-facts-internal" type="xs:boolean" use="optional" /> </xs:complexType> </xs:element> <xs:element maxOccurs="unbounded" name="node-kind-alias"> <xs:complexType> <xs:sequence> <xs:element name="description" type="xs:string" /> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required" /> <xs:attribute name="alias" type="xs:string" use="required" /> </xs:complexType> </xs:element> <xs:element name="enumeration"> <xs:complexType> <xs:sequence> <xs:element name="description" type="xs:string" /> <xs:element minOccurs="0" name="lm-equiv"> <xs:complexType> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> <xs:element maxOccurs="unbounded" name="native-equiv"> <xs:complexType> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> <xs:element name="enumerators"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" name="enumerator"> <xs:complexType> <xs:sequence minOccurs="0"> <xs:element name="description" type="xs:string" /> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="name" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:choice> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="namespace" type="xs:string" use="required" /> <xs:attribute name="visitor" type="xs:string" use="required" /> <xs:attribute name="rewrite-visitor" type="xs:string" use="required" /> <xs:attribute name="factory-class" type="xs:string" use="required" /> <xs:attribute name="contextual-factory-class" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:schema>
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/CommandHandlers/ExecuteInInteractiveCommandHandler.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.ComponentModel.Composition; using System.Linq; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CommandHandlers { /// <summary> /// Implements a execute in interactive command handler. /// This class is separated from the <see cref="IExecuteInInteractiveCommandHandler"/> /// in order to ensure that the interactive command can be exposed without the necessity /// to load any of the interactive dll files just to get the command's status. /// </summary> [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name("Interactive Command Handler")] internal class ExecuteInInteractiveCommandHandler : ICommandHandler<ExecuteInInteractiveCommandArgs> { private readonly IEnumerable<Lazy<IExecuteInInteractiveCommandHandler, ContentTypeMetadata>> _executeInInteractiveHandlers; public string DisplayName => EditorFeaturesResources.Execute_In_Interactive; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExecuteInInteractiveCommandHandler( [ImportMany] IEnumerable<Lazy<IExecuteInInteractiveCommandHandler, ContentTypeMetadata>> executeInInteractiveHandlers) { _executeInInteractiveHandlers = executeInInteractiveHandlers; } private Lazy<IExecuteInInteractiveCommandHandler> GetCommandHandler(ITextBuffer textBuffer) { return _executeInInteractiveHandlers .Where(handler => handler.Metadata.ContentTypes.Any(textBuffer.ContentType.IsOfType)) .SingleOrDefault(); } bool ICommandHandler<ExecuteInInteractiveCommandArgs>.ExecuteCommand(ExecuteInInteractiveCommandArgs args, CommandExecutionContext context) => GetCommandHandler(args.SubjectBuffer)?.Value.ExecuteCommand(args, context) ?? false; CommandState ICommandHandler<ExecuteInInteractiveCommandArgs>.GetCommandState(ExecuteInInteractiveCommandArgs args) { return GetCommandHandler(args.SubjectBuffer) == null ? CommandState.Unavailable : CommandState.Available; } } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using System.Linq; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CommandHandlers { /// <summary> /// Implements a execute in interactive command handler. /// This class is separated from the <see cref="IExecuteInInteractiveCommandHandler"/> /// in order to ensure that the interactive command can be exposed without the necessity /// to load any of the interactive dll files just to get the command's status. /// </summary> [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name("Interactive Command Handler")] internal class ExecuteInInteractiveCommandHandler : ICommandHandler<ExecuteInInteractiveCommandArgs> { private readonly IEnumerable<Lazy<IExecuteInInteractiveCommandHandler, ContentTypeMetadata>> _executeInInteractiveHandlers; public string DisplayName => EditorFeaturesResources.Execute_In_Interactive; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ExecuteInInteractiveCommandHandler( [ImportMany] IEnumerable<Lazy<IExecuteInInteractiveCommandHandler, ContentTypeMetadata>> executeInInteractiveHandlers) { _executeInInteractiveHandlers = executeInInteractiveHandlers; } private Lazy<IExecuteInInteractiveCommandHandler> GetCommandHandler(ITextBuffer textBuffer) { return _executeInInteractiveHandlers .Where(handler => handler.Metadata.ContentTypes.Any(textBuffer.ContentType.IsOfType)) .SingleOrDefault(); } bool ICommandHandler<ExecuteInInteractiveCommandArgs>.ExecuteCommand(ExecuteInInteractiveCommandArgs args, CommandExecutionContext context) => GetCommandHandler(args.SubjectBuffer)?.Value.ExecuteCommand(args, context) ?? false; CommandState ICommandHandler<ExecuteInInteractiveCommandArgs>.GetCommandState(ExecuteInInteractiveCommandArgs args) { return GetCommandHandler(args.SubjectBuffer) == null ? CommandState.Unavailable : CommandState.Available; } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Emit/EmitOptions.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.Security.Cryptography; using System.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { /// <summary> /// Represents compilation emit options. /// </summary> public sealed class EmitOptions : IEquatable<EmitOptions> { internal static readonly EmitOptions Default = PlatformInformation.IsWindows ? new EmitOptions() : new EmitOptions().WithDebugInformationFormat(DebugInformationFormat.PortablePdb); /// <summary> /// True to emit an assembly excluding executable code such as method bodies. /// </summary> public bool EmitMetadataOnly { get; private set; } /// <summary> /// Tolerate errors, producing a PE stream and a success result even in the presence of (some) errors. /// </summary> public bool TolerateErrors { get; private set; } /// <summary> /// Unless set (private) members that don't affect the language semantics of the resulting assembly will be excluded /// when emitting metadata-only assemblies as primary output (with <see cref="EmitMetadataOnly"/> on). /// If emitting a secondary output, this flag is required to be false. /// </summary> public bool IncludePrivateMembers { get; private set; } /// <summary> /// Type of instrumentation that should be added to the output binary. /// </summary> public ImmutableArray<InstrumentationKind> InstrumentationKinds { get; private set; } /// <summary> /// Subsystem version /// </summary> public SubsystemVersion SubsystemVersion { get; private set; } /// <summary> /// Specifies the size of sections in the output file. /// </summary> /// <remarks> /// Valid values are 0, 512, 1024, 2048, 4096 and 8192. /// If the value is 0 the file alignment is determined based upon the value of <see cref="Platform"/>. /// </remarks> public int FileAlignment { get; private set; } /// <summary> /// True to enable high entropy virtual address space for the output binary. /// </summary> public bool HighEntropyVirtualAddressSpace { get; private set; } /// <summary> /// Specifies the preferred base address at which to load the output DLL. /// </summary> public ulong BaseAddress { get; private set; } /// <summary> /// Debug information format. /// </summary> public DebugInformationFormat DebugInformationFormat { get; private set; } /// <summary> /// Assembly name override - file name and extension. If not specified the compilation name is used. /// </summary> /// <remarks> /// By default the name of the output assembly is <see cref="Compilation.AssemblyName"/>. Only in rare cases it is necessary /// to override the name. /// /// CAUTION: If this is set to a (non-null) value other than the existing compilation output name, then internals-visible-to /// and assembly references may not work as expected. In particular, things that were visible at bind time, based on the /// name of the compilation, may not be visible at runtime and vice-versa. /// </remarks> public string? OutputNameOverride { get; private set; } /// <summary> /// The name of the PDB file to be embedded in the PE image, or null to use the default. /// </summary> /// <remarks> /// If not specified the file name of the source module with an extension changed to "pdb" is used. /// </remarks> public string? PdbFilePath { get; private set; } /// <summary> /// A crypto hash algorithm used to calculate PDB Checksum stored in the PE/COFF File. /// If not specified (the value is <c>default(HashAlgorithmName)</c>) the checksum is not calculated. /// </summary> public HashAlgorithmName PdbChecksumAlgorithm { get; private set; } /// <summary> /// Runtime metadata version. /// </summary> public string? RuntimeMetadataVersion { get; private set; } /// <summary> /// The encoding used to parse source files that do not have a Byte Order Mark. If specified, /// is stored in the emitted PDB in order to allow recreating the original compilation. /// </summary> public Encoding? DefaultSourceFileEncoding { get; private set; } /// <summary> /// If <see cref="DefaultSourceFileEncoding"/> is not specified, the encoding used to parse source files /// that do not declare their encoding via Byte Order Mark and are not UTF8-encoded. /// </summary> public Encoding? FallbackSourceFileEncoding { get; private set; } // 1.2 BACKCOMPAT OVERLOAD -- DO NOT TOUCH public EmitOptions( bool metadataOnly, DebugInformationFormat debugInformationFormat, string pdbFilePath, string outputNameOverride, int fileAlignment, ulong baseAddress, bool highEntropyVirtualAddressSpace, SubsystemVersion subsystemVersion, string runtimeMetadataVersion, bool tolerateErrors, bool includePrivateMembers) : this( metadataOnly, debugInformationFormat, pdbFilePath, outputNameOverride, fileAlignment, baseAddress, highEntropyVirtualAddressSpace, subsystemVersion, runtimeMetadataVersion, tolerateErrors, includePrivateMembers, instrumentationKinds: ImmutableArray<InstrumentationKind>.Empty) { } // 2.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH public EmitOptions( bool metadataOnly, DebugInformationFormat debugInformationFormat, string pdbFilePath, string outputNameOverride, int fileAlignment, ulong baseAddress, bool highEntropyVirtualAddressSpace, SubsystemVersion subsystemVersion, string runtimeMetadataVersion, bool tolerateErrors, bool includePrivateMembers, ImmutableArray<InstrumentationKind> instrumentationKinds) : this( metadataOnly, debugInformationFormat, pdbFilePath, outputNameOverride, fileAlignment, baseAddress, highEntropyVirtualAddressSpace, subsystemVersion, runtimeMetadataVersion, tolerateErrors, includePrivateMembers, instrumentationKinds, pdbChecksumAlgorithm: null) { } // 3.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH public EmitOptions( bool metadataOnly, DebugInformationFormat debugInformationFormat, string? pdbFilePath, string? outputNameOverride, int fileAlignment, ulong baseAddress, bool highEntropyVirtualAddressSpace, SubsystemVersion subsystemVersion, string? runtimeMetadataVersion, bool tolerateErrors, bool includePrivateMembers, ImmutableArray<InstrumentationKind> instrumentationKinds, HashAlgorithmName? pdbChecksumAlgorithm) : this( metadataOnly, debugInformationFormat, pdbFilePath, outputNameOverride, fileAlignment, baseAddress, highEntropyVirtualAddressSpace, subsystemVersion, runtimeMetadataVersion, tolerateErrors, includePrivateMembers, instrumentationKinds, pdbChecksumAlgorithm, defaultSourceFileEncoding: null, fallbackSourceFileEncoding: null) { } public EmitOptions( bool metadataOnly = false, DebugInformationFormat debugInformationFormat = 0, string? pdbFilePath = null, string? outputNameOverride = null, int fileAlignment = 0, ulong baseAddress = 0, bool highEntropyVirtualAddressSpace = false, SubsystemVersion subsystemVersion = default, string? runtimeMetadataVersion = null, bool tolerateErrors = false, bool includePrivateMembers = true, ImmutableArray<InstrumentationKind> instrumentationKinds = default, HashAlgorithmName? pdbChecksumAlgorithm = null, Encoding? defaultSourceFileEncoding = null, Encoding? fallbackSourceFileEncoding = null) { EmitMetadataOnly = metadataOnly; DebugInformationFormat = (debugInformationFormat == 0) ? DebugInformationFormat.Pdb : debugInformationFormat; PdbFilePath = pdbFilePath; OutputNameOverride = outputNameOverride; FileAlignment = fileAlignment; BaseAddress = baseAddress; HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace; SubsystemVersion = subsystemVersion; RuntimeMetadataVersion = runtimeMetadataVersion; TolerateErrors = tolerateErrors; IncludePrivateMembers = includePrivateMembers; InstrumentationKinds = instrumentationKinds.NullToEmpty(); PdbChecksumAlgorithm = pdbChecksumAlgorithm ?? HashAlgorithmName.SHA256; DefaultSourceFileEncoding = defaultSourceFileEncoding; FallbackSourceFileEncoding = fallbackSourceFileEncoding; } private EmitOptions(EmitOptions other) : this( other.EmitMetadataOnly, other.DebugInformationFormat, other.PdbFilePath, other.OutputNameOverride, other.FileAlignment, other.BaseAddress, other.HighEntropyVirtualAddressSpace, other.SubsystemVersion, other.RuntimeMetadataVersion, other.TolerateErrors, other.IncludePrivateMembers, other.InstrumentationKinds, other.PdbChecksumAlgorithm, other.DefaultSourceFileEncoding, other.FallbackSourceFileEncoding) { } public override bool Equals(object? obj) { return Equals(obj as EmitOptions); } public bool Equals(EmitOptions? other) { if (ReferenceEquals(other, null)) { return false; } return EmitMetadataOnly == other.EmitMetadataOnly && BaseAddress == other.BaseAddress && FileAlignment == other.FileAlignment && HighEntropyVirtualAddressSpace == other.HighEntropyVirtualAddressSpace && SubsystemVersion.Equals(other.SubsystemVersion) && DebugInformationFormat == other.DebugInformationFormat && PdbFilePath == other.PdbFilePath && PdbChecksumAlgorithm == other.PdbChecksumAlgorithm && OutputNameOverride == other.OutputNameOverride && RuntimeMetadataVersion == other.RuntimeMetadataVersion && TolerateErrors == other.TolerateErrors && IncludePrivateMembers == other.IncludePrivateMembers && InstrumentationKinds.NullToEmpty().SequenceEqual(other.InstrumentationKinds.NullToEmpty(), (a, b) => a == b) && DefaultSourceFileEncoding == other.DefaultSourceFileEncoding && FallbackSourceFileEncoding == other.FallbackSourceFileEncoding; } public override int GetHashCode() { return Hash.Combine(EmitMetadataOnly, Hash.Combine(BaseAddress.GetHashCode(), Hash.Combine(FileAlignment, Hash.Combine(HighEntropyVirtualAddressSpace, Hash.Combine(SubsystemVersion.GetHashCode(), Hash.Combine((int)DebugInformationFormat, Hash.Combine(PdbFilePath, Hash.Combine(PdbChecksumAlgorithm.GetHashCode(), Hash.Combine(OutputNameOverride, Hash.Combine(RuntimeMetadataVersion, Hash.Combine(TolerateErrors, Hash.Combine(IncludePrivateMembers, Hash.Combine(Hash.CombineValues(InstrumentationKinds), Hash.Combine(DefaultSourceFileEncoding, Hash.Combine(FallbackSourceFileEncoding, 0))))))))))))))); } public static bool operator ==(EmitOptions? left, EmitOptions? right) { return object.Equals(left, right); } public static bool operator !=(EmitOptions? left, EmitOptions? right) { return !object.Equals(left, right); } internal void ValidateOptions(DiagnosticBag diagnostics, CommonMessageProvider messageProvider, bool isDeterministic) { if (!DebugInformationFormat.IsValid()) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidDebugInformationFormat, Location.None, (int)DebugInformationFormat)); } foreach (var instrumentationKind in InstrumentationKinds) { if (!instrumentationKind.IsValid()) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidInstrumentationKind, Location.None, (int)instrumentationKind)); } } if (OutputNameOverride != null) { MetadataHelpers.CheckAssemblyOrModuleName(OutputNameOverride, messageProvider, messageProvider.ERR_InvalidOutputName, diagnostics); } if (FileAlignment != 0 && !IsValidFileAlignment(FileAlignment)) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidFileAlignment, Location.None, FileAlignment)); } if (!SubsystemVersion.Equals(SubsystemVersion.None) && !SubsystemVersion.IsValid) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidSubsystemVersion, Location.None, SubsystemVersion.ToString())); } if (PdbChecksumAlgorithm.Name != null) { try { IncrementalHash.CreateHash(PdbChecksumAlgorithm).Dispose(); } catch { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, PdbChecksumAlgorithm.ToString())); } } else if (isDeterministic) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, "")); } } internal bool EmitTestCoverageData => InstrumentationKinds.Contains(InstrumentationKind.TestCoverage); internal static bool IsValidFileAlignment(int value) { switch (value) { case 512: case 1024: case 2048: case 4096: case 8192: return true; default: return false; } } public EmitOptions WithEmitMetadataOnly(bool value) { if (EmitMetadataOnly == value) { return this; } return new EmitOptions(this) { EmitMetadataOnly = value }; } public EmitOptions WithPdbFilePath(string path) { if (PdbFilePath == path) { return this; } return new EmitOptions(this) { PdbFilePath = path }; } public EmitOptions WithPdbChecksumAlgorithm(HashAlgorithmName name) { if (PdbChecksumAlgorithm == name) { return this; } return new EmitOptions(this) { PdbChecksumAlgorithm = name }; } public EmitOptions WithOutputNameOverride(string outputName) { if (OutputNameOverride == outputName) { return this; } return new EmitOptions(this) { OutputNameOverride = outputName }; } public EmitOptions WithDebugInformationFormat(DebugInformationFormat format) { if (DebugInformationFormat == format) { return this; } return new EmitOptions(this) { DebugInformationFormat = format }; } /// <summary> /// Sets the byte alignment for portable executable file sections. /// </summary> /// <param name="value">Can be one of the following values: 0, 512, 1024, 2048, 4096, 8192</param> public EmitOptions WithFileAlignment(int value) { if (FileAlignment == value) { return this; } return new EmitOptions(this) { FileAlignment = value }; } public EmitOptions WithBaseAddress(ulong value) { if (BaseAddress == value) { return this; } return new EmitOptions(this) { BaseAddress = value }; } public EmitOptions WithHighEntropyVirtualAddressSpace(bool value) { if (HighEntropyVirtualAddressSpace == value) { return this; } return new EmitOptions(this) { HighEntropyVirtualAddressSpace = value }; } public EmitOptions WithSubsystemVersion(SubsystemVersion subsystemVersion) { if (subsystemVersion.Equals(SubsystemVersion)) { return this; } return new EmitOptions(this) { SubsystemVersion = subsystemVersion }; } public EmitOptions WithRuntimeMetadataVersion(string version) { if (RuntimeMetadataVersion == version) { return this; } return new EmitOptions(this) { RuntimeMetadataVersion = version }; } public EmitOptions WithTolerateErrors(bool value) { if (TolerateErrors == value) { return this; } return new EmitOptions(this) { TolerateErrors = value }; } public EmitOptions WithIncludePrivateMembers(bool value) { if (IncludePrivateMembers == value) { return this; } return new EmitOptions(this) { IncludePrivateMembers = value }; } public EmitOptions WithInstrumentationKinds(ImmutableArray<InstrumentationKind> instrumentationKinds) { if (InstrumentationKinds == instrumentationKinds) { return this; } return new EmitOptions(this) { InstrumentationKinds = instrumentationKinds }; } public EmitOptions WithDefaultSourceFileEncoding(Encoding? defaultSourceFileEncoding) { if (DefaultSourceFileEncoding == defaultSourceFileEncoding) { return this; } return new EmitOptions(this) { DefaultSourceFileEncoding = defaultSourceFileEncoding }; } public EmitOptions WithFallbackSourceFileEncoding(Encoding? fallbackSourceFileEncoding) { if (FallbackSourceFileEncoding == fallbackSourceFileEncoding) { return this; } return new EmitOptions(this) { FallbackSourceFileEncoding = fallbackSourceFileEncoding }; } } }
// Licensed to the .NET Foundation under one or more 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.Security.Cryptography; using System.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Emit { /// <summary> /// Represents compilation emit options. /// </summary> public sealed class EmitOptions : IEquatable<EmitOptions> { internal static readonly EmitOptions Default = PlatformInformation.IsWindows ? new EmitOptions() : new EmitOptions().WithDebugInformationFormat(DebugInformationFormat.PortablePdb); /// <summary> /// True to emit an assembly excluding executable code such as method bodies. /// </summary> public bool EmitMetadataOnly { get; private set; } /// <summary> /// Tolerate errors, producing a PE stream and a success result even in the presence of (some) errors. /// </summary> public bool TolerateErrors { get; private set; } /// <summary> /// Unless set (private) members that don't affect the language semantics of the resulting assembly will be excluded /// when emitting metadata-only assemblies as primary output (with <see cref="EmitMetadataOnly"/> on). /// If emitting a secondary output, this flag is required to be false. /// </summary> public bool IncludePrivateMembers { get; private set; } /// <summary> /// Type of instrumentation that should be added to the output binary. /// </summary> public ImmutableArray<InstrumentationKind> InstrumentationKinds { get; private set; } /// <summary> /// Subsystem version /// </summary> public SubsystemVersion SubsystemVersion { get; private set; } /// <summary> /// Specifies the size of sections in the output file. /// </summary> /// <remarks> /// Valid values are 0, 512, 1024, 2048, 4096 and 8192. /// If the value is 0 the file alignment is determined based upon the value of <see cref="Platform"/>. /// </remarks> public int FileAlignment { get; private set; } /// <summary> /// True to enable high entropy virtual address space for the output binary. /// </summary> public bool HighEntropyVirtualAddressSpace { get; private set; } /// <summary> /// Specifies the preferred base address at which to load the output DLL. /// </summary> public ulong BaseAddress { get; private set; } /// <summary> /// Debug information format. /// </summary> public DebugInformationFormat DebugInformationFormat { get; private set; } /// <summary> /// Assembly name override - file name and extension. If not specified the compilation name is used. /// </summary> /// <remarks> /// By default the name of the output assembly is <see cref="Compilation.AssemblyName"/>. Only in rare cases it is necessary /// to override the name. /// /// CAUTION: If this is set to a (non-null) value other than the existing compilation output name, then internals-visible-to /// and assembly references may not work as expected. In particular, things that were visible at bind time, based on the /// name of the compilation, may not be visible at runtime and vice-versa. /// </remarks> public string? OutputNameOverride { get; private set; } /// <summary> /// The name of the PDB file to be embedded in the PE image, or null to use the default. /// </summary> /// <remarks> /// If not specified the file name of the source module with an extension changed to "pdb" is used. /// </remarks> public string? PdbFilePath { get; private set; } /// <summary> /// A crypto hash algorithm used to calculate PDB Checksum stored in the PE/COFF File. /// If not specified (the value is <c>default(HashAlgorithmName)</c>) the checksum is not calculated. /// </summary> public HashAlgorithmName PdbChecksumAlgorithm { get; private set; } /// <summary> /// Runtime metadata version. /// </summary> public string? RuntimeMetadataVersion { get; private set; } /// <summary> /// The encoding used to parse source files that do not have a Byte Order Mark. If specified, /// is stored in the emitted PDB in order to allow recreating the original compilation. /// </summary> public Encoding? DefaultSourceFileEncoding { get; private set; } /// <summary> /// If <see cref="DefaultSourceFileEncoding"/> is not specified, the encoding used to parse source files /// that do not declare their encoding via Byte Order Mark and are not UTF8-encoded. /// </summary> public Encoding? FallbackSourceFileEncoding { get; private set; } // 1.2 BACKCOMPAT OVERLOAD -- DO NOT TOUCH public EmitOptions( bool metadataOnly, DebugInformationFormat debugInformationFormat, string pdbFilePath, string outputNameOverride, int fileAlignment, ulong baseAddress, bool highEntropyVirtualAddressSpace, SubsystemVersion subsystemVersion, string runtimeMetadataVersion, bool tolerateErrors, bool includePrivateMembers) : this( metadataOnly, debugInformationFormat, pdbFilePath, outputNameOverride, fileAlignment, baseAddress, highEntropyVirtualAddressSpace, subsystemVersion, runtimeMetadataVersion, tolerateErrors, includePrivateMembers, instrumentationKinds: ImmutableArray<InstrumentationKind>.Empty) { } // 2.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH public EmitOptions( bool metadataOnly, DebugInformationFormat debugInformationFormat, string pdbFilePath, string outputNameOverride, int fileAlignment, ulong baseAddress, bool highEntropyVirtualAddressSpace, SubsystemVersion subsystemVersion, string runtimeMetadataVersion, bool tolerateErrors, bool includePrivateMembers, ImmutableArray<InstrumentationKind> instrumentationKinds) : this( metadataOnly, debugInformationFormat, pdbFilePath, outputNameOverride, fileAlignment, baseAddress, highEntropyVirtualAddressSpace, subsystemVersion, runtimeMetadataVersion, tolerateErrors, includePrivateMembers, instrumentationKinds, pdbChecksumAlgorithm: null) { } // 3.7 BACKCOMPAT OVERLOAD -- DO NOT TOUCH public EmitOptions( bool metadataOnly, DebugInformationFormat debugInformationFormat, string? pdbFilePath, string? outputNameOverride, int fileAlignment, ulong baseAddress, bool highEntropyVirtualAddressSpace, SubsystemVersion subsystemVersion, string? runtimeMetadataVersion, bool tolerateErrors, bool includePrivateMembers, ImmutableArray<InstrumentationKind> instrumentationKinds, HashAlgorithmName? pdbChecksumAlgorithm) : this( metadataOnly, debugInformationFormat, pdbFilePath, outputNameOverride, fileAlignment, baseAddress, highEntropyVirtualAddressSpace, subsystemVersion, runtimeMetadataVersion, tolerateErrors, includePrivateMembers, instrumentationKinds, pdbChecksumAlgorithm, defaultSourceFileEncoding: null, fallbackSourceFileEncoding: null) { } public EmitOptions( bool metadataOnly = false, DebugInformationFormat debugInformationFormat = 0, string? pdbFilePath = null, string? outputNameOverride = null, int fileAlignment = 0, ulong baseAddress = 0, bool highEntropyVirtualAddressSpace = false, SubsystemVersion subsystemVersion = default, string? runtimeMetadataVersion = null, bool tolerateErrors = false, bool includePrivateMembers = true, ImmutableArray<InstrumentationKind> instrumentationKinds = default, HashAlgorithmName? pdbChecksumAlgorithm = null, Encoding? defaultSourceFileEncoding = null, Encoding? fallbackSourceFileEncoding = null) { EmitMetadataOnly = metadataOnly; DebugInformationFormat = (debugInformationFormat == 0) ? DebugInformationFormat.Pdb : debugInformationFormat; PdbFilePath = pdbFilePath; OutputNameOverride = outputNameOverride; FileAlignment = fileAlignment; BaseAddress = baseAddress; HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace; SubsystemVersion = subsystemVersion; RuntimeMetadataVersion = runtimeMetadataVersion; TolerateErrors = tolerateErrors; IncludePrivateMembers = includePrivateMembers; InstrumentationKinds = instrumentationKinds.NullToEmpty(); PdbChecksumAlgorithm = pdbChecksumAlgorithm ?? HashAlgorithmName.SHA256; DefaultSourceFileEncoding = defaultSourceFileEncoding; FallbackSourceFileEncoding = fallbackSourceFileEncoding; } private EmitOptions(EmitOptions other) : this( other.EmitMetadataOnly, other.DebugInformationFormat, other.PdbFilePath, other.OutputNameOverride, other.FileAlignment, other.BaseAddress, other.HighEntropyVirtualAddressSpace, other.SubsystemVersion, other.RuntimeMetadataVersion, other.TolerateErrors, other.IncludePrivateMembers, other.InstrumentationKinds, other.PdbChecksumAlgorithm, other.DefaultSourceFileEncoding, other.FallbackSourceFileEncoding) { } public override bool Equals(object? obj) { return Equals(obj as EmitOptions); } public bool Equals(EmitOptions? other) { if (ReferenceEquals(other, null)) { return false; } return EmitMetadataOnly == other.EmitMetadataOnly && BaseAddress == other.BaseAddress && FileAlignment == other.FileAlignment && HighEntropyVirtualAddressSpace == other.HighEntropyVirtualAddressSpace && SubsystemVersion.Equals(other.SubsystemVersion) && DebugInformationFormat == other.DebugInformationFormat && PdbFilePath == other.PdbFilePath && PdbChecksumAlgorithm == other.PdbChecksumAlgorithm && OutputNameOverride == other.OutputNameOverride && RuntimeMetadataVersion == other.RuntimeMetadataVersion && TolerateErrors == other.TolerateErrors && IncludePrivateMembers == other.IncludePrivateMembers && InstrumentationKinds.NullToEmpty().SequenceEqual(other.InstrumentationKinds.NullToEmpty(), (a, b) => a == b) && DefaultSourceFileEncoding == other.DefaultSourceFileEncoding && FallbackSourceFileEncoding == other.FallbackSourceFileEncoding; } public override int GetHashCode() { return Hash.Combine(EmitMetadataOnly, Hash.Combine(BaseAddress.GetHashCode(), Hash.Combine(FileAlignment, Hash.Combine(HighEntropyVirtualAddressSpace, Hash.Combine(SubsystemVersion.GetHashCode(), Hash.Combine((int)DebugInformationFormat, Hash.Combine(PdbFilePath, Hash.Combine(PdbChecksumAlgorithm.GetHashCode(), Hash.Combine(OutputNameOverride, Hash.Combine(RuntimeMetadataVersion, Hash.Combine(TolerateErrors, Hash.Combine(IncludePrivateMembers, Hash.Combine(Hash.CombineValues(InstrumentationKinds), Hash.Combine(DefaultSourceFileEncoding, Hash.Combine(FallbackSourceFileEncoding, 0))))))))))))))); } public static bool operator ==(EmitOptions? left, EmitOptions? right) { return object.Equals(left, right); } public static bool operator !=(EmitOptions? left, EmitOptions? right) { return !object.Equals(left, right); } internal void ValidateOptions(DiagnosticBag diagnostics, CommonMessageProvider messageProvider, bool isDeterministic) { if (!DebugInformationFormat.IsValid()) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidDebugInformationFormat, Location.None, (int)DebugInformationFormat)); } foreach (var instrumentationKind in InstrumentationKinds) { if (!instrumentationKind.IsValid()) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidInstrumentationKind, Location.None, (int)instrumentationKind)); } } if (OutputNameOverride != null) { MetadataHelpers.CheckAssemblyOrModuleName(OutputNameOverride, messageProvider, messageProvider.ERR_InvalidOutputName, diagnostics); } if (FileAlignment != 0 && !IsValidFileAlignment(FileAlignment)) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidFileAlignment, Location.None, FileAlignment)); } if (!SubsystemVersion.Equals(SubsystemVersion.None) && !SubsystemVersion.IsValid) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidSubsystemVersion, Location.None, SubsystemVersion.ToString())); } if (PdbChecksumAlgorithm.Name != null) { try { IncrementalHash.CreateHash(PdbChecksumAlgorithm).Dispose(); } catch { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, PdbChecksumAlgorithm.ToString())); } } else if (isDeterministic) { diagnostics.Add(messageProvider.CreateDiagnostic(messageProvider.ERR_InvalidHashAlgorithmName, Location.None, "")); } } internal bool EmitTestCoverageData => InstrumentationKinds.Contains(InstrumentationKind.TestCoverage); internal static bool IsValidFileAlignment(int value) { switch (value) { case 512: case 1024: case 2048: case 4096: case 8192: return true; default: return false; } } public EmitOptions WithEmitMetadataOnly(bool value) { if (EmitMetadataOnly == value) { return this; } return new EmitOptions(this) { EmitMetadataOnly = value }; } public EmitOptions WithPdbFilePath(string path) { if (PdbFilePath == path) { return this; } return new EmitOptions(this) { PdbFilePath = path }; } public EmitOptions WithPdbChecksumAlgorithm(HashAlgorithmName name) { if (PdbChecksumAlgorithm == name) { return this; } return new EmitOptions(this) { PdbChecksumAlgorithm = name }; } public EmitOptions WithOutputNameOverride(string outputName) { if (OutputNameOverride == outputName) { return this; } return new EmitOptions(this) { OutputNameOverride = outputName }; } public EmitOptions WithDebugInformationFormat(DebugInformationFormat format) { if (DebugInformationFormat == format) { return this; } return new EmitOptions(this) { DebugInformationFormat = format }; } /// <summary> /// Sets the byte alignment for portable executable file sections. /// </summary> /// <param name="value">Can be one of the following values: 0, 512, 1024, 2048, 4096, 8192</param> public EmitOptions WithFileAlignment(int value) { if (FileAlignment == value) { return this; } return new EmitOptions(this) { FileAlignment = value }; } public EmitOptions WithBaseAddress(ulong value) { if (BaseAddress == value) { return this; } return new EmitOptions(this) { BaseAddress = value }; } public EmitOptions WithHighEntropyVirtualAddressSpace(bool value) { if (HighEntropyVirtualAddressSpace == value) { return this; } return new EmitOptions(this) { HighEntropyVirtualAddressSpace = value }; } public EmitOptions WithSubsystemVersion(SubsystemVersion subsystemVersion) { if (subsystemVersion.Equals(SubsystemVersion)) { return this; } return new EmitOptions(this) { SubsystemVersion = subsystemVersion }; } public EmitOptions WithRuntimeMetadataVersion(string version) { if (RuntimeMetadataVersion == version) { return this; } return new EmitOptions(this) { RuntimeMetadataVersion = version }; } public EmitOptions WithTolerateErrors(bool value) { if (TolerateErrors == value) { return this; } return new EmitOptions(this) { TolerateErrors = value }; } public EmitOptions WithIncludePrivateMembers(bool value) { if (IncludePrivateMembers == value) { return this; } return new EmitOptions(this) { IncludePrivateMembers = value }; } public EmitOptions WithInstrumentationKinds(ImmutableArray<InstrumentationKind> instrumentationKinds) { if (InstrumentationKinds == instrumentationKinds) { return this; } return new EmitOptions(this) { InstrumentationKinds = instrumentationKinds }; } public EmitOptions WithDefaultSourceFileEncoding(Encoding? defaultSourceFileEncoding) { if (DefaultSourceFileEncoding == defaultSourceFileEncoding) { return this; } return new EmitOptions(this) { DefaultSourceFileEncoding = defaultSourceFileEncoding }; } public EmitOptions WithFallbackSourceFileEncoding(Encoding? fallbackSourceFileEncoding) { if (FallbackSourceFileEncoding == fallbackSourceFileEncoding) { return this; } return new EmitOptions(this) { FallbackSourceFileEncoding = fallbackSourceFileEncoding }; } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/GenerateConstructorFromMembers/AbstractGenerateConstructorFromMembersCodeRefactoringProvider.State.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.GenerateConstructorFromMembers { internal abstract partial class AbstractGenerateConstructorFromMembersCodeRefactoringProvider { private class State { public TextSpan TextSpan { get; private set; } public IMethodSymbol? MatchingConstructor { get; private set; } public IMethodSymbol? DelegatedConstructor { get; private set; } [NotNull] public INamedTypeSymbol? ContainingType { get; private set; } public ImmutableArray<ISymbol> SelectedMembers { get; private set; } public ImmutableArray<IParameterSymbol> Parameters { get; private set; } public bool IsContainedInUnsafeType { get; private set; } public static async Task<State?> TryGenerateAsync( AbstractGenerateConstructorFromMembersCodeRefactoringProvider service, Document document, TextSpan textSpan, INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeAsync(service, document, textSpan, containingType, selectedMembers, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( AbstractGenerateConstructorFromMembersCodeRefactoringProvider service, Document document, TextSpan textSpan, INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers, CancellationToken cancellationToken) { if (!selectedMembers.All(IsWritableInstanceFieldOrProperty)) { return false; } SelectedMembers = selectedMembers; ContainingType = containingType; TextSpan = textSpan; if (ContainingType == null || ContainingType.TypeKind == TypeKind.Interface) { return false; } IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(containingType); var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false); Parameters = DetermineParameters(selectedMembers, rules); MatchingConstructor = GetMatchingConstructorBasedOnParameterTypes(ContainingType, Parameters); // We are going to create a new contructor and pass part of the parameters into DelegatedConstructor, // so parameters should be compared based on types since we don't want get a type mismatch error after the new constructor is genreated. DelegatedConstructor = GetDelegatedConstructorBasedOnParameterTypes(ContainingType, Parameters); return true; } private static IMethodSymbol? GetDelegatedConstructorBasedOnParameterTypes( INamedTypeSymbol containingType, ImmutableArray<IParameterSymbol> parameters) { var q = from c in containingType.InstanceConstructors orderby c.Parameters.Length descending where c.Parameters.Length > 0 && c.Parameters.Length < parameters.Length where c.Parameters.All(p => p.RefKind == RefKind.None) && !c.Parameters.Any(p => p.IsParams) let constructorTypes = c.Parameters.Select(p => p.Type) let symbolTypes = parameters.Take(c.Parameters.Length).Select(p => p.Type) where constructorTypes.SequenceEqual(symbolTypes, SymbolEqualityComparer.Default) select c; return q.FirstOrDefault(); } private static IMethodSymbol? GetMatchingConstructorBasedOnParameterTypes(INamedTypeSymbol containingType, ImmutableArray<IParameterSymbol> parameters) => containingType.InstanceConstructors.FirstOrDefault(c => MatchesConstructorBasedOnParameterTypes(c, parameters)); private static bool MatchesConstructorBasedOnParameterTypes(IMethodSymbol constructor, ImmutableArray<IParameterSymbol> parameters) => parameters.Select(p => p.Type).SequenceEqual(constructor.Parameters.Select(p => p.Type)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.GenerateConstructorFromMembers { internal abstract partial class AbstractGenerateConstructorFromMembersCodeRefactoringProvider { private class State { public TextSpan TextSpan { get; private set; } public IMethodSymbol? MatchingConstructor { get; private set; } public IMethodSymbol? DelegatedConstructor { get; private set; } [NotNull] public INamedTypeSymbol? ContainingType { get; private set; } public ImmutableArray<ISymbol> SelectedMembers { get; private set; } public ImmutableArray<IParameterSymbol> Parameters { get; private set; } public bool IsContainedInUnsafeType { get; private set; } public static async Task<State?> TryGenerateAsync( AbstractGenerateConstructorFromMembersCodeRefactoringProvider service, Document document, TextSpan textSpan, INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeAsync(service, document, textSpan, containingType, selectedMembers, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( AbstractGenerateConstructorFromMembersCodeRefactoringProvider service, Document document, TextSpan textSpan, INamedTypeSymbol containingType, ImmutableArray<ISymbol> selectedMembers, CancellationToken cancellationToken) { if (!selectedMembers.All(IsWritableInstanceFieldOrProperty)) { return false; } SelectedMembers = selectedMembers; ContainingType = containingType; TextSpan = textSpan; if (ContainingType == null || ContainingType.TypeKind == TypeKind.Interface) { return false; } IsContainedInUnsafeType = service.ContainingTypesOrSelfHasUnsafeKeyword(containingType); var rules = await document.GetNamingRulesAsync(cancellationToken).ConfigureAwait(false); Parameters = DetermineParameters(selectedMembers, rules); MatchingConstructor = GetMatchingConstructorBasedOnParameterTypes(ContainingType, Parameters); // We are going to create a new contructor and pass part of the parameters into DelegatedConstructor, // so parameters should be compared based on types since we don't want get a type mismatch error after the new constructor is genreated. DelegatedConstructor = GetDelegatedConstructorBasedOnParameterTypes(ContainingType, Parameters); return true; } private static IMethodSymbol? GetDelegatedConstructorBasedOnParameterTypes( INamedTypeSymbol containingType, ImmutableArray<IParameterSymbol> parameters) { var q = from c in containingType.InstanceConstructors orderby c.Parameters.Length descending where c.Parameters.Length > 0 && c.Parameters.Length < parameters.Length where c.Parameters.All(p => p.RefKind == RefKind.None) && !c.Parameters.Any(p => p.IsParams) let constructorTypes = c.Parameters.Select(p => p.Type) let symbolTypes = parameters.Take(c.Parameters.Length).Select(p => p.Type) where constructorTypes.SequenceEqual(symbolTypes, SymbolEqualityComparer.Default) select c; return q.FirstOrDefault(); } private static IMethodSymbol? GetMatchingConstructorBasedOnParameterTypes(INamedTypeSymbol containingType, ImmutableArray<IParameterSymbol> parameters) => containingType.InstanceConstructors.FirstOrDefault(c => MatchesConstructorBasedOnParameterTypes(c, parameters)); private static bool MatchesConstructorBasedOnParameterTypes(IMethodSymbol constructor, ImmutableArray<IParameterSymbol> parameters) => parameters.Select(p => p.Type).SequenceEqual(constructor.Parameters.Select(p => p.Type)); } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/GoToImplementation/GoToImplementationCommandHandler.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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CommandHandlers; using Microsoft.CodeAnalysis.Editor.Commanding.Commands; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToImplementation { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(PredefinedCommandHandlerNames.GoToImplementation)] internal class GoToImplementationCommandHandler : AbstractGoToCommandHandler<IFindUsagesService, GoToImplementationCommandArgs> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GoToImplementationCommandHandler( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter) : base(threadingContext, streamingPresenter) { } public override string DisplayName => EditorFeaturesResources.Go_To_Implementation; protected override string ScopeDescription => EditorFeaturesResources.Locating_implementations; protected override FunctionId FunctionId => FunctionId.CommandHandler_GoToImplementation; protected override Task FindActionAsync(IFindUsagesService service, Document document, int caretPosition, IFindUsagesContext context, CancellationToken cancellationToken) => service.FindImplementationsAsync(document, caretPosition, context, cancellationToken); protected override IFindUsagesService? GetService(Document? document) => document?.GetLanguageService<IFindUsagesService>(); } }
// Licensed to the .NET Foundation under one or more 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.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CommandHandlers; using Microsoft.CodeAnalysis.Editor.Commanding.Commands; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.GoToImplementation { [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(PredefinedCommandHandlerNames.GoToImplementation)] internal class GoToImplementationCommandHandler : AbstractGoToCommandHandler<IFindUsagesService, GoToImplementationCommandArgs> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public GoToImplementationCommandHandler( IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter) : base(threadingContext, streamingPresenter) { } public override string DisplayName => EditorFeaturesResources.Go_To_Implementation; protected override string ScopeDescription => EditorFeaturesResources.Locating_implementations; protected override FunctionId FunctionId => FunctionId.CommandHandler_GoToImplementation; protected override Task FindActionAsync(IFindUsagesService service, Document document, int caretPosition, IFindUsagesContext context, CancellationToken cancellationToken) => service.FindImplementationsAsync(document, caretPosition, context, cancellationToken); protected override IFindUsagesService? GetService(Document? document) => document?.GetLanguageService<IFindUsagesService>(); } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/vbc/App.config
<?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. --> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <runtime> <AppContextSwitchOverrides value="Switch.System.Security.Cryptography.UseLegacyFipsThrow=false" /> <gcServer enabled="true" /> <gcConcurrent enabled="false"/> </runtime> </configuration>
<?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. --> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <runtime> <AppContextSwitchOverrides value="Switch.System.Security.Cryptography.UseLegacyFipsThrow=false" /> <gcServer enabled="true" /> <gcConcurrent enabled="false"/> </runtime> </configuration>
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Resources/Core/SymbolsTests/Metadata/MDTestAttributeApplicationLib.dll
MZ@ !L!This program cannot be run in DOS mode. $PELN! ^5 @@ @5W@`  H.textd  `.rsrc@@@.reloc `@B@5H H( *0 { +*"}**0 +*( *( *( *( *( *BSJB v4.0.30319l#~T#Strings$#US,#GUID< #BlobW %3 B<55 $U5 p~          " 1 @R5r5! + IP&.6=J\aaaaaaaP C X [p i|   C  C  C  C  C w C )Co1C ACICICQCYCDQC[aC% iCC qCY YCyC C C C# CCC !$'S ' ''' ';! '[ '3 'c 'k 's ).. .[ .3 .S . . .;! . ..c .k .s A|Cta;d;+s { ( 3   ; [H kw S* c^ ;;> { k 3V r ;w#;CJ!KbA3a+1+++m3kk##eh   <Module>mscorlibC1C2`1C3C4InnerC1`1InnerC2`2SystemObject.ctorfield1_Property1get_Property1set_Property1AutoPropertyValueSub1p1Function1Property1T1System.Collections.GenericList`1L1L2L3KeyValuePair`2L4L5TypeA1A2A3A4A5A6A7A8t1s1s2MDTestAttributeDefLibAStringAttributeSystem.Runtime.CompilerServicesCompilerGeneratedAttributeTopLevelClassANestedAttributeAObjectAttributeATypeAttributeAInt32AttributeADoubleAttributeASingleAttributeAInt64AttributeAInt16AttributeAEnumAttributeTestAttributeEnumACharAttributeAByteAttributeABooleanAttributeCompilationRelaxationsAttributeRuntimeCompatibilityAttributeMDTestAttributeApplicationLibMDTestAttributeApplicationLib.dll N~,M_Ԍnz\V4    (         C1 Property1 Sub1p1 Function1 Integer field1  InnerC1 InnerC2 wtwoPZSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 JM! @'Q  snSystem.Collections.Generic.List`1, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089wrSystem.Collections.Generic.List`1[C1], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089OISystem.Collections.Generic.List`1[[System.Collections.Generic.KeyValuePair`2[C1,[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089ztSystem.Collections.Generic.List`1[[System.Collections.Generic.KeyValuePair`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],C1+InnerC1`1+InnerC2`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089  hZSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089C2`1ePZSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089dPZSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089jQPZSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089C1SPTC3helloTSworld  JM! @T DJM! @  mVI@T SI@  @T I@ TI   TI EpTU_TestAttributeEnum, MDTestAttributeDefLib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=nullE  aTCb  TB TBC1SPTAC1C3NoTQOAYesNoNoTSAYesNozTU_TestAttributeEnum, MDTestAttributeDefLib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=nullEATIA_ZSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089I@ object @  JM! @a moduleTWrapNonExceptionThrows assembly,5N5 @5_CorDllMainmscoree.dll% @0HX@4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0d"InternalNameMDTestAttributeApplicationLib.dll(LegalCopyright l"OriginalFilenameMDTestAttributeApplicationLib.dll4ProductVersion0.0.0.08Assembly Version0.0.0.00 `5
MZ@ !L!This program cannot be run in DOS mode. $PELN! ^5 @@ @5W@`  H.textd  `.rsrc@@@.reloc `@B@5H H( *0 { +*"}**0 +*( *( *( *( *( *BSJB v4.0.30319l#~T#Strings$#US,#GUID< #BlobW %3 B<55 $U5 p~          " 1 @R5r5! + IP&.6=J\aaaaaaaP C X [p i|   C  C  C  C  C w C )Co1C ACICICQCYCDQC[aC% iCC qCY YCyC C C C# CCC !$'S ' ''' ';! '[ '3 'c 'k 's ).. .[ .3 .S . . .;! . ..c .k .s A|Cta;d;+s { ( 3   ; [H kw S* c^ ;;> { k 3V r ;w#;CJ!KbA3a+1+++m3kk##eh   <Module>mscorlibC1C2`1C3C4InnerC1`1InnerC2`2SystemObject.ctorfield1_Property1get_Property1set_Property1AutoPropertyValueSub1p1Function1Property1T1System.Collections.GenericList`1L1L2L3KeyValuePair`2L4L5TypeA1A2A3A4A5A6A7A8t1s1s2MDTestAttributeDefLibAStringAttributeSystem.Runtime.CompilerServicesCompilerGeneratedAttributeTopLevelClassANestedAttributeAObjectAttributeATypeAttributeAInt32AttributeADoubleAttributeASingleAttributeAInt64AttributeAInt16AttributeAEnumAttributeTestAttributeEnumACharAttributeAByteAttributeABooleanAttributeCompilationRelaxationsAttributeRuntimeCompatibilityAttributeMDTestAttributeApplicationLibMDTestAttributeApplicationLib.dll N~,M_Ԍnz\V4    (         C1 Property1 Sub1p1 Function1 Integer field1  InnerC1 InnerC2 wtwoPZSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 JM! @'Q  snSystem.Collections.Generic.List`1, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089wrSystem.Collections.Generic.List`1[C1], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089OISystem.Collections.Generic.List`1[[System.Collections.Generic.KeyValuePair`2[C1,[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089ztSystem.Collections.Generic.List`1[[System.Collections.Generic.KeyValuePair`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],C1+InnerC1`1+InnerC2`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089  hZSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089C2`1ePZSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089dPZSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089jQPZSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089C1SPTC3helloTSworld  JM! @T DJM! @  mVI@T SI@  @T I@ TI   TI EpTU_TestAttributeEnum, MDTestAttributeDefLib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=nullE  aTCb  TB TBC1SPTAC1C3NoTQOAYesNoNoTSAYesNozTU_TestAttributeEnum, MDTestAttributeDefLib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=nullEATIA_ZSystem.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089I@ object @  JM! @a moduleTWrapNonExceptionThrows assembly,5N5 @5_CorDllMainmscoree.dll% @0HX@4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0d"InternalNameMDTestAttributeApplicationLib.dll(LegalCopyright l"OriginalFilenameMDTestAttributeApplicationLib.dll4ProductVersion0.0.0.08Assembly Version0.0.0.00 `5
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/Extensibility/Composition/IContentTypeMetadata.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; namespace Microsoft.CodeAnalysis.Editor { internal interface IContentTypeMetadata { IEnumerable<string> ContentTypes { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Editor { internal interface IContentTypeMetadata { IEnumerable<string> ContentTypes { get; } } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Core/Platform/Desktop/ErrorDiagnostics.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 #if NET472 using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Roslyn.Test.Utilities { public sealed class ErrorDiagnostics { public enum WellKnownDll { PlatformVsEditor, PlatformEditor, TextLogic, TextUI, TextWpf, TextData, UIUndo, StandardClassification } public enum DllVersion { Unknown, Beta2, RC } public static List<string> DiagnoseMefProblems() { var list = new List<string>(); var dllList = GetWellKnownDllsWithVersion().ToList(); foreach (var tuple in dllList) { if (tuple.Item3 == DllVersion.RC) { var assembly = tuple.Item1; list.Add(string.Format("Loaded RC version of assembly {0} instead of beta2: {1} - {2}", assembly.GetName().Name, assembly.CodeBase, assembly.Location)); } } return list; } public static IEnumerable<Tuple<Assembly, WellKnownDll>> GetWellKnownDlls() { var list = AppDomain.CurrentDomain.GetAssemblies().ToList(); foreach (var assembly in list) { switch (assembly.GetName().Name) { case "Microsoft.VisualStudio.Platform.VSEditor": yield return Tuple.Create(assembly, WellKnownDll.PlatformVsEditor); break; case "Microsoft.VisualStudio.Platform.Editor": yield return Tuple.Create(assembly, WellKnownDll.PlatformEditor); break; case "Microsoft.VisualStudio.Text.Logic": yield return Tuple.Create(assembly, WellKnownDll.TextLogic); break; case "Microsoft.VisualStudio.Text.UI": yield return Tuple.Create(assembly, WellKnownDll.TextUI); break; case "Microsoft.VisualStudio.Text.Data": yield return Tuple.Create(assembly, WellKnownDll.TextData); break; case "Microsoft.VisualStudio.Text.UI.Wpf": yield return Tuple.Create(assembly, WellKnownDll.TextWpf); break; case "Microsoft.VisualStudio.UI.Undo": yield return Tuple.Create(assembly, WellKnownDll.UIUndo); break; case "Microsoft.VisualStudio.Language.StandardClassification": yield return Tuple.Create(assembly, WellKnownDll.StandardClassification); break; } } } private static IEnumerable<Tuple<Assembly, WellKnownDll, DllVersion>> GetWellKnownDllsWithVersion() { foreach (var pair in GetWellKnownDlls()) { switch (pair.Item2) { case WellKnownDll.PlatformVsEditor: { var type = pair.Item1.GetType("Microsoft.VisualStudio.Text.Implementation.BaseSnapshot"); var ct = type.GetProperty("ContentType"); var version = ct == null ? DllVersion.Beta2 : DllVersion.RC; yield return Tuple.Create(pair.Item1, pair.Item2, version); } break; case WellKnownDll.TextData: { var type = pair.Item1.GetType("Microsoft.VisualStudio.Text.ITextSnapshot"); var ct = type.GetProperty("ContentType"); var version = ct == null ? DllVersion.Beta2 : DllVersion.RC; yield return Tuple.Create(pair.Item1, pair.Item2, version); } break; default: yield return Tuple.Create(pair.Item1, pair.Item2, DllVersion.Unknown); break; } } } } } #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. #nullable disable #if NET472 using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Roslyn.Test.Utilities { public sealed class ErrorDiagnostics { public enum WellKnownDll { PlatformVsEditor, PlatformEditor, TextLogic, TextUI, TextWpf, TextData, UIUndo, StandardClassification } public enum DllVersion { Unknown, Beta2, RC } public static List<string> DiagnoseMefProblems() { var list = new List<string>(); var dllList = GetWellKnownDllsWithVersion().ToList(); foreach (var tuple in dllList) { if (tuple.Item3 == DllVersion.RC) { var assembly = tuple.Item1; list.Add(string.Format("Loaded RC version of assembly {0} instead of beta2: {1} - {2}", assembly.GetName().Name, assembly.CodeBase, assembly.Location)); } } return list; } public static IEnumerable<Tuple<Assembly, WellKnownDll>> GetWellKnownDlls() { var list = AppDomain.CurrentDomain.GetAssemblies().ToList(); foreach (var assembly in list) { switch (assembly.GetName().Name) { case "Microsoft.VisualStudio.Platform.VSEditor": yield return Tuple.Create(assembly, WellKnownDll.PlatformVsEditor); break; case "Microsoft.VisualStudio.Platform.Editor": yield return Tuple.Create(assembly, WellKnownDll.PlatformEditor); break; case "Microsoft.VisualStudio.Text.Logic": yield return Tuple.Create(assembly, WellKnownDll.TextLogic); break; case "Microsoft.VisualStudio.Text.UI": yield return Tuple.Create(assembly, WellKnownDll.TextUI); break; case "Microsoft.VisualStudio.Text.Data": yield return Tuple.Create(assembly, WellKnownDll.TextData); break; case "Microsoft.VisualStudio.Text.UI.Wpf": yield return Tuple.Create(assembly, WellKnownDll.TextWpf); break; case "Microsoft.VisualStudio.UI.Undo": yield return Tuple.Create(assembly, WellKnownDll.UIUndo); break; case "Microsoft.VisualStudio.Language.StandardClassification": yield return Tuple.Create(assembly, WellKnownDll.StandardClassification); break; } } } private static IEnumerable<Tuple<Assembly, WellKnownDll, DllVersion>> GetWellKnownDllsWithVersion() { foreach (var pair in GetWellKnownDlls()) { switch (pair.Item2) { case WellKnownDll.PlatformVsEditor: { var type = pair.Item1.GetType("Microsoft.VisualStudio.Text.Implementation.BaseSnapshot"); var ct = type.GetProperty("ContentType"); var version = ct == null ? DllVersion.Beta2 : DllVersion.RC; yield return Tuple.Create(pair.Item1, pair.Item2, version); } break; case WellKnownDll.TextData: { var type = pair.Item1.GetType("Microsoft.VisualStudio.Text.ITextSnapshot"); var ct = type.GetProperty("ContentType"); var version = ct == null ? DllVersion.Beta2 : DllVersion.RC; yield return Tuple.Create(pair.Item1, pair.Item2, version); } break; default: yield return Tuple.Create(pair.Item1, pair.Item2, DllVersion.Unknown); break; } } } } } #endif
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Workspace/Host/ILanguageService.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.Host { /// <summary> /// Empty interface just to mark language services. /// </summary> public interface ILanguageService { } }
// Licensed to the .NET Foundation under one or more 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.Host { /// <summary> /// Empty interface just to mark language services. /// </summary> public interface ILanguageService { } }
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Dependencies/PooledObjects/Microsoft.CodeAnalysis.PooledObjects.shproj
<?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> <PropertyGroup Label="Globals"> <ProjectGuid>c1930979-c824-496b-a630-70f5369a636f</ProjectGuid> <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> </PropertyGroup> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props')" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props')" /> <PropertyGroup /> <Import Project="Microsoft.CodeAnalysis.PooledObjects.projitems" Label="Shared" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets')" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project> <PropertyGroup Label="Globals"> <ProjectGuid>c1930979-c824-496b-a630-70f5369a636f</ProjectGuid> <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> </PropertyGroup> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props')" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props')" /> <PropertyGroup /> <Import Project="Microsoft.CodeAnalysis.PooledObjects.projitems" Label="Shared" /> <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" Condition="Exists('$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets')" /> </Project>
-1
dotnet/roslyn
55,020
Fix 'move type' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T19:05:46Z
2021-07-22T18:42:39Z
f6c6a6f407383d6bc74f5399f840261a8503951c
91d692fd452933d9852186bdcd5a911b3f2c455b
Fix 'move type' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Symbols/Attributes/WellKnownAttributeData.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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Base class for storing information decoded from well-known custom attributes. /// </summary> internal abstract class WellKnownAttributeData { #pragma warning disable CA1802 // Remove suppression once https://github.com/dotnet/roslyn/issues/20894 is fixed /// <summary> /// Used to distinguish cases when attribute is applied with null value and when attribute is not applied. /// For some well-known attributes, the latter case will return string stored in <see cref="StringMissingValue"/> /// field. /// </summary> public static readonly string StringMissingValue = nameof(StringMissingValue); #pragma warning restore CA1802 #if DEBUG private bool _isSealed; private bool _anyDataStored; #endif public WellKnownAttributeData() { #if DEBUG _isSealed = false; _anyDataStored = false; #endif } [Conditional("DEBUG")] protected void VerifySealed(bool expected = true) { #if DEBUG Debug.Assert(_isSealed == expected); #endif } [Conditional("DEBUG")] internal void VerifyDataStored(bool expected = true) { #if DEBUG Debug.Assert(_anyDataStored == expected); #endif } [Conditional("DEBUG")] protected void SetDataStored() { #if DEBUG _anyDataStored = true; #endif } [Conditional("DEBUG")] internal static void Seal(WellKnownAttributeData data) { #if DEBUG if (data != null) { Debug.Assert(!data._isSealed); Debug.Assert(data._anyDataStored); data._isSealed = true; } #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. #nullable disable using System; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Base class for storing information decoded from well-known custom attributes. /// </summary> internal abstract class WellKnownAttributeData { #pragma warning disable CA1802 // Remove suppression once https://github.com/dotnet/roslyn/issues/20894 is fixed /// <summary> /// Used to distinguish cases when attribute is applied with null value and when attribute is not applied. /// For some well-known attributes, the latter case will return string stored in <see cref="StringMissingValue"/> /// field. /// </summary> public static readonly string StringMissingValue = nameof(StringMissingValue); #pragma warning restore CA1802 #if DEBUG private bool _isSealed; private bool _anyDataStored; #endif public WellKnownAttributeData() { #if DEBUG _isSealed = false; _anyDataStored = false; #endif } [Conditional("DEBUG")] protected void VerifySealed(bool expected = true) { #if DEBUG Debug.Assert(_isSealed == expected); #endif } [Conditional("DEBUG")] internal void VerifyDataStored(bool expected = true) { #if DEBUG Debug.Assert(_anyDataStored == expected); #endif } [Conditional("DEBUG")] protected void SetDataStored() { #if DEBUG _anyDataStored = true; #endif } [Conditional("DEBUG")] internal static void Seal(WellKnownAttributeData data) { #if DEBUG if (data != null) { Debug.Assert(!data._isSealed); Debug.Assert(data._anyDataStored); data._isSealed = true; } #endif } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/CSharp/Analyzers/MatchFolderAndNamespace/CSharpMatchFolderAndNamespaceDiagnosticAnalyzer.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; using Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.CSharp.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.MatchFolderAndNamespace { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpMatchFolderAndNamespaceDiagnosticAnalyzer : AbstractMatchFolderAndNamespaceDiagnosticAnalyzer<NamespaceDeclarationSyntax> { protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; protected override void InitializeWorker(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNamespaceNode, SyntaxKind.NamespaceDeclaration); } } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.MatchFolderAndNamespace { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpMatchFolderAndNamespaceDiagnosticAnalyzer : AbstractMatchFolderAndNamespaceDiagnosticAnalyzer<SyntaxKind, BaseNamespaceDeclarationSyntax> { protected override ISyntaxFacts GetSyntaxFacts() => CSharpSyntaxFacts.Instance; protected override ImmutableArray<SyntaxKind> GetSyntaxKindsToAnalyze() => ImmutableArray.Create(SyntaxKind.NamespaceDeclaration, SyntaxKind.FileScopedNamespaceDeclaration); } }
1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/CSharp/Tests/MatchFolderAndNamespace/CSharpMatchFolderAndNamespaceTests.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.IO; using System.Threading.Tasks; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.Analyzers.MatchFolderAndNamespace.CSharpMatchFolderAndNamespaceDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.CodeFixes.MatchFolderAndNamespace.CSharpChangeNamespaceToMatchFolderCodeFixProvider>; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.MatchFolderAndNamespace { public class CSharpMatchFolderAndNamespaceTests { private static readonly string Directory = Path.Combine("Test", "Directory"); // DefaultNamespace gets exposed as RootNamespace in the build properties private const string DefaultNamespace = "Test.Root.Namespace"; private static readonly string EditorConfig = @$" is_global=true build_property.ProjectDir = {Directory} build_property.RootNamespace = {DefaultNamespace} "; private static string CreateFolderPath(params string[] folders) => Path.Combine(Directory, Path.Combine(folders)); private static Task RunTestAsync(string fileName, string fileContents, string? directory = null, string? editorConfig = null, string? fixedCode = null) { var filePath = Path.Combine(directory ?? Directory, fileName); fixedCode ??= fileContents; return RunTestAsync( new[] { (filePath, fileContents) }, new[] { (filePath, fixedCode) }, editorConfig); } private static Task RunTestAsync(IEnumerable<(string, string)> originalSources, IEnumerable<(string, string)>? fixedSources = null, string? editorconfig = null) { var testState = new VerifyCS.Test { EditorConfig = editorconfig ?? EditorConfig, CodeFixTestBehaviors = CodeAnalysis.Testing.CodeFixTestBehaviors.SkipFixAllInDocumentCheck }; foreach (var (fileName, content) in originalSources) { testState.TestState.Sources.Add((fileName, content)); } fixedSources ??= Array.Empty<(string, string)>(); foreach (var (fileName, content) in fixedSources) { testState.FixedState.Sources.Add((fileName, content)); } return testState.RunAsync(); } [Fact] public Task InvalidFolderName1_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "3B", "C" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName2_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "B.3C", "D" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName3_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { ".folder", "..subfolder", "name" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task CaseInsensitiveMatch_NoDiagnostic() { var folder = CreateFolderPath(new[] { "A", "B" }); var code = @$" namespace {DefaultNamespace}.a.b {{ class Class1 {{ }} }}"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public async Task SingleDocumentNoReference() { var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|] { class Class1 { } }"; var fixedCode = @$"namespace {DefaultNamespace}.B.C {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode); } [Fact] public async Task SingleDocumentNoReference_NoDefaultNamespace() { var editorConfig = @$" is_global=true build_property.ProjectDir = {Directory} "; var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|] { class Class1 { } }"; var fixedCode = @$"namespace B.C {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode, editorConfig: editorConfig); } [Fact] public async Task NamespaceWithSpaces_NoDiagnostic() { var folder = CreateFolderPath("A", "B"); var code = @$"namespace {DefaultNamespace}.A . B {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task NestedNamespaces_NoDiagnostic() { // The code fix doesn't currently support nested namespaces for sync, so // diagnostic does not report. var folder = CreateFolderPath("B", "C"); var code = @"namespace A.B { namespace C.D { class CDClass { } } class ABClass { } }"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task PartialTypeWithMultipleDeclarations_NoDiagnostic() { // The code fix doesn't currently support nested namespaces for sync, so // diagnostic does not report. var folder = CreateFolderPath("B", "C"); var code1 = @"namespace A.B { partial class ABClass { void M1() {} } }"; var code2 = @"namespace A.B { partial class ABClass { void M2() {} } }"; var sources = new[] { (Path.Combine(folder, "ABClass1.cs"), code1), (Path.Combine(folder, "ABClass2.cs"), code2), }; await RunTestAsync(sources); } [Fact] public async Task FileNotInProjectFolder_NoDiagnostic() { // Default directory is Test\Directory for the project, // putting the file outside the directory should have no // diagnostic shown. var folder = Path.Combine("B", "C"); var code = $@"namespace A.B {{ class ABClass {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task SingleDocumentLocalReference() { var @namespace = "Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code = $@" namespace [|{@namespace}|] {{ delegate void D1(); interface Class1 {{ void M1(); }} class Class2 : {@namespace}.Class1 {{ {@namespace}.D1 d; void {@namespace}.Class1.M1(){{}} }} }}"; var expected = @$"namespace {DefaultNamespace}.A.B.C {{ delegate void D1(); interface Class1 {{ void M1(); }} class Class2 : Class1 {{ D1 d; void Class1.M1() {{ }} }} }}"; await RunTestAsync( "Class1.cs", code, folder, fixedCode: expected); } [Fact] public async Task ChangeUsingsInMultipleContainers() { var declaredNamespace = "Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ }} }}"; var code2 = $@"namespace NS1 {{ using {declaredNamespace}; class Class2 {{ Class1 c2; }} namespace NS2 {{ using {declaredNamespace}; class Class2 {{ Class1 c1; }} }} }}"; var fixed1 = @$"namespace {DefaultNamespace}.A.B.C {{ class Class1 {{ }} }}"; var fixed2 = @$"namespace NS1 {{ using {DefaultNamespace}.A.B.C; class Class2 {{ Class1 c2; }} namespace NS2 {{ class Class2 {{ Class1 c1; }} }} }}"; var originalSources = new[] { (Path.Combine(folder, "Class1.cs"), code1), ("Class2.cs", code2) }; var fixedSources = new[] { (Path.Combine(folder, "Class1.cs"), fixed1), ("Class2.cs", fixed2) }; await RunTestAsync(originalSources, fixedSources); } [Fact] public async Task ChangeNamespace_WithAliasReferencesInOtherDocument() { var declaredNamespace = $"Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ }} }}"; var code2 = $@" using System; using {declaredNamespace}; using Class1Alias = {declaredNamespace}.Class1; namespace Foo {{ class RefClass {{ private Class1Alias c1; }} }}"; var fixed1 = @$"namespace {DefaultNamespace}.A.B.C {{ class Class1 {{ }} }}"; var fixed2 = @$" using System; using Class1Alias = {DefaultNamespace}.A.B.C.Class1; namespace Foo {{ class RefClass {{ private Class1Alias c1; }} }}"; var originalSources = new[] { (Path.Combine(folder, "Class1.cs"), code1), ("Class2.cs", code2) }; var fixedSources = new[] { (Path.Combine(folder, "Class1.cs"), fixed1), ("Class2.cs", fixed2) }; await RunTestAsync(originalSources, fixedSources); } [Fact] public async Task FixAll() { var declaredNamespace = "Bar.Baz"; var folder1 = CreateFolderPath("A", "B", "C"); var fixedNamespace1 = $"{DefaultNamespace}.A.B.C"; var folder2 = CreateFolderPath("Second", "Folder", "Path"); var fixedNamespace2 = $"{DefaultNamespace}.Second.Folder.Path"; var folder3 = CreateFolderPath("Third", "Folder", "Path"); var fixedNamespace3 = $"{DefaultNamespace}.Third.Folder.Path"; var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ Class2 C2 {{ get; }} Class3 C3 {{ get; }} }} }}"; var fixed1 = $@"using {fixedNamespace2}; using {fixedNamespace3}; namespace {fixedNamespace1} {{ class Class1 {{ Class2 C2 {{ get; }} Class3 C3 {{ get; }} }} }}"; var code2 = $@"namespace [|{declaredNamespace}|] {{ class Class2 {{ Class1 C1 {{ get; }} Class3 C3 {{ get; }} }} }}"; var fixed2 = $@"using {fixedNamespace1}; using {fixedNamespace3}; namespace {fixedNamespace2} {{ class Class2 {{ Class1 C1 {{ get; }} Class3 C3 {{ get; }} }} }}"; var code3 = $@"namespace [|{declaredNamespace}|] {{ class Class3 {{ Class1 C1 {{ get; }} Class2 C2 {{ get; }} }} }}"; var fixed3 = $@"using {fixedNamespace1}; using {fixedNamespace2}; namespace {fixedNamespace3} {{ class Class3 {{ Class1 C1 {{ get; }} Class2 C2 {{ get; }} }} }}"; var sources = new[] { (Path.Combine(folder1, "Class1.cs"), code1), (Path.Combine(folder2, "Class2.cs"), code2), (Path.Combine(folder3, "Class3.cs"), code3), }; var fixedSources = new[] { (Path.Combine(folder1, "Class1.cs"), fixed1), (Path.Combine(folder2, "Class2.cs"), fixed2), (Path.Combine(folder3, "Class3.cs"), fixed3), }; await RunTestAsync(sources, fixedSources); } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Threading.Tasks; using Xunit; using VerifyCS = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.CSharpCodeFixVerifier< Microsoft.CodeAnalysis.CSharp.Analyzers.MatchFolderAndNamespace.CSharpMatchFolderAndNamespaceDiagnosticAnalyzer, Microsoft.CodeAnalysis.CSharp.CodeFixes.MatchFolderAndNamespace.CSharpChangeNamespaceToMatchFolderCodeFixProvider>; namespace Microsoft.CodeAnalysis.CSharp.Analyzers.UnitTests.MatchFolderAndNamespace { public class CSharpMatchFolderAndNamespaceTests { private static readonly string Directory = Path.Combine("Test", "Directory"); // DefaultNamespace gets exposed as RootNamespace in the build properties private const string DefaultNamespace = "Test.Root.Namespace"; private static readonly string EditorConfig = @$" is_global=true build_property.ProjectDir = {Directory} build_property.RootNamespace = {DefaultNamespace} "; private static string CreateFolderPath(params string[] folders) => Path.Combine(Directory, Path.Combine(folders)); private static Task RunTestAsync(string fileName, string fileContents, string? directory = null, string? editorConfig = null, string? fixedCode = null) { var filePath = Path.Combine(directory ?? Directory, fileName); fixedCode ??= fileContents; return RunTestAsync( new[] { (filePath, fileContents) }, new[] { (filePath, fixedCode) }, editorConfig); } private static Task RunTestAsync(IEnumerable<(string, string)> originalSources, IEnumerable<(string, string)>? fixedSources = null, string? editorconfig = null) { var testState = new VerifyCS.Test { EditorConfig = editorconfig ?? EditorConfig, CodeFixTestBehaviors = CodeAnalysis.Testing.CodeFixTestBehaviors.SkipFixAllInDocumentCheck, LanguageVersion = LanguageVersion.CSharp10, }; foreach (var (fileName, content) in originalSources) testState.TestState.Sources.Add((fileName, content)); fixedSources ??= Array.Empty<(string, string)>(); foreach (var (fileName, content) in fixedSources) testState.FixedState.Sources.Add((fileName, content)); return testState.RunAsync(); } [Fact] public Task InvalidFolderName1_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "3B", "C" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName1_NoDiagnostic_FileScopedNamespace() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "3B", "C" }); var code = @" namespace A.B; class Class1 { } "; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName2_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { "B.3C", "D" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task InvalidFolderName3_NoDiagnostic() { // No change namespace action because the folder name is not valid identifier var folder = CreateFolderPath(new[] { ".folder", "..subfolder", "name" }); var code = @" namespace A.B { class Class1 { } }"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public Task CaseInsensitiveMatch_NoDiagnostic() { var folder = CreateFolderPath(new[] { "A", "B" }); var code = @$" namespace {DefaultNamespace}.a.b {{ class Class1 {{ }} }}"; return RunTestAsync( "File1.cs", code, directory: folder); } [Fact] public async Task SingleDocumentNoReference() { var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|] { class Class1 { } }"; var fixedCode = @$"namespace {DefaultNamespace}.B.C {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode); } [Fact] public async Task SingleDocumentNoReference_FileScopedNamespace() { var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|]; class Class1 { } "; var fixedCode = @$"namespace {DefaultNamespace}.B.C; class Class1 {{ }} "; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode); } [Fact] public async Task SingleDocumentNoReference_NoDefaultNamespace() { var editorConfig = @$" is_global=true build_property.ProjectDir = {Directory} "; var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|] { class Class1 { } }"; var fixedCode = @$"namespace B.C {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode, editorConfig: editorConfig); } [Fact] public async Task SingleDocumentNoReference_NoDefaultNamespace_FileScopedNamespace() { var editorConfig = @$" is_global=true build_property.ProjectDir = {Directory} "; var folder = CreateFolderPath("B", "C"); var code = @"namespace [|A.B|]; class Class1 { } "; var fixedCode = @$"namespace B.C; class Class1 {{ }} "; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder, fixedCode: fixedCode, editorConfig: editorConfig); } [Fact] public async Task NamespaceWithSpaces_NoDiagnostic() { var folder = CreateFolderPath("A", "B"); var code = @$"namespace {DefaultNamespace}.A . B {{ class Class1 {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task NestedNamespaces_NoDiagnostic() { // The code fix doesn't currently support nested namespaces for sync, so // diagnostic does not report. var folder = CreateFolderPath("B", "C"); var code = @"namespace A.B { namespace C.D { class CDClass { } } class ABClass { } }"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task PartialTypeWithMultipleDeclarations_NoDiagnostic() { // The code fix doesn't currently support nested namespaces for sync, so // diagnostic does not report. var folder = CreateFolderPath("B", "C"); var code1 = @"namespace A.B { partial class ABClass { void M1() {} } }"; var code2 = @"namespace A.B { partial class ABClass { void M2() {} } }"; var sources = new[] { (Path.Combine(folder, "ABClass1.cs"), code1), (Path.Combine(folder, "ABClass2.cs"), code2), }; await RunTestAsync(sources); } [Fact] public async Task FileNotInProjectFolder_NoDiagnostic() { // Default directory is Test\Directory for the project, // putting the file outside the directory should have no // diagnostic shown. var folder = Path.Combine("B", "C"); var code = $@"namespace A.B {{ class ABClass {{ }} }}"; await RunTestAsync( fileName: "Class1.cs", fileContents: code, directory: folder); } [Fact] public async Task SingleDocumentLocalReference() { var @namespace = "Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code = $@" namespace [|{@namespace}|] {{ delegate void D1(); interface Class1 {{ void M1(); }} class Class2 : {@namespace}.Class1 {{ {@namespace}.D1 d; void {@namespace}.Class1.M1(){{}} }} }}"; var expected = @$"namespace {DefaultNamespace}.A.B.C {{ delegate void D1(); interface Class1 {{ void M1(); }} class Class2 : Class1 {{ D1 d; void Class1.M1() {{ }} }} }}"; await RunTestAsync( "Class1.cs", code, folder, fixedCode: expected); } [Fact] public async Task ChangeUsingsInMultipleContainers() { var declaredNamespace = "Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ }} }}"; var code2 = $@"namespace NS1 {{ using {declaredNamespace}; class Class2 {{ Class1 c2; }} namespace NS2 {{ using {declaredNamespace}; class Class2 {{ Class1 c1; }} }} }}"; var fixed1 = @$"namespace {DefaultNamespace}.A.B.C {{ class Class1 {{ }} }}"; var fixed2 = @$"namespace NS1 {{ using {DefaultNamespace}.A.B.C; class Class2 {{ Class1 c2; }} namespace NS2 {{ class Class2 {{ Class1 c1; }} }} }}"; var originalSources = new[] { (Path.Combine(folder, "Class1.cs"), code1), ("Class2.cs", code2) }; var fixedSources = new[] { (Path.Combine(folder, "Class1.cs"), fixed1), ("Class2.cs", fixed2) }; await RunTestAsync(originalSources, fixedSources); } [Fact] public async Task ChangeNamespace_WithAliasReferencesInOtherDocument() { var declaredNamespace = $"Bar.Baz"; var folder = CreateFolderPath("A", "B", "C"); var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ }} }}"; var code2 = $@" using System; using {declaredNamespace}; using Class1Alias = {declaredNamespace}.Class1; namespace Foo {{ class RefClass {{ private Class1Alias c1; }} }}"; var fixed1 = @$"namespace {DefaultNamespace}.A.B.C {{ class Class1 {{ }} }}"; var fixed2 = @$" using System; using Class1Alias = {DefaultNamespace}.A.B.C.Class1; namespace Foo {{ class RefClass {{ private Class1Alias c1; }} }}"; var originalSources = new[] { (Path.Combine(folder, "Class1.cs"), code1), ("Class2.cs", code2) }; var fixedSources = new[] { (Path.Combine(folder, "Class1.cs"), fixed1), ("Class2.cs", fixed2) }; await RunTestAsync(originalSources, fixedSources); } [Fact] public async Task FixAll() { var declaredNamespace = "Bar.Baz"; var folder1 = CreateFolderPath("A", "B", "C"); var fixedNamespace1 = $"{DefaultNamespace}.A.B.C"; var folder2 = CreateFolderPath("Second", "Folder", "Path"); var fixedNamespace2 = $"{DefaultNamespace}.Second.Folder.Path"; var folder3 = CreateFolderPath("Third", "Folder", "Path"); var fixedNamespace3 = $"{DefaultNamespace}.Third.Folder.Path"; var code1 = $@"namespace [|{declaredNamespace}|] {{ class Class1 {{ Class2 C2 {{ get; }} Class3 C3 {{ get; }} }} }}"; var fixed1 = $@"using {fixedNamespace2}; using {fixedNamespace3}; namespace {fixedNamespace1} {{ class Class1 {{ Class2 C2 {{ get; }} Class3 C3 {{ get; }} }} }}"; var code2 = $@"namespace [|{declaredNamespace}|] {{ class Class2 {{ Class1 C1 {{ get; }} Class3 C3 {{ get; }} }} }}"; var fixed2 = $@"using {fixedNamespace1}; using {fixedNamespace3}; namespace {fixedNamespace2} {{ class Class2 {{ Class1 C1 {{ get; }} Class3 C3 {{ get; }} }} }}"; var code3 = $@"namespace [|{declaredNamespace}|] {{ class Class3 {{ Class1 C1 {{ get; }} Class2 C2 {{ get; }} }} }}"; var fixed3 = $@"using {fixedNamespace1}; using {fixedNamespace2}; namespace {fixedNamespace3} {{ class Class3 {{ Class1 C1 {{ get; }} Class2 C2 {{ get; }} }} }}"; var sources = new[] { (Path.Combine(folder1, "Class1.cs"), code1), (Path.Combine(folder2, "Class2.cs"), code2), (Path.Combine(folder3, "Class3.cs"), code3), }; var fixedSources = new[] { (Path.Combine(folder1, "Class1.cs"), fixed1), (Path.Combine(folder2, "Class2.cs"), fixed2), (Path.Combine(folder3, "Class3.cs"), fixed3), }; await RunTestAsync(sources, fixedSources); } } }
1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/Core/Analyzers/MatchFolderAndNamespace/AbstractMatchFolderAndNamespaceDiagnosticAnalyzer.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.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace { internal abstract class AbstractMatchFolderAndNamespaceDiagnosticAnalyzer<TNamespaceSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TNamespaceSyntax : SyntaxNode { private static readonly LocalizableResourceString s_localizableTitle = new( nameof(AnalyzersResources.Namespace_does_not_match_folder_structure), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableInsideMessage = new( nameof(AnalyzersResources.Namespace_0_does_not_match_folder_structure_expected_1), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly SymbolDisplayFormat s_namespaceDisplayFormat = SymbolDisplayFormat .FullyQualifiedFormat .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted); protected AbstractMatchFolderAndNamespaceDiagnosticAnalyzer() : base(IDEDiagnosticIds.MatchFolderAndNamespaceDiagnosticId, EnforceOnBuildValues.MatchFolderAndNamespace, CodeStyleOptions2.PreferNamespaceAndFolderMatchStructure, s_localizableTitle, s_localizableInsideMessage) { } protected abstract ISyntaxFacts GetSyntaxFacts(); public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected void AnalyzeNamespaceNode(SyntaxNodeAnalysisContext context) { // It's ok to not have a rootnamespace property, but if it's there we want to use it correctly context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(MatchFolderAndNamespaceConstants.RootNamespaceOption, out var rootNamespace); // Project directory is a must to correctly get the relative path and construct a namespace if (!context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(MatchFolderAndNamespaceConstants.ProjectDirOption, out var projectDir) || string.IsNullOrEmpty(projectDir)) { return; } var namespaceDecl = (TNamespaceSyntax)context.Node; var symbol = context.SemanticModel.GetDeclaredSymbol(namespaceDecl); RoslynDebug.AssertNotNull(symbol); var currentNamespace = symbol.ToDisplayString(s_namespaceDisplayFormat); if (IsFileAndNamespaceMismatch(namespaceDecl, rootNamespace, projectDir, currentNamespace, out var targetNamespace) && IsFixSupported(context.SemanticModel, namespaceDecl, context.CancellationToken)) { var nameSyntax = GetSyntaxFacts().GetNameOfNamespaceDeclaration(namespaceDecl); RoslynDebug.AssertNotNull(nameSyntax); context.ReportDiagnostic(Diagnostic.Create( Descriptor, nameSyntax.GetLocation(), additionalLocations: null, properties: ImmutableDictionary<string, string?>.Empty.Add(MatchFolderAndNamespaceConstants.TargetNamespace, targetNamespace), messageArgs: new[] { currentNamespace, targetNamespace })); } } private bool IsFixSupported(SemanticModel semanticModel, TNamespaceSyntax namespaceDeclaration, CancellationToken cancellationToken) { var root = namespaceDeclaration.SyntaxTree.GetRoot(cancellationToken); // It should not be nested in other namespaces if (namespaceDeclaration.Ancestors().OfType<TNamespaceSyntax>().Any()) { return false; } // It should not contain a namespace var containsNamespace = namespaceDeclaration .DescendantNodes(n => n is TNamespaceSyntax) .OfType<TNamespaceSyntax>().Any(); if (containsNamespace) { return false; } // The current namespace should be valid var isCurrentNamespaceInvalid = GetSyntaxFacts() .GetNameOfNamespaceDeclaration(namespaceDeclaration) ?.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) ?? false; if (isCurrentNamespaceInvalid) { return false; } // It should not contain partial classes with more than one instance in the semantic model. The // fixer does not support this scenario. var containsPartialType = ContainsPartialTypeWithMultipleDeclarations(namespaceDeclaration, semanticModel); if (containsPartialType) { return false; } return true; } private bool IsFileAndNamespaceMismatch( TNamespaceSyntax namespaceDeclaration, string? rootNamespace, string projectDir, string currentNamespace, [NotNullWhen(returnValue: true)] out string? targetNamespace) { if (!PathUtilities.IsChildPath(projectDir, namespaceDeclaration.SyntaxTree.FilePath)) { // The file does not exist within the project directory targetNamespace = null; return false; } var relativeDirectoryPath = PathUtilities.GetRelativePath( projectDir, PathUtilities.GetDirectoryName(namespaceDeclaration.SyntaxTree.FilePath)!); var folders = relativeDirectoryPath.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); var expectedNamespace = PathMetadataUtilities.TryBuildNamespaceFromFolders(folders, GetSyntaxFacts(), rootNamespace); if (RoslynString.IsNullOrWhiteSpace(expectedNamespace) || expectedNamespace.Equals(currentNamespace, StringComparison.OrdinalIgnoreCase)) { // The namespace currently matches the folder structure or is invalid, in which case we don't want // to provide a diagnostic. targetNamespace = null; return false; } targetNamespace = expectedNamespace; return true; } /// <summary> /// Returns true if the namespace declaration contains one or more partial types with multiple declarations. /// </summary> protected bool ContainsPartialTypeWithMultipleDeclarations(TNamespaceSyntax namespaceDeclaration, SemanticModel semanticModel) { var syntaxFacts = GetSyntaxFacts(); var typeDeclarations = syntaxFacts.GetMembersOfNamespaceDeclaration(namespaceDeclaration) .Where(member => syntaxFacts.IsTypeDeclaration(member)); foreach (var typeDecl in typeDeclarations) { var symbol = semanticModel.GetDeclaredSymbol(typeDecl); // Simplify the check by assuming no multiple partial declarations in one document if (symbol is ITypeSymbol typeSymbol && typeSymbol.DeclaringSyntaxReferences.Length > 1) { return true; } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Analyzers.MatchFolderAndNamespace { internal abstract class AbstractMatchFolderAndNamespaceDiagnosticAnalyzer<TSyntaxKind, TNamespaceSyntax> : AbstractBuiltInCodeStyleDiagnosticAnalyzer where TSyntaxKind : struct where TNamespaceSyntax : SyntaxNode { private static readonly LocalizableResourceString s_localizableTitle = new( nameof(AnalyzersResources.Namespace_does_not_match_folder_structure), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly LocalizableResourceString s_localizableInsideMessage = new( nameof(AnalyzersResources.Namespace_0_does_not_match_folder_structure_expected_1), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); private static readonly SymbolDisplayFormat s_namespaceDisplayFormat = SymbolDisplayFormat .FullyQualifiedFormat .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted); protected AbstractMatchFolderAndNamespaceDiagnosticAnalyzer() : base(IDEDiagnosticIds.MatchFolderAndNamespaceDiagnosticId, EnforceOnBuildValues.MatchFolderAndNamespace, CodeStyleOptions2.PreferNamespaceAndFolderMatchStructure, s_localizableTitle, s_localizableInsideMessage) { } protected abstract ISyntaxFacts GetSyntaxFacts(); protected abstract ImmutableArray<TSyntaxKind> GetSyntaxKindsToAnalyze(); protected sealed override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeNamespaceNode, GetSyntaxKindsToAnalyze()); public override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; private void AnalyzeNamespaceNode(SyntaxNodeAnalysisContext context) { // It's ok to not have a rootnamespace property, but if it's there we want to use it correctly context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(MatchFolderAndNamespaceConstants.RootNamespaceOption, out var rootNamespace); // Project directory is a must to correctly get the relative path and construct a namespace if (!context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue(MatchFolderAndNamespaceConstants.ProjectDirOption, out var projectDir) || string.IsNullOrEmpty(projectDir)) { return; } var namespaceDecl = (TNamespaceSyntax)context.Node; var symbol = context.SemanticModel.GetDeclaredSymbol(namespaceDecl); RoslynDebug.AssertNotNull(symbol); var currentNamespace = symbol.ToDisplayString(s_namespaceDisplayFormat); if (IsFileAndNamespaceMismatch(namespaceDecl, rootNamespace, projectDir, currentNamespace, out var targetNamespace) && IsFixSupported(context.SemanticModel, namespaceDecl, context.CancellationToken)) { var nameSyntax = GetSyntaxFacts().GetNameOfNamespaceDeclaration(namespaceDecl); RoslynDebug.AssertNotNull(nameSyntax); context.ReportDiagnostic(Diagnostic.Create( Descriptor, nameSyntax.GetLocation(), additionalLocations: null, properties: ImmutableDictionary<string, string?>.Empty.Add(MatchFolderAndNamespaceConstants.TargetNamespace, targetNamespace), messageArgs: new[] { currentNamespace, targetNamespace })); } } private bool IsFixSupported(SemanticModel semanticModel, TNamespaceSyntax namespaceDeclaration, CancellationToken cancellationToken) { var root = namespaceDeclaration.SyntaxTree.GetRoot(cancellationToken); // It should not be nested in other namespaces if (namespaceDeclaration.Ancestors().OfType<TNamespaceSyntax>().Any()) { return false; } // It should not contain a namespace var containsNamespace = namespaceDeclaration .DescendantNodes(n => n is TNamespaceSyntax) .OfType<TNamespaceSyntax>().Any(); if (containsNamespace) { return false; } // The current namespace should be valid var isCurrentNamespaceInvalid = GetSyntaxFacts() .GetNameOfNamespaceDeclaration(namespaceDeclaration) ?.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) ?? false; if (isCurrentNamespaceInvalid) { return false; } // It should not contain partial classes with more than one instance in the semantic model. The // fixer does not support this scenario. var containsPartialType = ContainsPartialTypeWithMultipleDeclarations(namespaceDeclaration, semanticModel); if (containsPartialType) { return false; } return true; } private bool IsFileAndNamespaceMismatch( TNamespaceSyntax namespaceDeclaration, string? rootNamespace, string projectDir, string currentNamespace, [NotNullWhen(returnValue: true)] out string? targetNamespace) { if (!PathUtilities.IsChildPath(projectDir, namespaceDeclaration.SyntaxTree.FilePath)) { // The file does not exist within the project directory targetNamespace = null; return false; } var relativeDirectoryPath = PathUtilities.GetRelativePath( projectDir, PathUtilities.GetDirectoryName(namespaceDeclaration.SyntaxTree.FilePath)!); var folders = relativeDirectoryPath.Split(new[] { Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries); var expectedNamespace = PathMetadataUtilities.TryBuildNamespaceFromFolders(folders, GetSyntaxFacts(), rootNamespace); if (RoslynString.IsNullOrWhiteSpace(expectedNamespace) || expectedNamespace.Equals(currentNamespace, StringComparison.OrdinalIgnoreCase)) { // The namespace currently matches the folder structure or is invalid, in which case we don't want // to provide a diagnostic. targetNamespace = null; return false; } targetNamespace = expectedNamespace; return true; } /// <summary> /// Returns true if the namespace declaration contains one or more partial types with multiple declarations. /// </summary> protected bool ContainsPartialTypeWithMultipleDeclarations(TNamespaceSyntax namespaceDeclaration, SemanticModel semanticModel) { var syntaxFacts = GetSyntaxFacts(); var typeDeclarations = syntaxFacts.GetMembersOfNamespaceDeclaration(namespaceDeclaration) .Where(member => syntaxFacts.IsTypeDeclaration(member)); foreach (var typeDecl in typeDeclarations) { var symbol = semanticModel.GetDeclaredSymbol(typeDecl); // Simplify the check by assuming no multiple partial declarations in one document if (symbol is ITypeSymbol typeSymbol && typeSymbol.DeclaringSyntaxReferences.Length > 1) { return true; } } return false; } } }
1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Debugging/LocationInfoGetterTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Debugging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Debugging { [UseExportProvider] public class LocationInfoGetterTests { private static async Task TestAsync(string markup, string expectedName, int expectedLineOffset, CSharpParseOptions parseOptions = null) { using var workspace = TestWorkspace.CreateCSharp(markup, parseOptions); var testDocument = workspace.Documents.Single(); var position = testDocument.CursorPosition.Value; var locationInfo = await LocationInfoGetter.GetInfoAsync( workspace.CurrentSolution.Projects.Single().Documents.Single(), position, CancellationToken.None); Assert.Equal(expectedName, locationInfo.Name); Assert.Equal(expectedLineOffset, locationInfo.LineOffset); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestClass() => await TestAsync("class G$$oo { }", "Goo", 0); [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668"), WorkItem(538415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538415")] public async Task TestMethod() { await TestAsync( @"class Class { public static void Meth$$od() { } } ", "Class.Method()", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestNamespace() { await TestAsync( @"namespace Namespace { class Class { void Method() { }$$ } }", "Namespace.Class.Method()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(49000, "https://github.com/dotnet/roslyn/issues/49000")] public async Task TestFileScopedNamespace() { // This test behavior is incorrect. This should be Namespace.Class.Method. // See the associated WorkItem for details. await TestAsync( @"namespace Namespace; class Class { void Method() { }$$ } ", "Class.Method()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestDottedNamespace() { await TestAsync( @"namespace Namespace.Another { class Class { void Method() { }$$ } }", "Namespace.Another.Class.Method()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestNestedNamespace() { await TestAsync( @"namespace Namespace { namespace Another { class Class { void Method() { }$$ } } }", "Namespace.Another.Class.Method()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestNestedType() { await TestAsync( @"class Outer { class Inner { void Quux() {$$ } } }", "Outer.Inner.Quux()", 1); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestPropertyGetter() { await TestAsync( @"class Class { string Property { get { return null;$$ } } }", "Class.Property", 4); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestPropertySetter() { await TestAsync( @"class Class { string Property { get { return null; } set { string s = $$value; } } }", "Class.Property", 9); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(538415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538415")] public async Task TestField() { await TestAsync( @"class Class { int fi$$eld; }", "Class.field", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")] public async Task TestLambdaInFieldInitializer() { await TestAsync( @"class Class { Action<int> a = b => { in$$t c; }; }", "Class.a", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")] public async Task TestMultipleFields() { await TestAsync( @"class Class { int a1, a$$2; }", "Class.a2", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestConstructor() { await TestAsync( @"class C1 { C1() { $$} } ", "C1.C1()", 3); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestDestructor() { await TestAsync( @"class C1 { ~C1() { $$} } ", "C1.~C1()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestOperator() { await TestAsync( @"namespace N1 { class C1 { public static int operator +(C1 x, C1 y) { $$return 42; } } } ", "N1.C1.+(C1 x, C1 y)", 2); // Old implementation reports "operator +" (rather than "+")... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestConversionOperator() { await TestAsync( @"namespace N1 { class C1 { public static explicit operator N1.C2(N1.C1 x) { $$return null; } } class C2 { } } ", "N1.C1.N1.C2(N1.C1 x)", 2); // Old implementation reports "explicit operator N1.C2" (rather than "N1.C2")... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestEvent() { await TestAsync( @"class C1 { delegate void D1(); event D1 e1$$; } ", "C1.e1", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TextExplicitInterfaceImplementation() { await TestAsync( @"interface I1 { void M1(); } class C1 { void I1.M1() { $$} } ", "C1.M1()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TextIndexer() { await TestAsync( @"class C1 { C1 this[int x] { get { $$return null; } } } ", "C1.this[int x]", 4); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestParamsParameter() { await TestAsync( @"class C1 { void M1(params int[] x) { $$ } } ", "C1.M1(params int[] x)", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestArglistParameter() { await TestAsync( @"class C1 { void M1(__arglist) { $$ } } ", "C1.M1(__arglist)", 0); // Old implementation does not show "__arglist"... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestRefAndOutParameters() { await TestAsync( @"class C1 { void M1( ref int x, out int y ) { $$y = x; } } ", "C1.M1( ref int x, out int y )", 2); // Old implementation did not show extra spaces around the parameters... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestOptionalParameters() { await TestAsync( @"class C1 { void M1(int x =1) { $$y = x; } } ", "C1.M1(int x =1)", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestExtensionMethod() { await TestAsync( @"static class C1 { static void M1(this int x) { }$$ } ", "C1.M1(this int x)", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestGenericType() { await TestAsync( @"class C1<T, U> { static void M1() { $$ } } ", "C1.M1()", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestGenericMethod() { await TestAsync( @"class C1<T, U> { static void M1<V>() { $$ } } ", "C1.M1()", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestGenericParameters() { await TestAsync( @"class C1<T, U> { static void M1<V>(C1<int, V> x, V y) { $$ } } ", "C1.M1(C1<int, V> x, V y)", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingNamespace() { await TestAsync( @"{ class Class { int a1, a$$2; } }", "Class.a2", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingNamespaceName() { await TestAsync( @"namespace { class C1 { int M1() $${ } } }", "?.C1.M1()", 1); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingClassName() { await TestAsync( @"namespace N1 class { int M1() $${ } } }", "N1.M1()", 1); // Old implementation displayed "N1.?.M1", but we don't see a class declaration in the syntax tree... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingMethodName() { await TestAsync( @"namespace N1 { class C1 { static void (ref int x) { $$} } }", "N1.C1", 4); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingParameterList() { await TestAsync( @"namespace N1 { class C1 { static void M1 { $$} } }", "N1.C1.M1", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TopLevelField() { await TestAsync( @"$$int f1; ", "f1", 0, new CSharpParseOptions(kind: SourceCodeKind.Script)); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TopLevelMethod() { await TestAsync( @"int M1(int x) { $$} ", "M1(int x)", 2, new CSharpParseOptions(kind: SourceCodeKind.Script)); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TopLevelStatement() { await TestAsync( @" $$System.Console.WriteLine(""Hello"") ", null, 0, new CSharpParseOptions(kind: SourceCodeKind.Script)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Debugging; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Debugging { [UseExportProvider] public class LocationInfoGetterTests { private static async Task TestAsync(string markup, string expectedName, int expectedLineOffset, CSharpParseOptions parseOptions = null) { using var workspace = TestWorkspace.CreateCSharp(markup, parseOptions); var testDocument = workspace.Documents.Single(); var position = testDocument.CursorPosition.Value; var locationInfo = await LocationInfoGetter.GetInfoAsync( workspace.CurrentSolution.Projects.Single().Documents.Single(), position, CancellationToken.None); Assert.Equal(expectedName, locationInfo.Name); Assert.Equal(expectedLineOffset, locationInfo.LineOffset); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestClass() => await TestAsync("class G$$oo { }", "Goo", 0); [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668"), WorkItem(538415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538415")] public async Task TestMethod() { await TestAsync( @"class Class { public static void Meth$$od() { } } ", "Class.Method()", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestNamespace() { await TestAsync( @"namespace Namespace { class Class { void Method() { }$$ } }", "Namespace.Class.Method()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(49000, "https://github.com/dotnet/roslyn/issues/49000")] public async Task TestFileScopedNamespace() { // This test behavior is incorrect. This should be Namespace.Class.Method. // See the associated WorkItem for details. await TestAsync( @"namespace Namespace; class Class { void Method() { }$$ } ", "Namespace.Class.Method()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestDottedNamespace() { await TestAsync( @"namespace Namespace.Another { class Class { void Method() { }$$ } }", "Namespace.Another.Class.Method()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestNestedNamespace() { await TestAsync( @"namespace Namespace { namespace Another { class Class { void Method() { }$$ } } }", "Namespace.Another.Class.Method()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestNestedType() { await TestAsync( @"class Outer { class Inner { void Quux() {$$ } } }", "Outer.Inner.Quux()", 1); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestPropertyGetter() { await TestAsync( @"class Class { string Property { get { return null;$$ } } }", "Class.Property", 4); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(527668, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527668")] public async Task TestPropertySetter() { await TestAsync( @"class Class { string Property { get { return null; } set { string s = $$value; } } }", "Class.Property", 9); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(538415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538415")] public async Task TestField() { await TestAsync( @"class Class { int fi$$eld; }", "Class.field", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")] public async Task TestLambdaInFieldInitializer() { await TestAsync( @"class Class { Action<int> a = b => { in$$t c; }; }", "Class.a", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] [WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")] public async Task TestMultipleFields() { await TestAsync( @"class Class { int a1, a$$2; }", "Class.a2", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestConstructor() { await TestAsync( @"class C1 { C1() { $$} } ", "C1.C1()", 3); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestDestructor() { await TestAsync( @"class C1 { ~C1() { $$} } ", "C1.~C1()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestOperator() { await TestAsync( @"namespace N1 { class C1 { public static int operator +(C1 x, C1 y) { $$return 42; } } } ", "N1.C1.+(C1 x, C1 y)", 2); // Old implementation reports "operator +" (rather than "+")... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestConversionOperator() { await TestAsync( @"namespace N1 { class C1 { public static explicit operator N1.C2(N1.C1 x) { $$return null; } } class C2 { } } ", "N1.C1.N1.C2(N1.C1 x)", 2); // Old implementation reports "explicit operator N1.C2" (rather than "N1.C2")... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestEvent() { await TestAsync( @"class C1 { delegate void D1(); event D1 e1$$; } ", "C1.e1", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TextExplicitInterfaceImplementation() { await TestAsync( @"interface I1 { void M1(); } class C1 { void I1.M1() { $$} } ", "C1.M1()", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TextIndexer() { await TestAsync( @"class C1 { C1 this[int x] { get { $$return null; } } } ", "C1.this[int x]", 4); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestParamsParameter() { await TestAsync( @"class C1 { void M1(params int[] x) { $$ } } ", "C1.M1(params int[] x)", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestArglistParameter() { await TestAsync( @"class C1 { void M1(__arglist) { $$ } } ", "C1.M1(__arglist)", 0); // Old implementation does not show "__arglist"... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestRefAndOutParameters() { await TestAsync( @"class C1 { void M1( ref int x, out int y ) { $$y = x; } } ", "C1.M1( ref int x, out int y )", 2); // Old implementation did not show extra spaces around the parameters... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestOptionalParameters() { await TestAsync( @"class C1 { void M1(int x =1) { $$y = x; } } ", "C1.M1(int x =1)", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestExtensionMethod() { await TestAsync( @"static class C1 { static void M1(this int x) { }$$ } ", "C1.M1(this int x)", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestGenericType() { await TestAsync( @"class C1<T, U> { static void M1() { $$ } } ", "C1.M1()", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestGenericMethod() { await TestAsync( @"class C1<T, U> { static void M1<V>() { $$ } } ", "C1.M1()", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestGenericParameters() { await TestAsync( @"class C1<T, U> { static void M1<V>(C1<int, V> x, V y) { $$ } } ", "C1.M1(C1<int, V> x, V y)", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingNamespace() { await TestAsync( @"{ class Class { int a1, a$$2; } }", "Class.a2", 0); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingNamespaceName() { await TestAsync( @"namespace { class C1 { int M1() $${ } } }", "?.C1.M1()", 1); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingClassName() { await TestAsync( @"namespace N1 class { int M1() $${ } } }", "N1.M1()", 1); // Old implementation displayed "N1.?.M1", but we don't see a class declaration in the syntax tree... } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingMethodName() { await TestAsync( @"namespace N1 { class C1 { static void (ref int x) { $$} } }", "N1.C1", 4); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TestMissingParameterList() { await TestAsync( @"namespace N1 { class C1 { static void M1 { $$} } }", "N1.C1.M1", 2); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TopLevelField() { await TestAsync( @"$$int f1; ", "f1", 0, new CSharpParseOptions(kind: SourceCodeKind.Script)); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TopLevelMethod() { await TestAsync( @"int M1(int x) { $$} ", "M1(int x)", 2, new CSharpParseOptions(kind: SourceCodeKind.Script)); } [Fact, Trait(Traits.Feature, Traits.Features.DebuggingLocationName)] public async Task TopLevelStatement() { await TestAsync( @" $$System.Console.WriteLine(""Hello"") ", null, 0, new CSharpParseOptions(kind: SourceCodeKind.Script)); } } }
1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/CodeRefactorings/SyncNamespace/CSharpChangeNamespaceService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ChangeNamespace { [ExportLanguageService(typeof(IChangeNamespaceService), LanguageNames.CSharp), Shared] internal sealed class CSharpChangeNamespaceService : AbstractChangeNamespaceService<NamespaceDeclarationSyntax, CompilationUnitSyntax, MemberDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpChangeNamespaceService() { } protected override async Task<ImmutableArray<(DocumentId, SyntaxNode)>> GetValidContainersFromAllLinkedDocumentsAsync( Document document, SyntaxNode container, CancellationToken cancellationToken) { if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles || document.IsGeneratedCode(cancellationToken)) { return default; } TextSpan containerSpan; if (container is NamespaceDeclarationSyntax) { containerSpan = container.Span; } else if (container is CompilationUnitSyntax) { // A compilation unit as container means user want to move all its members from global to some namespace. // We use an empty span to indicate this case. containerSpan = default; } else { throw ExceptionUtilities.Unreachable; } if (!IsSupportedLinkedDocument(document, out var allDocumentIds)) { return default; } return await TryGetApplicableContainersFromAllDocumentsAsync(document.Project.Solution, allDocumentIds, containerSpan, cancellationToken) .ConfigureAwait(false); } protected override string GetDeclaredNamespace(SyntaxNode container) { if (container is CompilationUnitSyntax) { return string.Empty; } if (container is NamespaceDeclarationSyntax namespaceDecl) { return CSharpSyntaxGenerator.Instance.GetName(namespaceDecl); } throw ExceptionUtilities.Unreachable; } protected override SyntaxList<MemberDeclarationSyntax> GetMemberDeclarationsInContainer(SyntaxNode container) { if (container is NamespaceDeclarationSyntax namespaceDecl) { return namespaceDecl.Members; } if (container is CompilationUnitSyntax compilationUnit) { return compilationUnit.Members; } throw ExceptionUtilities.Unreachable; } /// <summary> /// Try to get a new node to replace given node, which is a reference to a top-level type declared inside the namespace to be changed. /// If this reference is the right side of a qualified name, the new node returned would be the entire qualified name. Depends on /// whether <paramref name="newNamespaceParts"/> is provided, the name in the new node might be qualified with this new namespace instead. /// </summary> /// <param name="reference">A reference to a type declared inside the namespace to be changed, which is calculated based on results from /// `SymbolFinder.FindReferencesAsync`.</param> /// <param name="newNamespaceParts">If specified, and the reference is qualified with namespace, the namespace part of original reference /// will be replaced with given namespace in the new node.</param> /// <param name="oldNode">The node to be replaced. This might be an ancestor of original reference.</param> /// <param name="newNode">The replacement node.</param> public override bool TryGetReplacementReferenceSyntax( SyntaxNode reference, ImmutableArray<string> newNamespaceParts, ISyntaxFactsService syntaxFacts, [NotNullWhen(returnValue: true)] out SyntaxNode? oldNode, [NotNullWhen(returnValue: true)] out SyntaxNode? newNode) { if (!(reference is SimpleNameSyntax nameRef)) { oldNode = newNode = null; return false; } // A few different cases are handled here: // // 1. When the reference is not qualified (i.e. just a simple name), then there's nothing need to be done. // And both old and new will point to the original reference. // // 2. When the new namespace is not specified, we don't need to change the qualified part of reference. // Both old and new will point to the qualified reference. // // 3. When the new namespace is "", i.e. we are moving type referenced by name here to global namespace. // As a result, we need replace qualified reference with the simple name. // // 4. When the namespace is specified and not "", i.e. we are moving referenced type to a different non-global // namespace. We need to replace the qualified reference with a new qualified reference (which is qualified // with new namespace.) // // Note that qualified type name can appear in QualifiedNameSyntax or MemberAccessSyntax, so we need to handle both cases. if (syntaxFacts.IsRightSideOfQualifiedName(nameRef)) { RoslynDebug.Assert(nameRef.Parent is object); oldNode = nameRef.Parent; var aliasQualifier = GetAliasQualifier(oldNode); if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { var qualifiedNamespaceName = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); newNode = SyntaxFactory.QualifiedName(qualifiedNamespaceName, nameRef.WithoutTrivia()); } // We might lose some trivia associated with children of `oldNode`. newNode = newNode.WithTriviaFrom(oldNode); return true; } else if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameRef) || syntaxFacts.IsNameOfMemberBindingExpression(nameRef)) { RoslynDebug.Assert(nameRef.Parent is object); oldNode = nameRef.Parent; var aliasQualifier = GetAliasQualifier(oldNode); if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { var memberAccessNamespaceName = CreateNamespaceAsMemberAccess(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); newNode = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccessNamespaceName, nameRef.WithoutTrivia()); } // We might lose some trivia associated with children of `oldNode`. newNode = newNode.WithTriviaFrom(oldNode); return true; } else if (nameRef.Parent is NameMemberCrefSyntax crefName && crefName.Parent is QualifiedCrefSyntax qualifiedCref) { // This is the case where the reference is the right most part of a qualified name in `cref`. // for example, `<see cref="Foo.Baz.Bar"/>` and `<see cref="SomeAlias::Foo.Baz.Bar"/>`. // This is the form of `cref` we need to handle as a spacial case when changing namespace name or // changing namespace from non-global to global, other cases in these 2 scenarios can be handled in the // same way we handle non cref references, for example, `<see cref="SomeAlias::Foo"/>` and `<see cref="Foo"/>`. var container = qualifiedCref.Container; var aliasQualifier = GetAliasQualifier(container); if (TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { // We will replace entire `QualifiedCrefSyntax` with a `TypeCrefSyntax`, // which is a alias qualified simple name, similar to the regular case above. oldNode = qualifiedCref; newNode = SyntaxFactory.TypeCref((AliasQualifiedNameSyntax)newNode!); } else { // if the new namespace is not global, then we just need to change the container in `QualifiedCrefSyntax`, // which is just a regular namespace node, no cref node involve here. oldNode = container; newNode = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); } return true; } // Simple name reference, nothing to be done. // The name will be resolved by adding proper import. oldNode = newNode = nameRef; return false; } private static bool TryGetGlobalQualifiedName( ImmutableArray<string> newNamespaceParts, SimpleNameSyntax nameNode, string? aliasQualifier, [NotNullWhen(returnValue: true)] out SyntaxNode? newNode) { if (IsGlobalNamespace(newNamespaceParts)) { // If new namespace is "", then name will be declared in global namespace. // We will replace qualified reference with simple name qualified with alias (global if it's not alias qualified) var aliasNode = aliasQualifier?.ToIdentifierName() ?? SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); newNode = SyntaxFactory.AliasQualifiedName(aliasNode, nameNode.WithoutTrivia()); return true; } newNode = null; return false; } /// <summary> /// Try to change the namespace declaration based on the following rules: /// - if neither declared nor target namespace are "" (i.e. global namespace), /// then we try to change the name of the namespace. /// - if declared namespace is "", then we try to move all types declared /// in global namespace in the document into a new namespace declaration. /// - if target namespace is "", then we try to move all members in declared /// namespace to global namespace (i.e. remove the namespace declaration). /// </summary> protected override CompilationUnitSyntax ChangeNamespaceDeclaration( CompilationUnitSyntax root, ImmutableArray<string> declaredNamespaceParts, ImmutableArray<string> targetNamespaceParts) { Debug.Assert(!declaredNamespaceParts.IsDefault && !targetNamespaceParts.IsDefault); var container = root.GetAnnotatedNodes(ContainerAnnotation).Single(); if (container is CompilationUnitSyntax compilationUnit) { // Move everything from global namespace to a namespace declaration Debug.Assert(IsGlobalNamespace(declaredNamespaceParts)); return MoveMembersFromGlobalToNamespace(compilationUnit, targetNamespaceParts); } if (container is NamespaceDeclarationSyntax namespaceDecl) { // Move everything to global namespace if (IsGlobalNamespace(targetNamespaceParts)) { return MoveMembersFromNamespaceToGlobal(root, namespaceDecl); } // Change namespace name return root.ReplaceNode( namespaceDecl, namespaceDecl.WithName( CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1) .WithTriviaFrom(namespaceDecl.Name).WithAdditionalAnnotations(WarningAnnotation)) .WithoutAnnotations(ContainerAnnotation)); // Make sure to remove the annotation we added } throw ExceptionUtilities.Unreachable; } private static CompilationUnitSyntax MoveMembersFromNamespaceToGlobal(CompilationUnitSyntax root, NamespaceDeclarationSyntax namespaceDecl) { var (namespaceOpeningTrivia, namespaceClosingTrivia) = GetOpeningAndClosingTriviaOfNamespaceDeclaration(namespaceDecl); var members = namespaceDecl.Members; var eofToken = root.EndOfFileToken .WithAdditionalAnnotations(WarningAnnotation); // Try to preserve trivia from original namespace declaration. // If there's any member inside the declaration, we attach them to the // first and last member, otherwise, simply attach all to the EOF token. if (members.Count > 0) { var first = members.First(); var firstWithTrivia = first.WithPrependedLeadingTrivia(namespaceOpeningTrivia); members = members.Replace(first, firstWithTrivia); var last = members.Last(); var lastWithTrivia = last.WithAppendedTrailingTrivia(namespaceClosingTrivia); members = members.Replace(last, lastWithTrivia); } else { eofToken = eofToken.WithPrependedLeadingTrivia( namespaceOpeningTrivia.Concat(namespaceClosingTrivia)); } // Moving inner imports out of the namespace declaration can lead to a break in semantics. // For example: // // namespace A.B.C // { // using D.E.F; // } // // The using of D.E.F is looked up with in the context of A.B.C first. If it's moved outside, // it may fail to resolve. return root.Update( root.Externs.AddRange(namespaceDecl.Externs), root.Usings.AddRange(namespaceDecl.Usings), root.AttributeLists, root.Members.ReplaceRange(namespaceDecl, members), eofToken); } private static CompilationUnitSyntax MoveMembersFromGlobalToNamespace(CompilationUnitSyntax compilationUnit, ImmutableArray<string> targetNamespaceParts) { Debug.Assert(!compilationUnit.Members.Any(m => m is NamespaceDeclarationSyntax)); var targetNamespaceDecl = SyntaxFactory.NamespaceDeclaration( name: CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1) .WithAdditionalAnnotations(WarningAnnotation), externs: default, usings: default, members: compilationUnit.Members); return compilationUnit.WithMembers(new SyntaxList<MemberDeclarationSyntax>(targetNamespaceDecl)) .WithoutAnnotations(ContainerAnnotation); // Make sure to remove the annotation we added } /// <summary> /// For the node specified by <paramref name="span"/> to be applicable container, it must be a namespace /// declaration or a compilation unit, contain no partial declarations and meet the following additional /// requirements: /// /// - If a namespace declaration: /// 1. It doesn't contain or is nested in other namespace declarations /// 2. The name of the namespace is valid (i.e. no errors) /// /// - If a compilation unit (i.e. <paramref name="span"/> is empty), there must be no namespace declaration /// inside (i.e. all members are declared in global namespace) /// </summary> protected override async Task<SyntaxNode?> TryGetApplicableContainerFromSpanAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(syntaxRoot); var compilationUnit = (CompilationUnitSyntax)syntaxRoot; SyntaxNode? container = null; // Empty span means that user wants to move all types declared in the document to a new namespace. // This action is only supported when everything in the document is declared in global namespace, // which we use the number of namespace declaration nodes to decide. if (span.IsEmpty) { if (ContainsNamespaceDeclaration(compilationUnit)) { return null; } container = compilationUnit; } else { // Otherwise, the span should contain a namespace declaration node, which must be the only one // in the entire syntax spine to enable the change namespace operation. if (!compilationUnit.Span.Contains(span)) { return null; } var node = compilationUnit.FindNode(span, getInnermostNodeForTie: true); var namespaceDecl = node.AncestorsAndSelf().OfType<NamespaceDeclarationSyntax>().SingleOrDefault(); if (namespaceDecl == null) { return null; } if (namespaceDecl.Name.GetDiagnostics().Any(diag => diag.DefaultSeverity == DiagnosticSeverity.Error)) { return null; } if (ContainsNamespaceDeclaration(node)) { return null; } container = namespaceDecl; } var containsPartial = await ContainsPartialTypeWithMultipleDeclarationsAsync(document, container, cancellationToken).ConfigureAwait(false); if (containsPartial) { return null; } return container; static bool ContainsNamespaceDeclaration(SyntaxNode node) => node.DescendantNodes(n => n is CompilationUnitSyntax || n is NamespaceDeclarationSyntax) .OfType<NamespaceDeclarationSyntax>().Any(); } private static string? GetAliasQualifier(SyntaxNode? name) { while (true) { switch (name) { case QualifiedNameSyntax qualifiedNameNode: name = qualifiedNameNode.Left; continue; case MemberAccessExpressionSyntax memberAccessNode: name = memberAccessNode.Expression; continue; case AliasQualifiedNameSyntax aliasQualifiedNameNode: return aliasQualifiedNameNode.Alias.Identifier.ValueText; } return null; } } private static NameSyntax CreateNamespaceAsQualifiedName(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index) { var part = namespaceParts[index].EscapeIdentifier(); Debug.Assert(part.Length > 0); var namePiece = SyntaxFactory.IdentifierName(part); if (index == 0) { return aliasQualifier == null ? (NameSyntax)namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece); } return SyntaxFactory.QualifiedName(CreateNamespaceAsQualifiedName(namespaceParts, aliasQualifier, index - 1), namePiece); } private static ExpressionSyntax CreateNamespaceAsMemberAccess(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index) { var part = namespaceParts[index].EscapeIdentifier(); Debug.Assert(part.Length > 0); var namePiece = SyntaxFactory.IdentifierName(part); if (index == 0) { return aliasQualifier == null ? (NameSyntax)namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece); } return SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, CreateNamespaceAsMemberAccess(namespaceParts, aliasQualifier, index - 1), namePiece); } /// <summary> /// return trivia attached to namespace declaration. /// Leading trivia of the node and trivia around opening brace, as well as /// trivia around closing brace are concatenated together respectively. /// </summary> private static (ImmutableArray<SyntaxTrivia> openingTrivia, ImmutableArray<SyntaxTrivia> closingTrivia) GetOpeningAndClosingTriviaOfNamespaceDeclaration(NamespaceDeclarationSyntax namespaceDeclaration) { var openingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance(); openingBuilder.AddRange(namespaceDeclaration.GetLeadingTrivia()); openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.LeadingTrivia); openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.TrailingTrivia); var closingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance(); closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.LeadingTrivia); closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.TrailingTrivia); return (openingBuilder.ToImmutableAndFree(), closingBuilder.ToImmutableAndFree()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ChangeNamespace { [ExportLanguageService(typeof(IChangeNamespaceService), LanguageNames.CSharp), Shared] internal sealed class CSharpChangeNamespaceService : AbstractChangeNamespaceService<BaseNamespaceDeclarationSyntax, CompilationUnitSyntax, MemberDeclarationSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpChangeNamespaceService() { } protected override async Task<ImmutableArray<(DocumentId, SyntaxNode)>> GetValidContainersFromAllLinkedDocumentsAsync( Document document, SyntaxNode container, CancellationToken cancellationToken) { if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles || document.IsGeneratedCode(cancellationToken)) { return default; } TextSpan containerSpan; if (container is BaseNamespaceDeclarationSyntax) { containerSpan = container.Span; } else if (container is CompilationUnitSyntax) { // A compilation unit as container means user want to move all its members from global to some namespace. // We use an empty span to indicate this case. containerSpan = default; } else { throw ExceptionUtilities.Unreachable; } if (!IsSupportedLinkedDocument(document, out var allDocumentIds)) return default; return await TryGetApplicableContainersFromAllDocumentsAsync( document.Project.Solution, allDocumentIds, containerSpan, cancellationToken).ConfigureAwait(false); } protected override string GetDeclaredNamespace(SyntaxNode container) { if (container is CompilationUnitSyntax) return string.Empty; if (container is BaseNamespaceDeclarationSyntax namespaceDecl) return CSharpSyntaxGenerator.Instance.GetName(namespaceDecl); throw ExceptionUtilities.Unreachable; } protected override SyntaxList<MemberDeclarationSyntax> GetMemberDeclarationsInContainer(SyntaxNode container) { if (container is BaseNamespaceDeclarationSyntax namespaceDecl) return namespaceDecl.Members; if (container is CompilationUnitSyntax compilationUnit) return compilationUnit.Members; throw ExceptionUtilities.Unreachable; } /// <summary> /// Try to get a new node to replace given node, which is a reference to a top-level type declared inside the namespace to be changed. /// If this reference is the right side of a qualified name, the new node returned would be the entire qualified name. Depends on /// whether <paramref name="newNamespaceParts"/> is provided, the name in the new node might be qualified with this new namespace instead. /// </summary> /// <param name="reference">A reference to a type declared inside the namespace to be changed, which is calculated based on results from /// `SymbolFinder.FindReferencesAsync`.</param> /// <param name="newNamespaceParts">If specified, and the reference is qualified with namespace, the namespace part of original reference /// will be replaced with given namespace in the new node.</param> /// <param name="oldNode">The node to be replaced. This might be an ancestor of original reference.</param> /// <param name="newNode">The replacement node.</param> public override bool TryGetReplacementReferenceSyntax( SyntaxNode reference, ImmutableArray<string> newNamespaceParts, ISyntaxFactsService syntaxFacts, [NotNullWhen(returnValue: true)] out SyntaxNode? oldNode, [NotNullWhen(returnValue: true)] out SyntaxNode? newNode) { if (reference is not SimpleNameSyntax nameRef) { oldNode = newNode = null; return false; } // A few different cases are handled here: // // 1. When the reference is not qualified (i.e. just a simple name), then there's nothing need to be done. // And both old and new will point to the original reference. // // 2. When the new namespace is not specified, we don't need to change the qualified part of reference. // Both old and new will point to the qualified reference. // // 3. When the new namespace is "", i.e. we are moving type referenced by name here to global namespace. // As a result, we need replace qualified reference with the simple name. // // 4. When the namespace is specified and not "", i.e. we are moving referenced type to a different non-global // namespace. We need to replace the qualified reference with a new qualified reference (which is qualified // with new namespace.) // // Note that qualified type name can appear in QualifiedNameSyntax or MemberAccessSyntax, so we need to handle both cases. if (syntaxFacts.IsRightSideOfQualifiedName(nameRef)) { RoslynDebug.Assert(nameRef.Parent is object); oldNode = nameRef.Parent; var aliasQualifier = GetAliasQualifier(oldNode); if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { var qualifiedNamespaceName = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); newNode = SyntaxFactory.QualifiedName(qualifiedNamespaceName, nameRef.WithoutTrivia()); } // We might lose some trivia associated with children of `oldNode`. newNode = newNode.WithTriviaFrom(oldNode); return true; } else if (syntaxFacts.IsNameOfSimpleMemberAccessExpression(nameRef) || syntaxFacts.IsNameOfMemberBindingExpression(nameRef)) { RoslynDebug.Assert(nameRef.Parent is object); oldNode = nameRef.Parent; var aliasQualifier = GetAliasQualifier(oldNode); if (!TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { var memberAccessNamespaceName = CreateNamespaceAsMemberAccess(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); newNode = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, memberAccessNamespaceName, nameRef.WithoutTrivia()); } // We might lose some trivia associated with children of `oldNode`. newNode = newNode.WithTriviaFrom(oldNode); return true; } else if (nameRef.Parent is NameMemberCrefSyntax crefName && crefName.Parent is QualifiedCrefSyntax qualifiedCref) { // This is the case where the reference is the right most part of a qualified name in `cref`. // for example, `<see cref="Foo.Baz.Bar"/>` and `<see cref="SomeAlias::Foo.Baz.Bar"/>`. // This is the form of `cref` we need to handle as a spacial case when changing namespace name or // changing namespace from non-global to global, other cases in these 2 scenarios can be handled in the // same way we handle non cref references, for example, `<see cref="SomeAlias::Foo"/>` and `<see cref="Foo"/>`. var container = qualifiedCref.Container; var aliasQualifier = GetAliasQualifier(container); if (TryGetGlobalQualifiedName(newNamespaceParts, nameRef, aliasQualifier, out newNode)) { // We will replace entire `QualifiedCrefSyntax` with a `TypeCrefSyntax`, // which is a alias qualified simple name, similar to the regular case above. oldNode = qualifiedCref; newNode = SyntaxFactory.TypeCref((AliasQualifiedNameSyntax)newNode!); } else { // if the new namespace is not global, then we just need to change the container in `QualifiedCrefSyntax`, // which is just a regular namespace node, no cref node involve here. oldNode = container; newNode = CreateNamespaceAsQualifiedName(newNamespaceParts, aliasQualifier, newNamespaceParts.Length - 1); } return true; } // Simple name reference, nothing to be done. // The name will be resolved by adding proper import. oldNode = newNode = nameRef; return false; } private static bool TryGetGlobalQualifiedName( ImmutableArray<string> newNamespaceParts, SimpleNameSyntax nameNode, string? aliasQualifier, [NotNullWhen(returnValue: true)] out SyntaxNode? newNode) { if (IsGlobalNamespace(newNamespaceParts)) { // If new namespace is "", then name will be declared in global namespace. // We will replace qualified reference with simple name qualified with alias (global if it's not alias qualified) var aliasNode = aliasQualifier?.ToIdentifierName() ?? SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); newNode = SyntaxFactory.AliasQualifiedName(aliasNode, nameNode.WithoutTrivia()); return true; } newNode = null; return false; } /// <summary> /// Try to change the namespace declaration based on the following rules: /// - if neither declared nor target namespace are "" (i.e. global namespace), /// then we try to change the name of the namespace. /// - if declared namespace is "", then we try to move all types declared /// in global namespace in the document into a new namespace declaration. /// - if target namespace is "", then we try to move all members in declared /// namespace to global namespace (i.e. remove the namespace declaration). /// </summary> protected override CompilationUnitSyntax ChangeNamespaceDeclaration( CompilationUnitSyntax root, ImmutableArray<string> declaredNamespaceParts, ImmutableArray<string> targetNamespaceParts) { Debug.Assert(!declaredNamespaceParts.IsDefault && !targetNamespaceParts.IsDefault); var container = root.GetAnnotatedNodes(ContainerAnnotation).Single(); if (container is CompilationUnitSyntax compilationUnit) { // Move everything from global namespace to a namespace declaration Debug.Assert(IsGlobalNamespace(declaredNamespaceParts)); return MoveMembersFromGlobalToNamespace(compilationUnit, targetNamespaceParts); } if (container is BaseNamespaceDeclarationSyntax namespaceDecl) { // Move everything to global namespace if (IsGlobalNamespace(targetNamespaceParts)) return MoveMembersFromNamespaceToGlobal(root, namespaceDecl); // Change namespace name return root.ReplaceNode( namespaceDecl, namespaceDecl.WithName( CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1) .WithTriviaFrom(namespaceDecl.Name).WithAdditionalAnnotations(WarningAnnotation)) .WithoutAnnotations(ContainerAnnotation)); // Make sure to remove the annotation we added } throw ExceptionUtilities.Unreachable; } private static CompilationUnitSyntax MoveMembersFromNamespaceToGlobal( CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax namespaceDecl) { var (namespaceOpeningTrivia, namespaceClosingTrivia) = GetOpeningAndClosingTriviaOfNamespaceDeclaration(namespaceDecl); var members = namespaceDecl.Members; var eofToken = root.EndOfFileToken .WithAdditionalAnnotations(WarningAnnotation); // Try to preserve trivia from original namespace declaration. // If there's any member inside the declaration, we attach them to the // first and last member, otherwise, simply attach all to the EOF token. if (members.Count > 0) { var first = members.First(); var firstWithTrivia = first.WithPrependedLeadingTrivia(namespaceOpeningTrivia); members = members.Replace(first, firstWithTrivia); var last = members.Last(); var lastWithTrivia = last.WithAppendedTrailingTrivia(namespaceClosingTrivia); members = members.Replace(last, lastWithTrivia); } else { eofToken = eofToken.WithPrependedLeadingTrivia( namespaceOpeningTrivia.Concat(namespaceClosingTrivia)); } // Moving inner imports out of the namespace declaration can lead to a break in semantics. // For example: // // namespace A.B.C // { // using D.E.F; // } // // The using of D.E.F is looked up with in the context of A.B.C first. If it's moved outside, // it may fail to resolve. return root.Update( root.Externs.AddRange(namespaceDecl.Externs), root.Usings.AddRange(namespaceDecl.Usings), root.AttributeLists, root.Members.ReplaceRange(namespaceDecl, members), eofToken); } private static CompilationUnitSyntax MoveMembersFromGlobalToNamespace(CompilationUnitSyntax compilationUnit, ImmutableArray<string> targetNamespaceParts) { Debug.Assert(!compilationUnit.Members.Any(m => m is BaseNamespaceDeclarationSyntax)); var targetNamespaceDecl = SyntaxFactory.NamespaceDeclaration( name: CreateNamespaceAsQualifiedName(targetNamespaceParts, aliasQualifier: null, targetNamespaceParts.Length - 1) .WithAdditionalAnnotations(WarningAnnotation), externs: default, usings: default, members: compilationUnit.Members); return compilationUnit.WithMembers(new SyntaxList<MemberDeclarationSyntax>(targetNamespaceDecl)) .WithoutAnnotations(ContainerAnnotation); // Make sure to remove the annotation we added } /// <summary> /// For the node specified by <paramref name="span"/> to be applicable container, it must be a namespace /// declaration or a compilation unit, contain no partial declarations and meet the following additional /// requirements: /// /// - If a namespace declaration: /// 1. It doesn't contain or is nested in other namespace declarations /// 2. The name of the namespace is valid (i.e. no errors) /// /// - If a compilation unit (i.e. <paramref name="span"/> is empty), there must be no namespace declaration /// inside (i.e. all members are declared in global namespace) /// </summary> protected override async Task<SyntaxNode?> TryGetApplicableContainerFromSpanAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(syntaxRoot); var compilationUnit = (CompilationUnitSyntax)syntaxRoot; SyntaxNode? container = null; // Empty span means that user wants to move all types declared in the document to a new namespace. // This action is only supported when everything in the document is declared in global namespace, // which we use the number of namespace declaration nodes to decide. if (span.IsEmpty) { if (ContainsNamespaceDeclaration(compilationUnit)) return null; container = compilationUnit; } else { // Otherwise, the span should contain a namespace declaration node, which must be the only one // in the entire syntax spine to enable the change namespace operation. if (!compilationUnit.Span.Contains(span)) return null; var node = compilationUnit.FindNode(span, getInnermostNodeForTie: true); var namespaceDecl = node.AncestorsAndSelf().OfType<BaseNamespaceDeclarationSyntax>().SingleOrDefault(); if (namespaceDecl == null) return null; if (namespaceDecl.Name.GetDiagnostics().Any(diag => diag.DefaultSeverity == DiagnosticSeverity.Error)) return null; if (ContainsNamespaceDeclaration(node)) return null; container = namespaceDecl; } var containsPartial = await ContainsPartialTypeWithMultipleDeclarationsAsync(document, container, cancellationToken).ConfigureAwait(false); if (containsPartial) return null; return container; static bool ContainsNamespaceDeclaration(SyntaxNode node) => node.DescendantNodes(n => n is CompilationUnitSyntax || n is BaseNamespaceDeclarationSyntax) .OfType<BaseNamespaceDeclarationSyntax>().Any(); } private static string? GetAliasQualifier(SyntaxNode? name) { while (true) { switch (name) { case QualifiedNameSyntax qualifiedNameNode: name = qualifiedNameNode.Left; continue; case MemberAccessExpressionSyntax memberAccessNode: name = memberAccessNode.Expression; continue; case AliasQualifiedNameSyntax aliasQualifiedNameNode: return aliasQualifiedNameNode.Alias.Identifier.ValueText; } return null; } } private static NameSyntax CreateNamespaceAsQualifiedName(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index) { var part = namespaceParts[index].EscapeIdentifier(); Debug.Assert(part.Length > 0); var namePiece = SyntaxFactory.IdentifierName(part); if (index == 0) return aliasQualifier == null ? namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece); return SyntaxFactory.QualifiedName(CreateNamespaceAsQualifiedName(namespaceParts, aliasQualifier, index - 1), namePiece); } private static ExpressionSyntax CreateNamespaceAsMemberAccess(ImmutableArray<string> namespaceParts, string? aliasQualifier, int index) { var part = namespaceParts[index].EscapeIdentifier(); Debug.Assert(part.Length > 0); var namePiece = SyntaxFactory.IdentifierName(part); if (index == 0) { return aliasQualifier == null ? (NameSyntax)namePiece : SyntaxFactory.AliasQualifiedName(aliasQualifier, namePiece); } return SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, CreateNamespaceAsMemberAccess(namespaceParts, aliasQualifier, index - 1), namePiece); } /// <summary> /// return trivia attached to namespace declaration. /// Leading trivia of the node and trivia around opening brace, as well as /// trivia around closing brace are concatenated together respectively. /// </summary> private static (ImmutableArray<SyntaxTrivia> openingTrivia, ImmutableArray<SyntaxTrivia> closingTrivia) GetOpeningAndClosingTriviaOfNamespaceDeclaration(BaseNamespaceDeclarationSyntax baseNamespace) { var openingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance(); var closingBuilder = ArrayBuilder<SyntaxTrivia>.GetInstance(); openingBuilder.AddRange(baseNamespace.GetLeadingTrivia()); if (baseNamespace is NamespaceDeclarationSyntax namespaceDeclaration) { openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.LeadingTrivia); openingBuilder.AddRange(namespaceDeclaration.OpenBraceToken.TrailingTrivia); closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.LeadingTrivia); closingBuilder.AddRange(namespaceDeclaration.CloseBraceToken.TrailingTrivia); } else if (baseNamespace is FileScopedNamespaceDeclarationSyntax fileScopedNamespace) { openingBuilder.AddRange(fileScopedNamespace.SemicolonToken.TrailingTrivia); } return (openingBuilder.ToImmutableAndFree(), closingBuilder.ToImmutableAndFree()); } } }
1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Services/SyntaxFacts/CSharpSyntaxFacts.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.CSharp.LanguageServices { internal class CSharpSyntaxFacts : AbstractSyntaxFacts, ISyntaxFacts { internal static readonly CSharpSyntaxFacts Instance = new(); protected CSharpSyntaxFacts() { } public bool IsCaseSensitive => true; public StringComparer StringComparer { get; } = StringComparer.Ordinal; public SyntaxTrivia ElasticMarker => SyntaxFactory.ElasticMarker; public SyntaxTrivia ElasticCarriageReturnLineFeed => SyntaxFactory.ElasticCarriageReturnLineFeed; public override ISyntaxKinds SyntaxKinds { get; } = CSharpSyntaxKinds.Instance; protected override IDocumentationCommentService DocumentationCommentService => CSharpDocumentationCommentService.Instance; public bool SupportsIndexingInitializer(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6; public bool SupportsThrowExpression(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsLocalFunctionDeclaration(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsRecord(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp9; public bool SupportsRecordStruct(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp10OrAbove(); public SyntaxToken ParseToken(string text) => SyntaxFactory.ParseToken(text); public SyntaxTriviaList ParseLeadingTrivia(string text) => SyntaxFactory.ParseLeadingTrivia(text); public string EscapeIdentifier(string identifier) { var nullIndex = identifier.IndexOf('\0'); if (nullIndex >= 0) { identifier = identifier.Substring(0, nullIndex); } var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None; return needsEscaping ? "@" + identifier : identifier; } public bool IsVerbatimIdentifier(SyntaxToken token) => token.IsVerbatimIdentifier(); public bool IsOperator(SyntaxToken token) { var kind = token.Kind(); return (SyntaxFacts.IsAnyUnaryExpression(kind) && (token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax); } public bool IsReservedKeyword(SyntaxToken token) => SyntaxFacts.IsReservedKeyword(token.Kind()); public bool IsContextualKeyword(SyntaxToken token) => SyntaxFacts.IsContextualKeyword(token.Kind()); public bool IsPreprocessorKeyword(SyntaxToken token) => SyntaxFacts.IsPreprocessorKeyword(token.Kind()); public bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) => syntaxTree.IsPreProcessorDirectiveContext( position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken); public bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree == null) { return false; } return syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken); } public bool IsDirective([NotNullWhen(true)] SyntaxNode? node) => node is DirectiveTriviaSyntax; public bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? node, out ExternalSourceInfo info) { if (node is LineDirectiveTriviaSyntax lineDirective) { if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword) { info = new ExternalSourceInfo(null, ends: true); return true; } else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken && lineDirective.Line.Value is int) { info = new ExternalSourceInfo((int)lineDirective.Line.Value, false); return true; } } info = default; return false; } public bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsRightSideOfQualifiedName(); } public bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsSimpleMemberAccessExpressionName(); } public bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == node; public bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsMemberBindingExpressionName(); } [return: NotNullIfNotNull("node")] public SyntaxNode? GetStandaloneExpression(SyntaxNode? node) => node is ExpressionSyntax expression ? SyntaxFactory.GetStandaloneExpression(expression) : node; public SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node) => node.GetRootConditionalAccessExpression(); public bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.ObjectCreationExpression, out ObjectCreationExpressionSyntax? objectCreation) && objectCreation.Type == node; public bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node) => node is DeclarationExpressionSyntax; public bool IsAttributeName(SyntaxNode node) => SyntaxFacts.IsAttributeName(node); public bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? node) { return node is ParenthesizedLambdaExpressionSyntax || node is SimpleLambdaExpressionSyntax || node is AnonymousMethodExpressionSyntax; } public bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node is ArgumentSyntax arg && arg.NameColon != null; public bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node.CheckParent<NameColonSyntax>(p => p.Name == node); public SyntaxToken? GetNameOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Identifier; public SyntaxNode? GetDefaultOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Default; public SyntaxNode? GetParameterList(SyntaxNode node) => node.GetParameterList(); public bool IsParameterList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList); public SyntaxToken GetIdentifierOfGenericName(SyntaxNode? genericName) { return genericName is GenericNameSyntax csharpGenericName ? csharpGenericName.Identifier : default; } public bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax? usingDirective) && usingDirective.Name == node; public bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node) => node is UsingDirectiveSyntax usingDirectiveNode && usingDirectiveNode.Alias != null; public bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node) => node is ForEachVariableStatementSyntax; public bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node) => node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction(); public Location GetDeconstructionReferenceLocation(SyntaxNode node) { return node switch { AssignmentExpressionSyntax assignment => assignment.Left.GetLocation(), ForEachVariableStatementSyntax @foreach => @foreach.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }; } public bool IsStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node) { if (node is BlockSyntax || node is ArrowExpressionClauseSyntax) { return node.Parent is BaseMethodDeclarationSyntax || node.Parent is AccessorDeclarationSyntax; } return false; } public SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node) => (node as ReturnStatementSyntax)?.Expression; public bool IsThisConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsBaseConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsQueryKeyword(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.FromKeyword: case SyntaxKind.JoinKeyword: case SyntaxKind.LetKeyword: case SyntaxKind.OrderByKeyword: case SyntaxKind.WhereKeyword: case SyntaxKind.OnKeyword: case SyntaxKind.EqualsKeyword: case SyntaxKind.InKeyword: return token.Parent is QueryClauseSyntax; case SyntaxKind.ByKeyword: case SyntaxKind.GroupKeyword: case SyntaxKind.SelectKeyword: return token.Parent is SelectOrGroupClauseSyntax; case SyntaxKind.AscendingKeyword: case SyntaxKind.DescendingKeyword: return token.Parent is OrderingSyntax; case SyntaxKind.IntoKeyword: return token.Parent.IsKind(SyntaxKind.JoinIntoClause, SyntaxKind.QueryContinuation); default: return false; } } public bool IsThrowExpression(SyntaxNode node) => node.Kind() == SyntaxKind.ThrowExpression; public bool IsPredefinedType(SyntaxToken token) => TryGetPredefinedType(token, out _); public bool IsPredefinedType(SyntaxToken token, PredefinedType type) => TryGetPredefinedType(token, out var actualType) && actualType == type; public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type) { type = GetPredefinedType(token); return type != PredefinedType.None; } private static PredefinedType GetPredefinedType(SyntaxToken token) { return (SyntaxKind)token.RawKind switch { SyntaxKind.BoolKeyword => PredefinedType.Boolean, SyntaxKind.ByteKeyword => PredefinedType.Byte, SyntaxKind.SByteKeyword => PredefinedType.SByte, SyntaxKind.IntKeyword => PredefinedType.Int32, SyntaxKind.UIntKeyword => PredefinedType.UInt32, SyntaxKind.ShortKeyword => PredefinedType.Int16, SyntaxKind.UShortKeyword => PredefinedType.UInt16, SyntaxKind.LongKeyword => PredefinedType.Int64, SyntaxKind.ULongKeyword => PredefinedType.UInt64, SyntaxKind.FloatKeyword => PredefinedType.Single, SyntaxKind.DoubleKeyword => PredefinedType.Double, SyntaxKind.DecimalKeyword => PredefinedType.Decimal, SyntaxKind.StringKeyword => PredefinedType.String, SyntaxKind.CharKeyword => PredefinedType.Char, SyntaxKind.ObjectKeyword => PredefinedType.Object, SyntaxKind.VoidKeyword => PredefinedType.Void, _ => PredefinedType.None, }; } public bool IsPredefinedOperator(SyntaxToken token) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator != PredefinedOperator.None; public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op; public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op) { op = GetPredefinedOperator(token); return op != PredefinedOperator.None; } private static PredefinedOperator GetPredefinedOperator(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: return PredefinedOperator.Addition; case SyntaxKind.MinusToken: case SyntaxKind.MinusEqualsToken: return PredefinedOperator.Subtraction; case SyntaxKind.AmpersandToken: case SyntaxKind.AmpersandEqualsToken: return PredefinedOperator.BitwiseAnd; case SyntaxKind.BarToken: case SyntaxKind.BarEqualsToken: return PredefinedOperator.BitwiseOr; case SyntaxKind.MinusMinusToken: return PredefinedOperator.Decrement; case SyntaxKind.PlusPlusToken: return PredefinedOperator.Increment; case SyntaxKind.SlashToken: case SyntaxKind.SlashEqualsToken: return PredefinedOperator.Division; case SyntaxKind.EqualsEqualsToken: return PredefinedOperator.Equality; case SyntaxKind.CaretToken: case SyntaxKind.CaretEqualsToken: return PredefinedOperator.ExclusiveOr; case SyntaxKind.GreaterThanToken: return PredefinedOperator.GreaterThan; case SyntaxKind.GreaterThanEqualsToken: return PredefinedOperator.GreaterThanOrEqual; case SyntaxKind.ExclamationEqualsToken: return PredefinedOperator.Inequality; case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: return PredefinedOperator.LeftShift; case SyntaxKind.LessThanToken: return PredefinedOperator.LessThan; case SyntaxKind.LessThanEqualsToken: return PredefinedOperator.LessThanOrEqual; case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: return PredefinedOperator.Multiplication; case SyntaxKind.PercentToken: case SyntaxKind.PercentEqualsToken: return PredefinedOperator.Modulus; case SyntaxKind.ExclamationToken: case SyntaxKind.TildeToken: return PredefinedOperator.Complement; case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: return PredefinedOperator.RightShift; } return PredefinedOperator.None; } public string GetText(int kind) => SyntaxFacts.GetText((SyntaxKind)kind); public bool IsIdentifierStartCharacter(char c) => SyntaxFacts.IsIdentifierStartCharacter(c); public bool IsIdentifierPartCharacter(char c) => SyntaxFacts.IsIdentifierPartCharacter(c); public bool IsIdentifierEscapeCharacter(char c) => c == '@'; public bool IsValidIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length; } public bool IsVerbatimIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier(); } public bool IsTypeCharacter(char c) => false; public bool IsStartOfUnicodeEscapeSequence(char c) => c == '\\'; public bool IsLiteral(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.NumericLiteralToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringEndToken: case SyntaxKind.InterpolatedVerbatimStringStartToken: case SyntaxKind.InterpolatedStringTextToken: return true; default: return false; } } public bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken); public bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node?.IsKind(SyntaxKind.NumericLiteralExpression) == true; public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent) { var typedToken = token; var typedParent = parent; if (typedParent.IsKind(SyntaxKind.IdentifierName)) { TypeSyntax? declaredType = null; if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax? varDecl)) { declaredType = varDecl.Type; } else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration, out FieldDeclarationSyntax? fieldDecl)) { declaredType = fieldDecl.Declaration.Type; } return declaredType == typedParent && typedToken.ValueText == "var"; } return false; } public bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent) { if (parent is ExpressionSyntax typedParent) { if (SyntaxFacts.IsInTypeOnlyContext(typedParent) && typedParent.IsKind(SyntaxKind.IdentifierName) && token.ValueText == "dynamic") { return true; } } return false; } public bool IsBindableToken(SyntaxToken token) { if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token)) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.DelegateKeyword: case SyntaxKind.VoidKeyword: return false; } return true; } // In the order by clause a comma might be bound to ThenBy or ThenByDescending if (token.Kind() == SyntaxKind.CommaToken && token.Parent.IsKind(SyntaxKind.OrderByClause)) { return true; } return false; } public void GetPartsOfConditionalAccessExpression( SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull) { var conditionalAccess = (ConditionalAccessExpressionSyntax)node; expression = conditionalAccess.Expression; operatorToken = conditionalAccess.OperatorToken; whenNotNull = conditionalAccess.WhenNotNull; } public bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is PostfixUnaryExpressionSyntax; public bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) => node is MemberBindingExpressionSyntax; public bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node as MemberAccessExpressionSyntax)?.Kind() == SyntaxKind.PointerMemberAccessExpression; public void GetNameAndArityOfSimpleName(SyntaxNode? node, out string? name, out int arity) { name = null; arity = 0; if (node is SimpleNameSyntax simpleName) { name = simpleName.Identifier.ValueText; arity = simpleName.Arity; } } public bool LooksGeneric(SyntaxNode simpleName) => simpleName.IsKind(SyntaxKind.GenericName) || simpleName.GetLastToken().GetNextToken().Kind() == SyntaxKind.LessThanToken; public SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node) => (node as MemberBindingExpressionSyntax).GetParentConditionalAccessExpression()?.Expression; public SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node) => ((MemberBindingExpressionSyntax)node).Name; public SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget) => (node as MemberAccessExpressionSyntax)?.Expression; public void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList) { var elementAccess = node as ElementAccessExpressionSyntax; expression = elementAccess?.Expression; argumentList = elementAccess?.ArgumentList; } public SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node) => (node as InterpolationSyntax)?.Expression; public bool IsInStaticContext(SyntaxNode node) => node.IsInStaticContext(); public bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node) => SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); public bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.BaseList); public SyntaxNode? GetExpressionOfArgument(SyntaxNode? node) => (node as ArgumentSyntax)?.Expression; public RefKind GetRefKindOfArgument(SyntaxNode? node) => (node as ArgumentSyntax).GetRefKind(); public bool IsArgument([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Argument); public bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node) { return node is ArgumentSyntax argument && argument.RefOrOutKeyword.Kind() == SyntaxKind.None && argument.NameColon == null; } public bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsInConstantContext(); public bool IsInConstructor(SyntaxNode node) => node.GetAncestor<ConstructorDeclarationSyntax>() != null; public bool IsUnsafeContext(SyntaxNode node) => node.IsUnsafeContext(); public SyntaxNode GetNameOfAttribute(SyntaxNode node) => ((AttributeSyntax)node).Name; public SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node) => ((ParenthesizedExpressionSyntax)node).Expression; public bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node) => (node as IdentifierNameSyntax).IsAttributeNamedArgumentIdentifier(); public SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position) { if (root == null) { throw new ArgumentNullException(nameof(root)); } if (position < 0 || position > root.Span.End) { throw new ArgumentOutOfRangeException(nameof(position)); } return root .FindToken(position) .GetAncestors<SyntaxNode>() .FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax); } public SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node) => throw ExceptionUtilities.Unreachable; public SyntaxToken FindTokenOnLeftOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public SyntaxToken FindTokenOnRightOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IdentifierName) && node.IsParentKind(SyntaxKind.NameColon) && node.Parent.IsParentKind(SyntaxKind.Subpattern); public bool IsPropertyPatternClause(SyntaxNode node) => node.Kind() == SyntaxKind.PropertyPatternClause; public bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node) => IsMemberInitializerNamedAssignmentIdentifier(node, out _); public bool IsMemberInitializerNamedAssignmentIdentifier( [NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance) { initializedInstance = null; if (node is IdentifierNameSyntax identifier && identifier.IsLeftSideOfAssignExpression()) { if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression)) { var withInitializer = identifier.Parent.GetRequiredParent(); initializedInstance = withInitializer.GetRequiredParent(); return true; } else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression)) { var objectInitializer = identifier.Parent.GetRequiredParent(); if (objectInitializer.Parent is BaseObjectCreationExpressionSyntax) { initializedInstance = objectInitializer.Parent; return true; } else if (objectInitializer.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment)) { initializedInstance = assignment.Left; return true; } } } return false; } public bool IsElementAccessExpression(SyntaxNode? node) => node.IsKind(SyntaxKind.ElementAccessExpression); [return: NotNullIfNotNull("node")] public SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false) => node.ConvertToSingleLine(useElasticTrivia); public void GetPartsOfParenthesizedExpression( SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen) { var parenthesizedExpression = (ParenthesizedExpressionSyntax)node; openParen = parenthesizedExpression.OpenParenToken; expression = parenthesizedExpression.Expression; closeParen = parenthesizedExpression.CloseParenToken; } public bool IsIndexerMemberCRef(SyntaxNode? node) => node.IsKind(SyntaxKind.IndexerMemberCref); public SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true) { Contract.ThrowIfNull(root, "root"); Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position"); var end = root.FullSpan.End; if (end == 0) { // empty file return null; } // make sure position doesn't touch end of root position = Math.Min(position, end - 1); var node = root.FindToken(position).Parent; while (node != null) { if (useFullSpan || node.Span.Contains(position)) { var kind = node.Kind(); if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax)) { return node; } } node = node.Parent; } return null; } public bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node) { return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax; } public bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node) { return node is BaseNamespaceDeclarationSyntax || node is TypeDeclarationSyntax || node is EnumDeclarationSyntax; } private const string dotToken = "."; public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null) { if (node == null) { return string.Empty; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; // return type var memberDeclaration = node as MemberDeclarationSyntax; if ((options & DisplayNameOptions.IncludeType) != 0) { var type = memberDeclaration.GetMemberType(); if (type != null && !type.IsMissing) { builder.Append(type); builder.Append(' '); } } var names = ArrayBuilder<string?>.GetInstance(); // containing type(s) var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent; while (parent is TypeDeclarationSyntax) { names.Push(GetName(parent, options)); parent = parent.Parent; } // containing namespace(s) in source (if any) if ((options & DisplayNameOptions.IncludeNamespaces) != 0) { while (parent != null && parent.Kind() == SyntaxKind.NamespaceDeclaration) { names.Add(GetName(parent, options)); parent = parent.Parent; } } while (!names.IsEmpty()) { var name = names.Pop(); if (name != null) { builder.Append(name); builder.Append(dotToken); } } // name (including generic type parameters) builder.Append(GetName(node, options)); // parameter list (if any) if ((options & DisplayNameOptions.IncludeParameters) != 0) { builder.Append(memberDeclaration.GetParameterList()); } return pooled.ToStringAndFree(); } private static string? GetName(SyntaxNode node, DisplayNameOptions options) { const string missingTokenPlaceholder = "?"; switch (node.Kind()) { case SyntaxKind.CompilationUnit: return null; case SyntaxKind.IdentifierName: var identifier = ((IdentifierNameSyntax)node).Identifier; return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text; case SyntaxKind.IncompleteMember: return missingTokenPlaceholder; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return GetName(((BaseNamespaceDeclarationSyntax)node).Name, options); case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)node; return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options); } string? name = null; if (node is MemberDeclarationSyntax memberDeclaration) { if (memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration) { name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString(); } else { var nameToken = memberDeclaration.GetNameToken(); if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration) { name = "~" + name; } if ((options & DisplayNameOptions.IncludeTypeParameters) != 0) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append(name); AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()); name = pooled.ToStringAndFree(); } } else { Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember); name = "?"; } } } else { if (node is VariableDeclaratorSyntax fieldDeclarator) { var nameToken = fieldDeclarator.Identifier; if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; } } } Debug.Assert(name != null, "Unexpected node type " + node.Kind()); return name; } private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList) { if (typeParameterList != null && typeParameterList.Parameters.Count > 0) { builder.Append('<'); builder.Append(typeParameterList.Parameters[0].Identifier.ValueText); for (var i = 1; i < typeParameterList.Parameters.Count; i++) { builder.Append(", "); builder.Append(typeParameterList.Parameters[i].Identifier.ValueText); } builder.Append('>'); } } public List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: true, methodLevel: true); return list; } public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: false, methodLevel: true); return list; } public bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Kind() == SyntaxKind.ClassDeclaration; public bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Kind() == SyntaxKind.NamespaceDeclaration; public SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node) => node is NamespaceDeclarationSyntax namespaceDeclaration ? namespaceDeclaration.Name : null; public SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration) => ((TypeDeclarationSyntax)typeDeclaration).Members; public SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration) => ((NamespaceDeclarationSyntax)namespaceDeclaration).Members; public SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit) => ((CompilationUnitSyntax)compilationUnit).Members; public SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration) => ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Usings; public SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit) => ((CompilationUnitSyntax)compilationUnit).Usings; private void AppendMembers(SyntaxNode? node, List<SyntaxNode> list, bool topLevel, bool methodLevel) { Debug.Assert(topLevel || methodLevel); foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { if (topLevel) { list.Add(member); } AppendMembers(member, list, topLevel, methodLevel); continue; } if (methodLevel && IsMethodLevelMember(member)) { list.Add(member); } } } public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node) { if (node.Span.IsEmpty) { return default; } var member = GetContainingMemberDeclaration(node, node.SpanStart); if (member == null) { return default; } // TODO: currently we only support method for now if (member is BaseMethodDeclarationSyntax method) { if (method.Body == null) { return default; } return GetBlockBodySpan(method.Body); } return default; } public bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span) { switch (node) { case ConstructorDeclarationSyntax constructor: return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) || (constructor.Initializer != null && constructor.Initializer.Span.Contains(span)); case BaseMethodDeclarationSyntax method: return method.Body != null && GetBlockBodySpan(method.Body).Contains(span); case BasePropertyDeclarationSyntax property: return property.AccessorList != null && property.AccessorList.Span.Contains(span); case EnumMemberDeclarationSyntax @enum: return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span); case BaseFieldDeclarationSyntax field: return field.Declaration != null && field.Declaration.Span.Contains(span); } return false; } private static TextSpan GetBlockBodySpan(BlockSyntax body) => TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart); public SyntaxNode? TryGetBindableParent(SyntaxToken token) { var node = token.Parent; while (node != null) { var parent = node.Parent; // If this node is on the left side of a member access expression, don't ascend // further or we'll end up binding to something else. if (parent is MemberAccessExpressionSyntax memberAccess) { if (memberAccess.Expression == node) { break; } } // If this node is on the left side of a qualified name, don't ascend // further or we'll end up binding to something else. if (parent is QualifiedNameSyntax qualifiedName) { if (qualifiedName.Left == node) { break; } } // If this node is on the left side of a alias-qualified name, don't ascend // further or we'll end up binding to something else. if (parent is AliasQualifiedNameSyntax aliasQualifiedName) { if (aliasQualifiedName.Alias == node) { break; } } // If this node is the type of an object creation expression, return the // object creation expression. if (parent is ObjectCreationExpressionSyntax objectCreation) { if (objectCreation.Type == node) { node = parent; break; } } // The inside of an interpolated string is treated as its own token so we // need to force navigation to the parent expression syntax. if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax) { node = parent; break; } // If this node is not parented by a name, we're done. if (!(parent is NameSyntax)) { break; } node = parent; } if (node is VarPatternSyntax) { return node; } // Patterns are never bindable (though their constituent types/exprs may be). return node is PatternSyntax ? null : node; } public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken) { if (!(root is CompilationUnitSyntax compilationUnit)) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var constructors = new List<SyntaxNode>(); AppendConstructors(compilationUnit.Members, constructors, cancellationToken); return constructors; } private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); switch (member) { case ConstructorDeclarationSyntax constructor: constructors.Add(constructor); continue; case BaseNamespaceDeclarationSyntax @namespace: AppendConstructors(@namespace.Members, constructors, cancellationToken); break; case ClassDeclarationSyntax @class: AppendConstructors(@class.Members, constructors, cancellationToken); break; case RecordDeclarationSyntax record: AppendConstructors(record.Members, constructors, cancellationToken); break; case StructDeclarationSyntax @struct: AppendConstructors(@struct.Members, constructors, cancellationToken); break; } } } public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace) { if (token.Kind() == SyntaxKind.CloseBraceToken) { var tuple = token.Parent.GetBraces(); openBrace = tuple.openBrace; return openBrace.Kind() == SyntaxKind.OpenBraceToken; } openBrace = default; return false; } public TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (trivia.Kind() == SyntaxKind.DisabledTextTrivia) { return trivia.FullSpan; } var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken); if (token.Kind() == SyntaxKind.EndOfFileToken) { var triviaList = token.LeadingTrivia; foreach (var triviaTok in triviaList.Reverse()) { if (triviaTok.Span.Contains(position)) { return default; } if (triviaTok.Span.End < position) { if (!triviaTok.HasStructure) { return default; } var structure = triviaTok.GetStructure(); if (structure is BranchingDirectiveTriviaSyntax branch) { return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default; } } } } return default; } public string GetNameForArgument(SyntaxNode? argument) => (argument as ArgumentSyntax)?.NameColon?.Name.Identifier.ValueText ?? string.Empty; public string GetNameForAttributeArgument(SyntaxNode? argument) => (argument as AttributeArgumentSyntax)?.NameEquals?.Name.Identifier.ValueText ?? string.Empty; public bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfDot(); public SyntaxNode? GetRightSideOfDot(SyntaxNode? node) { return (node as QualifiedNameSyntax)?.Right ?? (node as MemberAccessExpressionSyntax)?.Name; } public SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget) { return (node as QualifiedNameSyntax)?.Left ?? (node as MemberAccessExpressionSyntax)?.Expression; } public bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node) => (node as NameSyntax).IsLeftSideOfExplicitInterfaceSpecifier(); public bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAssignExpression(); public bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAnyAssignExpression(); public bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfCompoundAssignExpression(); public SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node) => (node as AssignmentExpressionSyntax)?.Right; public bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonObject) && anonObject.NameEquals == null; public bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostIncrementExpression) || node.IsParentKind(SyntaxKind.PreIncrementExpression); public static bool IsOperandOfDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostDecrementExpression) || node.IsParentKind(SyntaxKind.PreDecrementExpression); public bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => IsOperandOfIncrementExpression(node) || IsOperandOfDecrementExpression(node); public SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString) => ((InterpolatedStringExpressionSyntax)interpolatedString).Contents; public bool IsVerbatimStringLiteral(SyntaxToken token) => token.IsVerbatimStringLiteral(); public bool IsNumericLiteral(SyntaxToken token) => token.Kind() == SyntaxKind.NumericLiteralToken; public void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList) { var invocation = (InvocationExpressionSyntax)node; expression = invocation.Expression; argumentList = invocation.ArgumentList; } public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? invocationExpression) => GetArgumentsOfArgumentList((invocationExpression as InvocationExpressionSyntax)?.ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? objectCreationExpression) => GetArgumentsOfArgumentList((objectCreationExpression as BaseObjectCreationExpressionSyntax)?.ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? argumentList) => (argumentList as BaseArgumentListSyntax)?.Arguments ?? default; public SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode invocationExpression) => ((InvocationExpressionSyntax)invocationExpression).ArgumentList; public SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode objectCreationExpression) => ((ObjectCreationExpressionSyntax)objectCreationExpression)!.ArgumentList; public bool IsRegularComment(SyntaxTrivia trivia) => trivia.IsRegularComment(); public bool IsDocumentationComment(SyntaxTrivia trivia) => trivia.IsDocComment(); public bool IsElastic(SyntaxTrivia trivia) => trivia.IsElastic(); public bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes) => trivia.IsPragmaDirective(out isDisable, out isActive, out errorCodes); public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia; public bool IsDocumentationComment(SyntaxNode node) => SyntaxFacts.IsDocumentationCommentTrivia(node.Kind()); public bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node) { return node.IsKind(SyntaxKind.UsingDirective) || node.IsKind(SyntaxKind.ExternAliasDirective); } public bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword); public bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.ModuleKeyword); private static bool IsGlobalAttribute([NotNullWhen(true)] SyntaxNode? node, SyntaxKind attributeTarget) => node.IsKind(SyntaxKind.Attribute) && node.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) && attributeList.Target?.Identifier.Kind() == attributeTarget; private static bool IsMemberDeclaration(SyntaxNode node) { // From the C# language spec: // class-member-declaration: // constant-declaration // field-declaration // method-declaration // property-declaration // event-declaration // indexer-declaration // operator-declaration // constructor-declaration // destructor-declaration // static-constructor-declaration // type-declaration switch (node.Kind()) { // Because fields declarations can define multiple symbols "public int a, b;" // We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. case SyntaxKind.VariableDeclarator: return node.Parent.IsParentKind(SyntaxKind.FieldDeclaration) || node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration); case SyntaxKind.FieldDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return true; default: return false; } } public bool IsDeclaration(SyntaxNode node) => SyntaxFacts.IsNamespaceMemberDeclaration(node.Kind()) || IsMemberDeclaration(node); public bool IsTypeDeclaration(SyntaxNode node) => SyntaxFacts.IsTypeDeclaration(node.Kind()); public SyntaxNode? GetObjectCreationInitializer(SyntaxNode node) => ((ObjectCreationExpressionSyntax)node).Initializer; public SyntaxNode GetObjectCreationType(SyntaxNode node) => ((ObjectCreationExpressionSyntax)node).Type; public bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement) => statement.IsKind(SyntaxKind.ExpressionStatement, out ExpressionStatementSyntax? exprStatement) && exprStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression); public void GetPartsOfAssignmentStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { GetPartsOfAssignmentExpressionOrStatement( ((ExpressionStatementSyntax)statement).Expression, out left, out operatorToken, out right); } public void GetPartsOfAssignmentExpressionOrStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var expression = statement; if (statement is ExpressionStatementSyntax expressionStatement) { expression = expressionStatement.Expression; } var assignment = (AssignmentExpressionSyntax)expression; left = assignment.Left; operatorToken = assignment.OperatorToken; right = assignment.Right; } public SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode memberAccessExpression) => ((MemberAccessExpressionSyntax)memberAccessExpression).Name; public void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name) { var memberAccess = (MemberAccessExpressionSyntax)node; expression = memberAccess.Expression; operatorToken = memberAccess.OperatorToken; name = memberAccess.Name; } public SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node) => ((SimpleNameSyntax)node).Identifier; public SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Identifier; public SyntaxToken GetIdentifierOfParameter(SyntaxNode node) => ((ParameterSyntax)node).Identifier; public SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node) => ((IdentifierNameSyntax)node).Identifier; public bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.LocalFunctionStatement); public bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement) { return ((LocalDeclarationStatementSyntax)localDeclarationStatement).Declaration.Variables.Contains( (VariableDeclaratorSyntax)declarator); } public bool AreEquivalent(SyntaxToken token1, SyntaxToken token2) => SyntaxFactory.AreEquivalent(token1, token2); public bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2) => SyntaxFactory.AreEquivalent(node1, node2); public bool IsExpressionOfInvocationExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as InvocationExpressionSyntax)?.Expression == node; public bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as AwaitExpressionSyntax)?.Expression == node; public bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as MemberAccessExpressionSyntax)?.Expression == node; public static SyntaxNode GetExpressionOfInvocationExpression(SyntaxNode node) => ((InvocationExpressionSyntax)node).Expression; public SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node) => ((AwaitExpressionSyntax)node).Expression; public bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is ForEachStatementSyntax foreachStatement && foreachStatement.Expression == node; public SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node) => ((ExpressionStatementSyntax)node).Expression; public bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is BinaryExpressionSyntax; public bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsExpression); public void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryExpression = (BinaryExpressionSyntax)node; left = binaryExpression.Left; operatorToken = binaryExpression.OperatorToken; right = binaryExpression.Right; } public void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse) { var conditionalExpression = (ConditionalExpressionSyntax)node; condition = conditionalExpression.Condition; whenTrue = conditionalExpression.WhenTrue; whenFalse = conditionalExpression.WhenFalse; } [return: NotNullIfNotNull("node")] public SyntaxNode? WalkDownParentheses(SyntaxNode? node) => (node as ExpressionSyntax)?.WalkDownParentheses() ?? node; public void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode { var tupleExpression = (TupleExpressionSyntax)node; openParen = tupleExpression.OpenParenToken; arguments = (SeparatedSyntaxList<TArgumentSyntax>)(SeparatedSyntaxList<SyntaxNode>)tupleExpression.Arguments; closeParen = tupleExpression.CloseParenToken; } public SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node) => ((PrefixUnaryExpressionSyntax)node).Operand; public SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node) => ((PrefixUnaryExpressionSyntax)node).OperatorToken; public SyntaxNode? GetNextExecutableStatement(SyntaxNode statement) => ((StatementSyntax)statement).GetNextStatement(); public override bool IsSingleLineCommentTrivia(SyntaxTrivia trivia) => trivia.IsSingleLineComment(); public override bool IsMultiLineCommentTrivia(SyntaxTrivia trivia) => trivia.IsMultiLineComment(); public override bool IsSingleLineDocCommentTrivia(SyntaxTrivia trivia) => trivia.IsSingleLineDocComment(); public override bool IsMultiLineDocCommentTrivia(SyntaxTrivia trivia) => trivia.IsMultiLineDocComment(); public override bool IsShebangDirectiveTrivia(SyntaxTrivia trivia) => trivia.IsShebangDirective(); public override bool IsPreprocessorDirective(SyntaxTrivia trivia) => SyntaxFacts.IsPreprocessorDirective(trivia.Kind()); public bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) { var node = TryGetAncestorForLocation<BaseTypeDeclarationSyntax>(root, position); typeDeclaration = node; if (node == null) return false; var lastToken = (node as TypeDeclarationSyntax)?.TypeParameterList?.GetLastToken() ?? node.Identifier; if (fullHeader) lastToken = node.BaseList?.GetLastToken() ?? lastToken; return IsOnHeader(root, position, node, lastToken); } public bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration) { var node = TryGetAncestorForLocation<PropertyDeclarationSyntax>(root, position); propertyDeclaration = node; if (propertyDeclaration == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.Identifier); } public bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter) { var node = TryGetAncestorForLocation<ParameterSyntax>(root, position); parameter = node; if (parameter == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node); } public bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method) { var node = TryGetAncestorForLocation<MethodDeclarationSyntax>(root, position); method = node; if (method == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.ParameterList); } public bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction) { var node = TryGetAncestorForLocation<LocalFunctionStatementSyntax>(root, position); localFunction = node; if (localFunction == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.ParameterList); } public bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration) { var node = TryGetAncestorForLocation<LocalDeclarationStatementSyntax>(root, position); localDeclaration = node; if (localDeclaration == null) { return false; } var initializersExpressions = node!.Declaration.Variables .Where(v => v.Initializer != null) .SelectAsArray(initializedV => initializedV.Initializer!.Value); return IsOnHeader(root, position, node, node, holes: initializersExpressions); } public bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement) { var node = TryGetAncestorForLocation<IfStatementSyntax>(root, position); ifStatement = node; if (ifStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement) { var node = TryGetAncestorForLocation<WhileStatementSyntax>(root, position); whileStatement = node; if (whileStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement) { var node = TryGetAncestorForLocation<ForEachStatementSyntax>(root, position); foreachStatement = node; if (foreachStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) { var token = root.FindToken(position); var typeDecl = token.GetAncestor<TypeDeclarationSyntax>(); typeDeclaration = typeDecl; if (typeDecl == null) { return false; } RoslynDebug.AssertNotNull(typeDeclaration); if (position < typeDecl.OpenBraceToken.Span.End || position > typeDecl.CloseBraceToken.Span.Start) { return false; } var line = sourceText.Lines.GetLineFromPosition(position); if (!line.IsEmptyOrWhitespace()) { return false; } var member = typeDecl.Members.FirstOrDefault(d => d.FullSpan.Contains(position)); if (member == null) { // There are no members, or we're after the last member. return true; } else { // We're within a member. Make sure we're in the leading whitespace of // the member. if (position < member.SpanStart) { foreach (var trivia in member.GetLeadingTrivia()) { if (!trivia.IsWhitespaceOrEndOfLine()) { return false; } if (trivia.FullSpan.Contains(position)) { return true; } } } } return false; } protected override bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken) => token.ContainsInterleavedDirective(span, cancellationToken); public SyntaxTokenList GetModifiers(SyntaxNode? node) => node.GetModifiers(); public SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers) => node.WithModifiers(modifiers); public bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node is LiteralExpressionSyntax; public SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node) => ((LocalDeclarationStatementSyntax)node).Declaration.Variables; public SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Initializer; public SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node) => ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)node).Parent!).Type; public SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node) => ((EqualsValueClauseSyntax?)node)?.Value; public bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block); public bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection, SyntaxKind.CompilationUnit); public IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node) { return node switch { BlockSyntax block => block.Statements, SwitchSectionSyntax switchSection => switchSection.Statements, CompilationUnitSyntax compilationUnit => compilationUnit.Members.OfType<GlobalStatementSyntax>().SelectAsArray(globalStatement => globalStatement.Statement), _ => throw ExceptionUtilities.UnexpectedValue(node), }; } public SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes) => nodes.FindInnermostCommonNode(node => IsExecutableBlock(node)); public bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node) => IsExecutableBlock(node) || node.IsEmbeddedStatementOwner(); public IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node) { if (IsExecutableBlock(node)) return GetExecutableBlockStatements(node); else if (node.GetEmbeddedStatement() is { } embeddedStatement) return ImmutableArray.Create<SyntaxNode>(embeddedStatement); else return ImmutableArray<SyntaxNode>.Empty; } public bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression) { var cast = (CastExpressionSyntax)node; type = cast.Type; expression = cast.Expression; } public SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token) { if (token.Kind() == SyntaxKind.OverrideKeyword && token.Parent is MemberDeclarationSyntax member) { return member.GetNameToken(); } return null; } public override SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node) => node.GetAttributeLists(); public override bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.XmlElement, out XmlElementSyntax? xmlElement) && xmlElement.StartTag.Name.LocalName.ValueText == DocumentationCommentXmlNames.ParameterElementName; public override SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia) { if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia) { return documentationCommentTrivia.Content; } throw ExceptionUtilities.UnexpectedValue(trivia.Kind()); } public override bool CanHaveAccessibility(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return true; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: var declarationKind = this.GetDeclarationKind(declaration); return declarationKind == DeclarationKind.Field || declarationKind == DeclarationKind.Event; case SyntaxKind.ConstructorDeclaration: // Static constructor can't have accessibility return !((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword); case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExplicitInterfaceSpecifier != null) { // explicit interface methods can't have accessibility. return false; } if (method.Modifiers.Any(SyntaxKind.PartialKeyword)) { // partial methods can't have accessibility modifiers. return false; } return true; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; default: return false; } } public override Accessibility GetAccessibility(SyntaxNode declaration) { if (!CanHaveAccessibility(declaration)) { return Accessibility.NotApplicable; } var modifierTokens = GetModifierTokens(declaration); GetAccessibilityAndModifiers(modifierTokens, out var accessibility, out _, out _); return accessibility; } public override void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault) { accessibility = Accessibility.NotApplicable; modifiers = DeclarationModifiers.None; isDefault = false; foreach (var token in modifierList) { accessibility = (token.Kind(), accessibility) switch { (SyntaxKind.PublicKeyword, _) => Accessibility.Public, (SyntaxKind.PrivateKeyword, Accessibility.Protected) => Accessibility.ProtectedAndInternal, (SyntaxKind.PrivateKeyword, _) => Accessibility.Private, (SyntaxKind.InternalKeyword, Accessibility.Protected) => Accessibility.ProtectedOrInternal, (SyntaxKind.InternalKeyword, _) => Accessibility.Internal, (SyntaxKind.ProtectedKeyword, Accessibility.Private) => Accessibility.ProtectedAndInternal, (SyntaxKind.ProtectedKeyword, Accessibility.Internal) => Accessibility.ProtectedOrInternal, (SyntaxKind.ProtectedKeyword, _) => Accessibility.Protected, _ => accessibility, }; modifiers |= token.Kind() switch { SyntaxKind.AbstractKeyword => DeclarationModifiers.Abstract, SyntaxKind.NewKeyword => DeclarationModifiers.New, SyntaxKind.OverrideKeyword => DeclarationModifiers.Override, SyntaxKind.VirtualKeyword => DeclarationModifiers.Virtual, SyntaxKind.StaticKeyword => DeclarationModifiers.Static, SyntaxKind.AsyncKeyword => DeclarationModifiers.Async, SyntaxKind.ConstKeyword => DeclarationModifiers.Const, SyntaxKind.ReadOnlyKeyword => DeclarationModifiers.ReadOnly, SyntaxKind.SealedKeyword => DeclarationModifiers.Sealed, SyntaxKind.UnsafeKeyword => DeclarationModifiers.Unsafe, SyntaxKind.PartialKeyword => DeclarationModifiers.Partial, SyntaxKind.RefKeyword => DeclarationModifiers.Ref, SyntaxKind.VolatileKeyword => DeclarationModifiers.Volatile, SyntaxKind.ExternKeyword => DeclarationModifiers.Extern, _ => DeclarationModifiers.None, }; isDefault |= token.Kind() == SyntaxKind.DefaultKeyword; } } public override SyntaxTokenList GetModifierTokens(SyntaxNode? declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.Modifiers, ParameterSyntax parameter => parameter.Modifiers, LocalDeclarationStatementSyntax localDecl => localDecl.Modifiers, LocalFunctionStatementSyntax localFunc => localFunc.Modifiers, AccessorDeclarationSyntax accessor => accessor.Modifiers, VariableDeclarationSyntax varDecl => GetModifierTokens(varDecl.Parent), VariableDeclaratorSyntax varDecl => GetModifierTokens(varDecl.Parent), AnonymousFunctionExpressionSyntax anonymous => anonymous.Modifiers, _ => default, }; public override DeclarationKind GetDeclarationKind(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: return DeclarationKind.Class; case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: return DeclarationKind.Struct; case SyntaxKind.InterfaceDeclaration: return DeclarationKind.Interface; case SyntaxKind.EnumDeclaration: return DeclarationKind.Enum; case SyntaxKind.DelegateDeclaration: return DeclarationKind.Delegate; case SyntaxKind.MethodDeclaration: return DeclarationKind.Method; case SyntaxKind.OperatorDeclaration: return DeclarationKind.Operator; case SyntaxKind.ConversionOperatorDeclaration: return DeclarationKind.ConversionOperator; case SyntaxKind.ConstructorDeclaration: return DeclarationKind.Constructor; case SyntaxKind.DestructorDeclaration: return DeclarationKind.Destructor; case SyntaxKind.PropertyDeclaration: return DeclarationKind.Property; case SyntaxKind.IndexerDeclaration: return DeclarationKind.Indexer; case SyntaxKind.EventDeclaration: return DeclarationKind.CustomEvent; case SyntaxKind.EnumMemberDeclaration: return DeclarationKind.EnumMember; case SyntaxKind.CompilationUnit: return DeclarationKind.CompilationUnit; case SyntaxKind.NamespaceDeclaration: return DeclarationKind.Namespace; case SyntaxKind.UsingDirective: return DeclarationKind.NamespaceImport; case SyntaxKind.Parameter: return DeclarationKind.Parameter; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return DeclarationKind.LambdaExpression; case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration != null && fd.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Field; } else { return DeclarationKind.None; } case SyntaxKind.EventFieldDeclaration: var ef = (EventFieldDeclarationSyntax)declaration; if (ef.Declaration != null && ef.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Event; } else { return DeclarationKind.None; } case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration != null && ld.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Variable; } else { return DeclarationKind.None; } case SyntaxKind.VariableDeclaration: { var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1 && vd.Parent == null) { // this node is the declaration if it contains only one variable and has no parent. return DeclarationKind.Variable; } else { return DeclarationKind.None; } } case SyntaxKind.VariableDeclarator: { var vd = declaration.Parent as VariableDeclarationSyntax; // this node is considered the declaration if it is one among many, or it has no parent if (vd == null || vd.Variables.Count > 1) { if (ParentIsFieldDeclaration(vd)) { return DeclarationKind.Field; } else if (ParentIsEventFieldDeclaration(vd)) { return DeclarationKind.Event; } else { return DeclarationKind.Variable; } } break; } case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.Attribute: if (!(declaration.Parent is AttributeListSyntax parentList) || parentList.Attributes.Count > 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.GetAccessorDeclaration: return DeclarationKind.GetAccessor; case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: return DeclarationKind.SetAccessor; case SyntaxKind.AddAccessorDeclaration: return DeclarationKind.AddAccessor; case SyntaxKind.RemoveAccessorDeclaration: return DeclarationKind.RemoveAccessor; } return DeclarationKind.None; } internal static bool ParentIsFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.FieldDeclaration) ?? false; internal static bool ParentIsEventFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.EventFieldDeclaration) ?? false; internal static bool ParentIsLocalDeclarationStatement([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) ?? false; public bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsPatternExpression); public void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right) { var isPatternExpression = (IsPatternExpressionSyntax)node; left = isPatternExpression.Expression; isToken = isPatternExpression.IsKeyword; right = isPatternExpression.Pattern; } public bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node) => node is PatternSyntax; public bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ConstantPattern); public bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.DeclarationPattern); public bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.RecursivePattern); public bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.VarPattern); public SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node) => ((ConstantPatternSyntax)node).Expression; public void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation) { var declarationPattern = (DeclarationPatternSyntax)node; type = declarationPattern.Type; designation = declarationPattern.Designation; } public void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation) { var recursivePattern = (RecursivePatternSyntax)node; type = recursivePattern.Type; positionalPart = recursivePattern.PositionalPatternClause; propertyPart = recursivePattern.PropertyPatternClause; designation = recursivePattern.Designation; } public bool SupportsNotPattern(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp9OrAbove(); public bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AndPattern); public bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is BinaryPatternSyntax; public bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.NotPattern); public bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.OrPattern); public bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParenthesizedPattern); public bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.TypePattern); public bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is UnaryPatternSyntax; public void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen) { var parenthesizedPattern = (ParenthesizedPatternSyntax)node; openParen = parenthesizedPattern.OpenParenToken; pattern = parenthesizedPattern.Pattern; closeParen = parenthesizedPattern.CloseParenToken; } public void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryPattern = (BinaryPatternSyntax)node; left = binaryPattern.Left; operatorToken = binaryPattern.OperatorToken; right = binaryPattern.Right; } public void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern) { var unaryPattern = (UnaryPatternSyntax)node; operatorToken = unaryPattern.OperatorToken; pattern = unaryPattern.Pattern; } public SyntaxNode GetTypeOfTypePattern(SyntaxNode node) => ((TypePatternSyntax)node).Type; public bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ImplicitObjectCreationExpression); public SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression) => ((ThrowExpressionSyntax)throwExpression).Expression; public bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ThrowStatement); public bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.LocalFunctionStatement); public void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken) { var interpolatedStringExpression = (InterpolatedStringExpressionSyntax)node; stringStartToken = interpolatedStringExpression.StringStartToken; contents = interpolatedStringExpression.Contents; stringEndToken = interpolatedStringExpression.StringEndToken; } public bool IsVerbatimInterpolatedStringExpression(SyntaxNode node) => node is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; #if CODE_STYLE using Microsoft.CodeAnalysis.Internal.Editing; #else using Microsoft.CodeAnalysis.Editing; #endif namespace Microsoft.CodeAnalysis.CSharp.LanguageServices { internal class CSharpSyntaxFacts : AbstractSyntaxFacts, ISyntaxFacts { internal static readonly CSharpSyntaxFacts Instance = new(); protected CSharpSyntaxFacts() { } public bool IsCaseSensitive => true; public StringComparer StringComparer { get; } = StringComparer.Ordinal; public SyntaxTrivia ElasticMarker => SyntaxFactory.ElasticMarker; public SyntaxTrivia ElasticCarriageReturnLineFeed => SyntaxFactory.ElasticCarriageReturnLineFeed; public override ISyntaxKinds SyntaxKinds { get; } = CSharpSyntaxKinds.Instance; protected override IDocumentationCommentService DocumentationCommentService => CSharpDocumentationCommentService.Instance; public bool SupportsIndexingInitializer(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp6; public bool SupportsThrowExpression(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsLocalFunctionDeclaration(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp7; public bool SupportsRecord(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion >= LanguageVersion.CSharp9; public bool SupportsRecordStruct(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp10OrAbove(); public SyntaxToken ParseToken(string text) => SyntaxFactory.ParseToken(text); public SyntaxTriviaList ParseLeadingTrivia(string text) => SyntaxFactory.ParseLeadingTrivia(text); public string EscapeIdentifier(string identifier) { var nullIndex = identifier.IndexOf('\0'); if (nullIndex >= 0) { identifier = identifier.Substring(0, nullIndex); } var needsEscaping = SyntaxFacts.GetKeywordKind(identifier) != SyntaxKind.None; return needsEscaping ? "@" + identifier : identifier; } public bool IsVerbatimIdentifier(SyntaxToken token) => token.IsVerbatimIdentifier(); public bool IsOperator(SyntaxToken token) { var kind = token.Kind(); return (SyntaxFacts.IsAnyUnaryExpression(kind) && (token.Parent is PrefixUnaryExpressionSyntax || token.Parent is PostfixUnaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsBinaryExpression(kind) && (token.Parent is BinaryExpressionSyntax || token.Parent is OperatorDeclarationSyntax)) || (SyntaxFacts.IsAssignmentExpressionOperatorToken(kind) && token.Parent is AssignmentExpressionSyntax); } public bool IsReservedKeyword(SyntaxToken token) => SyntaxFacts.IsReservedKeyword(token.Kind()); public bool IsContextualKeyword(SyntaxToken token) => SyntaxFacts.IsContextualKeyword(token.Kind()); public bool IsPreprocessorKeyword(SyntaxToken token) => SyntaxFacts.IsPreprocessorKeyword(token.Kind()); public bool IsPreProcessorDirectiveContext(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) => syntaxTree.IsPreProcessorDirectiveContext( position, syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true), cancellationToken); public bool IsEntirelyWithinStringOrCharOrNumericLiteral([NotNullWhen(true)] SyntaxTree? syntaxTree, int position, CancellationToken cancellationToken) { if (syntaxTree == null) { return false; } return syntaxTree.IsEntirelyWithinStringOrCharLiteral(position, cancellationToken); } public bool IsDirective([NotNullWhen(true)] SyntaxNode? node) => node is DirectiveTriviaSyntax; public bool TryGetExternalSourceInfo([NotNullWhen(true)] SyntaxNode? node, out ExternalSourceInfo info) { if (node is LineDirectiveTriviaSyntax lineDirective) { if (lineDirective.Line.Kind() == SyntaxKind.DefaultKeyword) { info = new ExternalSourceInfo(null, ends: true); return true; } else if (lineDirective.Line.Kind() == SyntaxKind.NumericLiteralToken && lineDirective.Line.Value is int) { info = new ExternalSourceInfo((int)lineDirective.Line.Value, false); return true; } } info = default; return false; } public bool IsRightSideOfQualifiedName([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsRightSideOfQualifiedName(); } public bool IsNameOfSimpleMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsSimpleMemberAccessExpressionName(); } public bool IsNameOfAnyMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is MemberAccessExpressionSyntax memberAccess && memberAccess.Name == node; public bool IsNameOfMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) { var name = node as SimpleNameSyntax; return name.IsMemberBindingExpressionName(); } [return: NotNullIfNotNull("node")] public SyntaxNode? GetStandaloneExpression(SyntaxNode? node) => node is ExpressionSyntax expression ? SyntaxFactory.GetStandaloneExpression(expression) : node; public SyntaxNode? GetRootConditionalAccessExpression(SyntaxNode? node) => node.GetRootConditionalAccessExpression(); public bool IsObjectCreationExpressionType([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.ObjectCreationExpression, out ObjectCreationExpressionSyntax? objectCreation) && objectCreation.Type == node; public bool IsDeclarationExpression([NotNullWhen(true)] SyntaxNode? node) => node is DeclarationExpressionSyntax; public bool IsAttributeName(SyntaxNode node) => SyntaxFacts.IsAttributeName(node); public bool IsAnonymousFunction([NotNullWhen(true)] SyntaxNode? node) { return node is ParenthesizedLambdaExpressionSyntax || node is SimpleLambdaExpressionSyntax || node is AnonymousMethodExpressionSyntax; } public bool IsNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node is ArgumentSyntax arg && arg.NameColon != null; public bool IsNameOfNamedArgument([NotNullWhen(true)] SyntaxNode? node) => node.CheckParent<NameColonSyntax>(p => p.Name == node); public SyntaxToken? GetNameOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Identifier; public SyntaxNode? GetDefaultOfParameter(SyntaxNode? node) => (node as ParameterSyntax)?.Default; public SyntaxNode? GetParameterList(SyntaxNode node) => node.GetParameterList(); public bool IsParameterList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParameterList, SyntaxKind.BracketedParameterList); public SyntaxToken GetIdentifierOfGenericName(SyntaxNode? genericName) { return genericName is GenericNameSyntax csharpGenericName ? csharpGenericName.Identifier : default; } public bool IsUsingDirectiveName([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax? usingDirective) && usingDirective.Name == node; public bool IsUsingAliasDirective([NotNullWhen(true)] SyntaxNode? node) => node is UsingDirectiveSyntax usingDirectiveNode && usingDirectiveNode.Alias != null; public bool IsDeconstructionForEachStatement([NotNullWhen(true)] SyntaxNode? node) => node is ForEachVariableStatementSyntax; public bool IsDeconstructionAssignment([NotNullWhen(true)] SyntaxNode? node) => node is AssignmentExpressionSyntax assignment && assignment.IsDeconstruction(); public Location GetDeconstructionReferenceLocation(SyntaxNode node) { return node switch { AssignmentExpressionSyntax assignment => assignment.Left.GetLocation(), ForEachVariableStatementSyntax @foreach => @foreach.Variable.GetLocation(), _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()), }; } public bool IsStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsExecutableStatement([NotNullWhen(true)] SyntaxNode? node) => node is StatementSyntax; public bool IsMethodBody([NotNullWhen(true)] SyntaxNode? node) { if (node is BlockSyntax || node is ArrowExpressionClauseSyntax) { return node.Parent is BaseMethodDeclarationSyntax || node.Parent is AccessorDeclarationSyntax; } return false; } public SyntaxNode? GetExpressionOfReturnStatement(SyntaxNode? node) => (node as ReturnStatementSyntax)?.Expression; public bool IsThisConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.ThisConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsBaseConstructorInitializer(SyntaxToken token) => token.Parent.IsKind(SyntaxKind.BaseConstructorInitializer, out ConstructorInitializerSyntax? constructorInit) && constructorInit.ThisOrBaseKeyword == token; public bool IsQueryKeyword(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.FromKeyword: case SyntaxKind.JoinKeyword: case SyntaxKind.LetKeyword: case SyntaxKind.OrderByKeyword: case SyntaxKind.WhereKeyword: case SyntaxKind.OnKeyword: case SyntaxKind.EqualsKeyword: case SyntaxKind.InKeyword: return token.Parent is QueryClauseSyntax; case SyntaxKind.ByKeyword: case SyntaxKind.GroupKeyword: case SyntaxKind.SelectKeyword: return token.Parent is SelectOrGroupClauseSyntax; case SyntaxKind.AscendingKeyword: case SyntaxKind.DescendingKeyword: return token.Parent is OrderingSyntax; case SyntaxKind.IntoKeyword: return token.Parent.IsKind(SyntaxKind.JoinIntoClause, SyntaxKind.QueryContinuation); default: return false; } } public bool IsThrowExpression(SyntaxNode node) => node.Kind() == SyntaxKind.ThrowExpression; public bool IsPredefinedType(SyntaxToken token) => TryGetPredefinedType(token, out _); public bool IsPredefinedType(SyntaxToken token, PredefinedType type) => TryGetPredefinedType(token, out var actualType) && actualType == type; public bool TryGetPredefinedType(SyntaxToken token, out PredefinedType type) { type = GetPredefinedType(token); return type != PredefinedType.None; } private static PredefinedType GetPredefinedType(SyntaxToken token) { return (SyntaxKind)token.RawKind switch { SyntaxKind.BoolKeyword => PredefinedType.Boolean, SyntaxKind.ByteKeyword => PredefinedType.Byte, SyntaxKind.SByteKeyword => PredefinedType.SByte, SyntaxKind.IntKeyword => PredefinedType.Int32, SyntaxKind.UIntKeyword => PredefinedType.UInt32, SyntaxKind.ShortKeyword => PredefinedType.Int16, SyntaxKind.UShortKeyword => PredefinedType.UInt16, SyntaxKind.LongKeyword => PredefinedType.Int64, SyntaxKind.ULongKeyword => PredefinedType.UInt64, SyntaxKind.FloatKeyword => PredefinedType.Single, SyntaxKind.DoubleKeyword => PredefinedType.Double, SyntaxKind.DecimalKeyword => PredefinedType.Decimal, SyntaxKind.StringKeyword => PredefinedType.String, SyntaxKind.CharKeyword => PredefinedType.Char, SyntaxKind.ObjectKeyword => PredefinedType.Object, SyntaxKind.VoidKeyword => PredefinedType.Void, _ => PredefinedType.None, }; } public bool IsPredefinedOperator(SyntaxToken token) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator != PredefinedOperator.None; public bool IsPredefinedOperator(SyntaxToken token, PredefinedOperator op) => TryGetPredefinedOperator(token, out var actualOperator) && actualOperator == op; public bool TryGetPredefinedOperator(SyntaxToken token, out PredefinedOperator op) { op = GetPredefinedOperator(token); return op != PredefinedOperator.None; } private static PredefinedOperator GetPredefinedOperator(SyntaxToken token) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.PlusToken: case SyntaxKind.PlusEqualsToken: return PredefinedOperator.Addition; case SyntaxKind.MinusToken: case SyntaxKind.MinusEqualsToken: return PredefinedOperator.Subtraction; case SyntaxKind.AmpersandToken: case SyntaxKind.AmpersandEqualsToken: return PredefinedOperator.BitwiseAnd; case SyntaxKind.BarToken: case SyntaxKind.BarEqualsToken: return PredefinedOperator.BitwiseOr; case SyntaxKind.MinusMinusToken: return PredefinedOperator.Decrement; case SyntaxKind.PlusPlusToken: return PredefinedOperator.Increment; case SyntaxKind.SlashToken: case SyntaxKind.SlashEqualsToken: return PredefinedOperator.Division; case SyntaxKind.EqualsEqualsToken: return PredefinedOperator.Equality; case SyntaxKind.CaretToken: case SyntaxKind.CaretEqualsToken: return PredefinedOperator.ExclusiveOr; case SyntaxKind.GreaterThanToken: return PredefinedOperator.GreaterThan; case SyntaxKind.GreaterThanEqualsToken: return PredefinedOperator.GreaterThanOrEqual; case SyntaxKind.ExclamationEqualsToken: return PredefinedOperator.Inequality; case SyntaxKind.LessThanLessThanToken: case SyntaxKind.LessThanLessThanEqualsToken: return PredefinedOperator.LeftShift; case SyntaxKind.LessThanToken: return PredefinedOperator.LessThan; case SyntaxKind.LessThanEqualsToken: return PredefinedOperator.LessThanOrEqual; case SyntaxKind.AsteriskToken: case SyntaxKind.AsteriskEqualsToken: return PredefinedOperator.Multiplication; case SyntaxKind.PercentToken: case SyntaxKind.PercentEqualsToken: return PredefinedOperator.Modulus; case SyntaxKind.ExclamationToken: case SyntaxKind.TildeToken: return PredefinedOperator.Complement; case SyntaxKind.GreaterThanGreaterThanToken: case SyntaxKind.GreaterThanGreaterThanEqualsToken: return PredefinedOperator.RightShift; } return PredefinedOperator.None; } public string GetText(int kind) => SyntaxFacts.GetText((SyntaxKind)kind); public bool IsIdentifierStartCharacter(char c) => SyntaxFacts.IsIdentifierStartCharacter(c); public bool IsIdentifierPartCharacter(char c) => SyntaxFacts.IsIdentifierPartCharacter(c); public bool IsIdentifierEscapeCharacter(char c) => c == '@'; public bool IsValidIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length; } public bool IsVerbatimIdentifier(string identifier) { var token = SyntaxFactory.ParseToken(identifier); return this.IsIdentifier(token) && !token.ContainsDiagnostics && token.ToString().Length == identifier.Length && token.IsVerbatimIdentifier(); } public bool IsTypeCharacter(char c) => false; public bool IsStartOfUnicodeEscapeSequence(char c) => c == '\\'; public bool IsLiteral(SyntaxToken token) { switch (token.Kind()) { case SyntaxKind.NumericLiteralToken: case SyntaxKind.CharacterLiteralToken: case SyntaxKind.StringLiteralToken: case SyntaxKind.NullKeyword: case SyntaxKind.TrueKeyword: case SyntaxKind.FalseKeyword: case SyntaxKind.InterpolatedStringStartToken: case SyntaxKind.InterpolatedStringEndToken: case SyntaxKind.InterpolatedVerbatimStringStartToken: case SyntaxKind.InterpolatedStringTextToken: return true; default: return false; } } public bool IsStringLiteralOrInterpolatedStringLiteral(SyntaxToken token) => token.IsKind(SyntaxKind.StringLiteralToken, SyntaxKind.InterpolatedStringTextToken); public bool IsNumericLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node?.IsKind(SyntaxKind.NumericLiteralExpression) == true; public bool IsTypeNamedVarInVariableOrFieldDeclaration(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent) { var typedToken = token; var typedParent = parent; if (typedParent.IsKind(SyntaxKind.IdentifierName)) { TypeSyntax? declaredType = null; if (typedParent.IsParentKind(SyntaxKind.VariableDeclaration, out VariableDeclarationSyntax? varDecl)) { declaredType = varDecl.Type; } else if (typedParent.IsParentKind(SyntaxKind.FieldDeclaration, out FieldDeclarationSyntax? fieldDecl)) { declaredType = fieldDecl.Declaration.Type; } return declaredType == typedParent && typedToken.ValueText == "var"; } return false; } public bool IsTypeNamedDynamic(SyntaxToken token, [NotNullWhen(true)] SyntaxNode? parent) { if (parent is ExpressionSyntax typedParent) { if (SyntaxFacts.IsInTypeOnlyContext(typedParent) && typedParent.IsKind(SyntaxKind.IdentifierName) && token.ValueText == "dynamic") { return true; } } return false; } public bool IsBindableToken(SyntaxToken token) { if (this.IsWord(token) || this.IsLiteral(token) || this.IsOperator(token)) { switch ((SyntaxKind)token.RawKind) { case SyntaxKind.DelegateKeyword: case SyntaxKind.VoidKeyword: return false; } return true; } // In the order by clause a comma might be bound to ThenBy or ThenByDescending if (token.Kind() == SyntaxKind.CommaToken && token.Parent.IsKind(SyntaxKind.OrderByClause)) { return true; } return false; } public void GetPartsOfConditionalAccessExpression( SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode whenNotNull) { var conditionalAccess = (ConditionalAccessExpressionSyntax)node; expression = conditionalAccess.Expression; operatorToken = conditionalAccess.OperatorToken; whenNotNull = conditionalAccess.WhenNotNull; } public bool IsPostfixUnaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is PostfixUnaryExpressionSyntax; public bool IsMemberBindingExpression([NotNullWhen(true)] SyntaxNode? node) => node is MemberBindingExpressionSyntax; public bool IsPointerMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node as MemberAccessExpressionSyntax)?.Kind() == SyntaxKind.PointerMemberAccessExpression; public void GetNameAndArityOfSimpleName(SyntaxNode? node, out string? name, out int arity) { name = null; arity = 0; if (node is SimpleNameSyntax simpleName) { name = simpleName.Identifier.ValueText; arity = simpleName.Arity; } } public bool LooksGeneric(SyntaxNode simpleName) => simpleName.IsKind(SyntaxKind.GenericName) || simpleName.GetLastToken().GetNextToken().Kind() == SyntaxKind.LessThanToken; public SyntaxNode? GetTargetOfMemberBinding(SyntaxNode? node) => (node as MemberBindingExpressionSyntax).GetParentConditionalAccessExpression()?.Expression; public SyntaxNode GetNameOfMemberBindingExpression(SyntaxNode node) => ((MemberBindingExpressionSyntax)node).Name; public SyntaxNode? GetExpressionOfMemberAccessExpression(SyntaxNode? node, bool allowImplicitTarget) => (node as MemberAccessExpressionSyntax)?.Expression; public void GetPartsOfElementAccessExpression(SyntaxNode? node, out SyntaxNode? expression, out SyntaxNode? argumentList) { var elementAccess = node as ElementAccessExpressionSyntax; expression = elementAccess?.Expression; argumentList = elementAccess?.ArgumentList; } public SyntaxNode? GetExpressionOfInterpolation(SyntaxNode? node) => (node as InterpolationSyntax)?.Expression; public bool IsInStaticContext(SyntaxNode node) => node.IsInStaticContext(); public bool IsInNamespaceOrTypeContext([NotNullWhen(true)] SyntaxNode? node) => SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax); public bool IsBaseTypeList([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.BaseList); public SyntaxNode? GetExpressionOfArgument(SyntaxNode? node) => (node as ArgumentSyntax)?.Expression; public RefKind GetRefKindOfArgument(SyntaxNode? node) => (node as ArgumentSyntax).GetRefKind(); public bool IsArgument([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Argument); public bool IsSimpleArgument([NotNullWhen(true)] SyntaxNode? node) { return node is ArgumentSyntax argument && argument.RefOrOutKeyword.Kind() == SyntaxKind.None && argument.NameColon == null; } public bool IsInConstantContext([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsInConstantContext(); public bool IsInConstructor(SyntaxNode node) => node.GetAncestor<ConstructorDeclarationSyntax>() != null; public bool IsUnsafeContext(SyntaxNode node) => node.IsUnsafeContext(); public SyntaxNode GetNameOfAttribute(SyntaxNode node) => ((AttributeSyntax)node).Name; public SyntaxNode GetExpressionOfParenthesizedExpression(SyntaxNode node) => ((ParenthesizedExpressionSyntax)node).Expression; public bool IsAttributeNamedArgumentIdentifier([NotNullWhen(true)] SyntaxNode? node) => (node as IdentifierNameSyntax).IsAttributeNamedArgumentIdentifier(); public SyntaxNode? GetContainingTypeDeclaration(SyntaxNode? root, int position) { if (root == null) { throw new ArgumentNullException(nameof(root)); } if (position < 0 || position > root.Span.End) { throw new ArgumentOutOfRangeException(nameof(position)); } return root .FindToken(position) .GetAncestors<SyntaxNode>() .FirstOrDefault(n => n is BaseTypeDeclarationSyntax || n is DelegateDeclarationSyntax); } public SyntaxNode? GetContainingVariableDeclaratorOfFieldDeclaration(SyntaxNode? node) => throw ExceptionUtilities.Unreachable; public SyntaxToken FindTokenOnLeftOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnLeftOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public SyntaxToken FindTokenOnRightOfPosition( SyntaxNode node, int position, bool includeSkipped, bool includeDirectives, bool includeDocumentationComments) { return node.FindTokenOnRightOfPosition(position, includeSkipped, includeDirectives, includeDocumentationComments); } public bool IsNameOfSubpattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IdentifierName) && node.IsParentKind(SyntaxKind.NameColon) && node.Parent.IsParentKind(SyntaxKind.Subpattern); public bool IsPropertyPatternClause(SyntaxNode node) => node.Kind() == SyntaxKind.PropertyPatternClause; public bool IsMemberInitializerNamedAssignmentIdentifier([NotNullWhen(true)] SyntaxNode? node) => IsMemberInitializerNamedAssignmentIdentifier(node, out _); public bool IsMemberInitializerNamedAssignmentIdentifier( [NotNullWhen(true)] SyntaxNode? node, [NotNullWhen(true)] out SyntaxNode? initializedInstance) { initializedInstance = null; if (node is IdentifierNameSyntax identifier && identifier.IsLeftSideOfAssignExpression()) { if (identifier.Parent.IsParentKind(SyntaxKind.WithInitializerExpression)) { var withInitializer = identifier.Parent.GetRequiredParent(); initializedInstance = withInitializer.GetRequiredParent(); return true; } else if (identifier.Parent.IsParentKind(SyntaxKind.ObjectInitializerExpression)) { var objectInitializer = identifier.Parent.GetRequiredParent(); if (objectInitializer.Parent is BaseObjectCreationExpressionSyntax) { initializedInstance = objectInitializer.Parent; return true; } else if (objectInitializer.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment)) { initializedInstance = assignment.Left; return true; } } } return false; } public bool IsElementAccessExpression(SyntaxNode? node) => node.IsKind(SyntaxKind.ElementAccessExpression); [return: NotNullIfNotNull("node")] public SyntaxNode? ConvertToSingleLine(SyntaxNode? node, bool useElasticTrivia = false) => node.ConvertToSingleLine(useElasticTrivia); public void GetPartsOfParenthesizedExpression( SyntaxNode node, out SyntaxToken openParen, out SyntaxNode expression, out SyntaxToken closeParen) { var parenthesizedExpression = (ParenthesizedExpressionSyntax)node; openParen = parenthesizedExpression.OpenParenToken; expression = parenthesizedExpression.Expression; closeParen = parenthesizedExpression.CloseParenToken; } public bool IsIndexerMemberCRef(SyntaxNode? node) => node.IsKind(SyntaxKind.IndexerMemberCref); public SyntaxNode? GetContainingMemberDeclaration(SyntaxNode? root, int position, bool useFullSpan = true) { Contract.ThrowIfNull(root, "root"); Contract.ThrowIfTrue(position < 0 || position > root.FullSpan.End, "position"); var end = root.FullSpan.End; if (end == 0) { // empty file return null; } // make sure position doesn't touch end of root position = Math.Min(position, end - 1); var node = root.FindToken(position).Parent; while (node != null) { if (useFullSpan || node.Span.Contains(position)) { var kind = node.Kind(); if ((kind != SyntaxKind.GlobalStatement) && (kind != SyntaxKind.IncompleteMember) && (node is MemberDeclarationSyntax)) { return node; } } node = node.Parent; } return null; } public bool IsMethodLevelMember([NotNullWhen(true)] SyntaxNode? node) { return node is BaseMethodDeclarationSyntax || node is BasePropertyDeclarationSyntax || node is EnumMemberDeclarationSyntax || node is BaseFieldDeclarationSyntax; } public bool IsTopLevelNodeWithMembers([NotNullWhen(true)] SyntaxNode? node) { return node is BaseNamespaceDeclarationSyntax || node is TypeDeclarationSyntax || node is EnumDeclarationSyntax; } private const string dotToken = "."; public string GetDisplayName(SyntaxNode? node, DisplayNameOptions options, string? rootNamespace = null) { if (node == null) { return string.Empty; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; // return type var memberDeclaration = node as MemberDeclarationSyntax; if ((options & DisplayNameOptions.IncludeType) != 0) { var type = memberDeclaration.GetMemberType(); if (type != null && !type.IsMissing) { builder.Append(type); builder.Append(' '); } } var names = ArrayBuilder<string?>.GetInstance(); // containing type(s) var parent = node.GetAncestor<TypeDeclarationSyntax>() ?? node.Parent; while (parent is TypeDeclarationSyntax) { names.Push(GetName(parent, options)); parent = parent.Parent; } // containing namespace(s) in source (if any) if ((options & DisplayNameOptions.IncludeNamespaces) != 0) { while (parent is BaseNamespaceDeclarationSyntax) { names.Add(GetName(parent, options)); parent = parent.Parent; } } while (!names.IsEmpty()) { var name = names.Pop(); if (name != null) { builder.Append(name); builder.Append(dotToken); } } // name (including generic type parameters) builder.Append(GetName(node, options)); // parameter list (if any) if ((options & DisplayNameOptions.IncludeParameters) != 0) { builder.Append(memberDeclaration.GetParameterList()); } return pooled.ToStringAndFree(); } private static string? GetName(SyntaxNode node, DisplayNameOptions options) { const string missingTokenPlaceholder = "?"; switch (node.Kind()) { case SyntaxKind.CompilationUnit: return null; case SyntaxKind.IdentifierName: var identifier = ((IdentifierNameSyntax)node).Identifier; return identifier.IsMissing ? missingTokenPlaceholder : identifier.Text; case SyntaxKind.IncompleteMember: return missingTokenPlaceholder; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return GetName(((BaseNamespaceDeclarationSyntax)node).Name, options); case SyntaxKind.QualifiedName: var qualified = (QualifiedNameSyntax)node; return GetName(qualified.Left, options) + dotToken + GetName(qualified.Right, options); } string? name = null; if (node is MemberDeclarationSyntax memberDeclaration) { if (memberDeclaration.Kind() == SyntaxKind.ConversionOperatorDeclaration) { name = (memberDeclaration as ConversionOperatorDeclarationSyntax)?.Type.ToString(); } else { var nameToken = memberDeclaration.GetNameToken(); if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; if (memberDeclaration.Kind() == SyntaxKind.DestructorDeclaration) { name = "~" + name; } if ((options & DisplayNameOptions.IncludeTypeParameters) != 0) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append(name); AppendTypeParameterList(builder, memberDeclaration.GetTypeParameterList()); name = pooled.ToStringAndFree(); } } else { Debug.Assert(memberDeclaration.Kind() == SyntaxKind.IncompleteMember); name = "?"; } } } else { if (node is VariableDeclaratorSyntax fieldDeclarator) { var nameToken = fieldDeclarator.Identifier; if (nameToken != default) { name = nameToken.IsMissing ? missingTokenPlaceholder : nameToken.Text; } } } Debug.Assert(name != null, "Unexpected node type " + node.Kind()); return name; } private static void AppendTypeParameterList(StringBuilder builder, TypeParameterListSyntax typeParameterList) { if (typeParameterList != null && typeParameterList.Parameters.Count > 0) { builder.Append('<'); builder.Append(typeParameterList.Parameters[0].Identifier.ValueText); for (var i = 1; i < typeParameterList.Parameters.Count; i++) { builder.Append(", "); builder.Append(typeParameterList.Parameters[i].Identifier.ValueText); } builder.Append('>'); } } public List<SyntaxNode> GetTopLevelAndMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: true, methodLevel: true); return list; } public List<SyntaxNode> GetMethodLevelMembers(SyntaxNode? root) { var list = new List<SyntaxNode>(); AppendMembers(root, list, topLevel: false, methodLevel: true); return list; } public bool IsClassDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Kind() == SyntaxKind.ClassDeclaration; public bool IsNamespaceDeclaration([NotNullWhen(true)] SyntaxNode? node) => node is BaseNamespaceDeclarationSyntax; public SyntaxNode? GetNameOfNamespaceDeclaration(SyntaxNode? node) => (node as BaseNamespaceDeclarationSyntax)?.Name; public SyntaxList<SyntaxNode> GetMembersOfTypeDeclaration(SyntaxNode typeDeclaration) => ((TypeDeclarationSyntax)typeDeclaration).Members; public SyntaxList<SyntaxNode> GetMembersOfNamespaceDeclaration(SyntaxNode namespaceDeclaration) => ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Members; public SyntaxList<SyntaxNode> GetMembersOfCompilationUnit(SyntaxNode compilationUnit) => ((CompilationUnitSyntax)compilationUnit).Members; public SyntaxList<SyntaxNode> GetImportsOfNamespaceDeclaration(SyntaxNode namespaceDeclaration) => ((BaseNamespaceDeclarationSyntax)namespaceDeclaration).Usings; public SyntaxList<SyntaxNode> GetImportsOfCompilationUnit(SyntaxNode compilationUnit) => ((CompilationUnitSyntax)compilationUnit).Usings; private void AppendMembers(SyntaxNode? node, List<SyntaxNode> list, bool topLevel, bool methodLevel) { Debug.Assert(topLevel || methodLevel); foreach (var member in node.GetMembers()) { if (IsTopLevelNodeWithMembers(member)) { if (topLevel) { list.Add(member); } AppendMembers(member, list, topLevel, methodLevel); continue; } if (methodLevel && IsMethodLevelMember(member)) { list.Add(member); } } } public TextSpan GetMemberBodySpanForSpeculativeBinding(SyntaxNode node) { if (node.Span.IsEmpty) { return default; } var member = GetContainingMemberDeclaration(node, node.SpanStart); if (member == null) { return default; } // TODO: currently we only support method for now if (member is BaseMethodDeclarationSyntax method) { if (method.Body == null) { return default; } return GetBlockBodySpan(method.Body); } return default; } public bool ContainsInMemberBody([NotNullWhen(true)] SyntaxNode? node, TextSpan span) { switch (node) { case ConstructorDeclarationSyntax constructor: return (constructor.Body != null && GetBlockBodySpan(constructor.Body).Contains(span)) || (constructor.Initializer != null && constructor.Initializer.Span.Contains(span)); case BaseMethodDeclarationSyntax method: return method.Body != null && GetBlockBodySpan(method.Body).Contains(span); case BasePropertyDeclarationSyntax property: return property.AccessorList != null && property.AccessorList.Span.Contains(span); case EnumMemberDeclarationSyntax @enum: return @enum.EqualsValue != null && @enum.EqualsValue.Span.Contains(span); case BaseFieldDeclarationSyntax field: return field.Declaration != null && field.Declaration.Span.Contains(span); } return false; } private static TextSpan GetBlockBodySpan(BlockSyntax body) => TextSpan.FromBounds(body.OpenBraceToken.Span.End, body.CloseBraceToken.SpanStart); public SyntaxNode? TryGetBindableParent(SyntaxToken token) { var node = token.Parent; while (node != null) { var parent = node.Parent; // If this node is on the left side of a member access expression, don't ascend // further or we'll end up binding to something else. if (parent is MemberAccessExpressionSyntax memberAccess) { if (memberAccess.Expression == node) { break; } } // If this node is on the left side of a qualified name, don't ascend // further or we'll end up binding to something else. if (parent is QualifiedNameSyntax qualifiedName) { if (qualifiedName.Left == node) { break; } } // If this node is on the left side of a alias-qualified name, don't ascend // further or we'll end up binding to something else. if (parent is AliasQualifiedNameSyntax aliasQualifiedName) { if (aliasQualifiedName.Alias == node) { break; } } // If this node is the type of an object creation expression, return the // object creation expression. if (parent is ObjectCreationExpressionSyntax objectCreation) { if (objectCreation.Type == node) { node = parent; break; } } // The inside of an interpolated string is treated as its own token so we // need to force navigation to the parent expression syntax. if (node is InterpolatedStringTextSyntax && parent is InterpolatedStringExpressionSyntax) { node = parent; break; } // If this node is not parented by a name, we're done. if (!(parent is NameSyntax)) { break; } node = parent; } if (node is VarPatternSyntax) { return node; } // Patterns are never bindable (though their constituent types/exprs may be). return node is PatternSyntax ? null : node; } public IEnumerable<SyntaxNode> GetConstructors(SyntaxNode? root, CancellationToken cancellationToken) { if (!(root is CompilationUnitSyntax compilationUnit)) { return SpecializedCollections.EmptyEnumerable<SyntaxNode>(); } var constructors = new List<SyntaxNode>(); AppendConstructors(compilationUnit.Members, constructors, cancellationToken); return constructors; } private void AppendConstructors(SyntaxList<MemberDeclarationSyntax> members, List<SyntaxNode> constructors, CancellationToken cancellationToken) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); switch (member) { case ConstructorDeclarationSyntax constructor: constructors.Add(constructor); continue; case BaseNamespaceDeclarationSyntax @namespace: AppendConstructors(@namespace.Members, constructors, cancellationToken); break; case ClassDeclarationSyntax @class: AppendConstructors(@class.Members, constructors, cancellationToken); break; case RecordDeclarationSyntax record: AppendConstructors(record.Members, constructors, cancellationToken); break; case StructDeclarationSyntax @struct: AppendConstructors(@struct.Members, constructors, cancellationToken); break; } } } public bool TryGetCorrespondingOpenBrace(SyntaxToken token, out SyntaxToken openBrace) { if (token.Kind() == SyntaxKind.CloseBraceToken) { var tuple = token.Parent.GetBraces(); openBrace = tuple.openBrace; return openBrace.Kind() == SyntaxKind.OpenBraceToken; } openBrace = default; return false; } public TextSpan GetInactiveRegionSpanAroundPosition(SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var trivia = syntaxTree.GetRoot(cancellationToken).FindTrivia(position, findInsideTrivia: false); if (trivia.Kind() == SyntaxKind.DisabledTextTrivia) { return trivia.FullSpan; } var token = syntaxTree.FindTokenOrEndToken(position, cancellationToken); if (token.Kind() == SyntaxKind.EndOfFileToken) { var triviaList = token.LeadingTrivia; foreach (var triviaTok in triviaList.Reverse()) { if (triviaTok.Span.Contains(position)) { return default; } if (triviaTok.Span.End < position) { if (!triviaTok.HasStructure) { return default; } var structure = triviaTok.GetStructure(); if (structure is BranchingDirectiveTriviaSyntax branch) { return !branch.IsActive || !branch.BranchTaken ? TextSpan.FromBounds(branch.FullSpan.Start, position) : default; } } } } return default; } public string GetNameForArgument(SyntaxNode? argument) => (argument as ArgumentSyntax)?.NameColon?.Name.Identifier.ValueText ?? string.Empty; public string GetNameForAttributeArgument(SyntaxNode? argument) => (argument as AttributeArgumentSyntax)?.NameEquals?.Name.Identifier.ValueText ?? string.Empty; public bool IsLeftSideOfDot([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfDot(); public SyntaxNode? GetRightSideOfDot(SyntaxNode? node) { return (node as QualifiedNameSyntax)?.Right ?? (node as MemberAccessExpressionSyntax)?.Name; } public SyntaxNode? GetLeftSideOfDot(SyntaxNode? node, bool allowImplicitTarget) { return (node as QualifiedNameSyntax)?.Left ?? (node as MemberAccessExpressionSyntax)?.Expression; } public bool IsLeftSideOfExplicitInterfaceSpecifier([NotNullWhen(true)] SyntaxNode? node) => (node as NameSyntax).IsLeftSideOfExplicitInterfaceSpecifier(); public bool IsLeftSideOfAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAssignExpression(); public bool IsLeftSideOfAnyAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfAnyAssignExpression(); public bool IsLeftSideOfCompoundAssignment([NotNullWhen(true)] SyntaxNode? node) => (node as ExpressionSyntax).IsLeftSideOfCompoundAssignExpression(); public SyntaxNode? GetRightHandSideOfAssignment(SyntaxNode? node) => (node as AssignmentExpressionSyntax)?.Right; public bool IsInferredAnonymousObjectMemberDeclarator([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AnonymousObjectMemberDeclarator, out AnonymousObjectMemberDeclaratorSyntax? anonObject) && anonObject.NameEquals == null; public bool IsOperandOfIncrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostIncrementExpression) || node.IsParentKind(SyntaxKind.PreIncrementExpression); public static bool IsOperandOfDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsParentKind(SyntaxKind.PostDecrementExpression) || node.IsParentKind(SyntaxKind.PreDecrementExpression); public bool IsOperandOfIncrementOrDecrementExpression([NotNullWhen(true)] SyntaxNode? node) => IsOperandOfIncrementExpression(node) || IsOperandOfDecrementExpression(node); public SyntaxList<SyntaxNode> GetContentsOfInterpolatedString(SyntaxNode interpolatedString) => ((InterpolatedStringExpressionSyntax)interpolatedString).Contents; public bool IsVerbatimStringLiteral(SyntaxToken token) => token.IsVerbatimStringLiteral(); public bool IsNumericLiteral(SyntaxToken token) => token.Kind() == SyntaxKind.NumericLiteralToken; public void GetPartsOfInvocationExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxNode argumentList) { var invocation = (InvocationExpressionSyntax)node; expression = invocation.Expression; argumentList = invocation.ArgumentList; } public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfInvocationExpression(SyntaxNode? invocationExpression) => GetArgumentsOfArgumentList((invocationExpression as InvocationExpressionSyntax)?.ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfObjectCreationExpression(SyntaxNode? objectCreationExpression) => GetArgumentsOfArgumentList((objectCreationExpression as BaseObjectCreationExpressionSyntax)?.ArgumentList); public SeparatedSyntaxList<SyntaxNode> GetArgumentsOfArgumentList(SyntaxNode? argumentList) => (argumentList as BaseArgumentListSyntax)?.Arguments ?? default; public SyntaxNode GetArgumentListOfInvocationExpression(SyntaxNode invocationExpression) => ((InvocationExpressionSyntax)invocationExpression).ArgumentList; public SyntaxNode? GetArgumentListOfObjectCreationExpression(SyntaxNode objectCreationExpression) => ((ObjectCreationExpressionSyntax)objectCreationExpression)!.ArgumentList; public bool IsRegularComment(SyntaxTrivia trivia) => trivia.IsRegularComment(); public bool IsDocumentationComment(SyntaxTrivia trivia) => trivia.IsDocComment(); public bool IsElastic(SyntaxTrivia trivia) => trivia.IsElastic(); public bool IsPragmaDirective(SyntaxTrivia trivia, out bool isDisable, out bool isActive, out SeparatedSyntaxList<SyntaxNode> errorCodes) => trivia.IsPragmaDirective(out isDisable, out isActive, out errorCodes); public bool IsDocumentationCommentExteriorTrivia(SyntaxTrivia trivia) => trivia.Kind() == SyntaxKind.DocumentationCommentExteriorTrivia; public bool IsDocumentationComment(SyntaxNode node) => SyntaxFacts.IsDocumentationCommentTrivia(node.Kind()); public bool IsUsingOrExternOrImport([NotNullWhen(true)] SyntaxNode? node) { return node.IsKind(SyntaxKind.UsingDirective) || node.IsKind(SyntaxKind.ExternAliasDirective); } public bool IsGlobalAssemblyAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.AssemblyKeyword); public bool IsGlobalModuleAttribute([NotNullWhen(true)] SyntaxNode? node) => IsGlobalAttribute(node, SyntaxKind.ModuleKeyword); private static bool IsGlobalAttribute([NotNullWhen(true)] SyntaxNode? node, SyntaxKind attributeTarget) => node.IsKind(SyntaxKind.Attribute) && node.Parent.IsKind(SyntaxKind.AttributeList, out AttributeListSyntax? attributeList) && attributeList.Target?.Identifier.Kind() == attributeTarget; private static bool IsMemberDeclaration(SyntaxNode node) { // From the C# language spec: // class-member-declaration: // constant-declaration // field-declaration // method-declaration // property-declaration // event-declaration // indexer-declaration // operator-declaration // constructor-declaration // destructor-declaration // static-constructor-declaration // type-declaration switch (node.Kind()) { // Because fields declarations can define multiple symbols "public int a, b;" // We want to get the VariableDeclarator node inside the field declaration to print out the symbol for the name. case SyntaxKind.VariableDeclarator: return node.Parent.IsParentKind(SyntaxKind.FieldDeclaration) || node.Parent.IsParentKind(SyntaxKind.EventFieldDeclaration); case SyntaxKind.FieldDeclaration: case SyntaxKind.MethodDeclaration: case SyntaxKind.PropertyDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.IndexerDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return true; default: return false; } } public bool IsDeclaration(SyntaxNode node) => SyntaxFacts.IsNamespaceMemberDeclaration(node.Kind()) || IsMemberDeclaration(node); public bool IsTypeDeclaration(SyntaxNode node) => SyntaxFacts.IsTypeDeclaration(node.Kind()); public SyntaxNode? GetObjectCreationInitializer(SyntaxNode node) => ((ObjectCreationExpressionSyntax)node).Initializer; public SyntaxNode GetObjectCreationType(SyntaxNode node) => ((ObjectCreationExpressionSyntax)node).Type; public bool IsSimpleAssignmentStatement([NotNullWhen(true)] SyntaxNode? statement) => statement.IsKind(SyntaxKind.ExpressionStatement, out ExpressionStatementSyntax? exprStatement) && exprStatement.Expression.IsKind(SyntaxKind.SimpleAssignmentExpression); public void GetPartsOfAssignmentStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { GetPartsOfAssignmentExpressionOrStatement( ((ExpressionStatementSyntax)statement).Expression, out left, out operatorToken, out right); } public void GetPartsOfAssignmentExpressionOrStatement( SyntaxNode statement, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var expression = statement; if (statement is ExpressionStatementSyntax expressionStatement) { expression = expressionStatement.Expression; } var assignment = (AssignmentExpressionSyntax)expression; left = assignment.Left; operatorToken = assignment.OperatorToken; right = assignment.Right; } public SyntaxNode GetNameOfMemberAccessExpression(SyntaxNode memberAccessExpression) => ((MemberAccessExpressionSyntax)memberAccessExpression).Name; public void GetPartsOfMemberAccessExpression(SyntaxNode node, out SyntaxNode expression, out SyntaxToken operatorToken, out SyntaxNode name) { var memberAccess = (MemberAccessExpressionSyntax)node; expression = memberAccess.Expression; operatorToken = memberAccess.OperatorToken; name = memberAccess.Name; } public SyntaxToken GetIdentifierOfSimpleName(SyntaxNode node) => ((SimpleNameSyntax)node).Identifier; public SyntaxToken GetIdentifierOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Identifier; public SyntaxToken GetIdentifierOfParameter(SyntaxNode node) => ((ParameterSyntax)node).Identifier; public SyntaxToken GetIdentifierOfIdentifierName(SyntaxNode node) => ((IdentifierNameSyntax)node).Identifier; public bool IsLocalFunctionStatement([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.LocalFunctionStatement); public bool IsDeclaratorOfLocalDeclarationStatement(SyntaxNode declarator, SyntaxNode localDeclarationStatement) { return ((LocalDeclarationStatementSyntax)localDeclarationStatement).Declaration.Variables.Contains( (VariableDeclaratorSyntax)declarator); } public bool AreEquivalent(SyntaxToken token1, SyntaxToken token2) => SyntaxFactory.AreEquivalent(token1, token2); public bool AreEquivalent(SyntaxNode? node1, SyntaxNode? node2) => SyntaxFactory.AreEquivalent(node1, node2); public bool IsExpressionOfInvocationExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as InvocationExpressionSyntax)?.Expression == node; public bool IsExpressionOfAwaitExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as AwaitExpressionSyntax)?.Expression == node; public bool IsExpressionOfMemberAccessExpression([NotNullWhen(true)] SyntaxNode? node) => (node?.Parent as MemberAccessExpressionSyntax)?.Expression == node; public static SyntaxNode GetExpressionOfInvocationExpression(SyntaxNode node) => ((InvocationExpressionSyntax)node).Expression; public SyntaxNode GetExpressionOfAwaitExpression(SyntaxNode node) => ((AwaitExpressionSyntax)node).Expression; public bool IsExpressionOfForeach([NotNullWhen(true)] SyntaxNode? node) => node?.Parent is ForEachStatementSyntax foreachStatement && foreachStatement.Expression == node; public SyntaxNode GetExpressionOfExpressionStatement(SyntaxNode node) => ((ExpressionStatementSyntax)node).Expression; public bool IsBinaryExpression([NotNullWhen(true)] SyntaxNode? node) => node is BinaryExpressionSyntax; public bool IsIsExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsExpression); public void GetPartsOfBinaryExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryExpression = (BinaryExpressionSyntax)node; left = binaryExpression.Left; operatorToken = binaryExpression.OperatorToken; right = binaryExpression.Right; } public void GetPartsOfConditionalExpression(SyntaxNode node, out SyntaxNode condition, out SyntaxNode whenTrue, out SyntaxNode whenFalse) { var conditionalExpression = (ConditionalExpressionSyntax)node; condition = conditionalExpression.Condition; whenTrue = conditionalExpression.WhenTrue; whenFalse = conditionalExpression.WhenFalse; } [return: NotNullIfNotNull("node")] public SyntaxNode? WalkDownParentheses(SyntaxNode? node) => (node as ExpressionSyntax)?.WalkDownParentheses() ?? node; public void GetPartsOfTupleExpression<TArgumentSyntax>(SyntaxNode node, out SyntaxToken openParen, out SeparatedSyntaxList<TArgumentSyntax> arguments, out SyntaxToken closeParen) where TArgumentSyntax : SyntaxNode { var tupleExpression = (TupleExpressionSyntax)node; openParen = tupleExpression.OpenParenToken; arguments = (SeparatedSyntaxList<TArgumentSyntax>)(SeparatedSyntaxList<SyntaxNode>)tupleExpression.Arguments; closeParen = tupleExpression.CloseParenToken; } public SyntaxNode GetOperandOfPrefixUnaryExpression(SyntaxNode node) => ((PrefixUnaryExpressionSyntax)node).Operand; public SyntaxToken GetOperatorTokenOfPrefixUnaryExpression(SyntaxNode node) => ((PrefixUnaryExpressionSyntax)node).OperatorToken; public SyntaxNode? GetNextExecutableStatement(SyntaxNode statement) => ((StatementSyntax)statement).GetNextStatement(); public override bool IsSingleLineCommentTrivia(SyntaxTrivia trivia) => trivia.IsSingleLineComment(); public override bool IsMultiLineCommentTrivia(SyntaxTrivia trivia) => trivia.IsMultiLineComment(); public override bool IsSingleLineDocCommentTrivia(SyntaxTrivia trivia) => trivia.IsSingleLineDocComment(); public override bool IsMultiLineDocCommentTrivia(SyntaxTrivia trivia) => trivia.IsMultiLineDocComment(); public override bool IsShebangDirectiveTrivia(SyntaxTrivia trivia) => trivia.IsShebangDirective(); public override bool IsPreprocessorDirective(SyntaxTrivia trivia) => SyntaxFacts.IsPreprocessorDirective(trivia.Kind()); public bool IsOnTypeHeader(SyntaxNode root, int position, bool fullHeader, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) { var node = TryGetAncestorForLocation<BaseTypeDeclarationSyntax>(root, position); typeDeclaration = node; if (node == null) return false; var lastToken = (node as TypeDeclarationSyntax)?.TypeParameterList?.GetLastToken() ?? node.Identifier; if (fullHeader) lastToken = node.BaseList?.GetLastToken() ?? lastToken; return IsOnHeader(root, position, node, lastToken); } public bool IsOnPropertyDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? propertyDeclaration) { var node = TryGetAncestorForLocation<PropertyDeclarationSyntax>(root, position); propertyDeclaration = node; if (propertyDeclaration == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.Identifier); } public bool IsOnParameterHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? parameter) { var node = TryGetAncestorForLocation<ParameterSyntax>(root, position); parameter = node; if (parameter == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node); } public bool IsOnMethodHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? method) { var node = TryGetAncestorForLocation<MethodDeclarationSyntax>(root, position); method = node; if (method == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.ParameterList); } public bool IsOnLocalFunctionHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localFunction) { var node = TryGetAncestorForLocation<LocalFunctionStatementSyntax>(root, position); localFunction = node; if (localFunction == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.ParameterList); } public bool IsOnLocalDeclarationHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? localDeclaration) { var node = TryGetAncestorForLocation<LocalDeclarationStatementSyntax>(root, position); localDeclaration = node; if (localDeclaration == null) { return false; } var initializersExpressions = node!.Declaration.Variables .Where(v => v.Initializer != null) .SelectAsArray(initializedV => initializedV.Initializer!.Value); return IsOnHeader(root, position, node, node, holes: initializersExpressions); } public bool IsOnIfStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? ifStatement) { var node = TryGetAncestorForLocation<IfStatementSyntax>(root, position); ifStatement = node; if (ifStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsOnWhileStatementHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? whileStatement) { var node = TryGetAncestorForLocation<WhileStatementSyntax>(root, position); whileStatement = node; if (whileStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsOnForeachHeader(SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? foreachStatement) { var node = TryGetAncestorForLocation<ForEachStatementSyntax>(root, position); foreachStatement = node; if (foreachStatement == null) { return false; } RoslynDebug.AssertNotNull(node); return IsOnHeader(root, position, node, node.CloseParenToken); } public bool IsBetweenTypeMembers(SourceText sourceText, SyntaxNode root, int position, [NotNullWhen(true)] out SyntaxNode? typeDeclaration) { var token = root.FindToken(position); var typeDecl = token.GetAncestor<TypeDeclarationSyntax>(); typeDeclaration = typeDecl; if (typeDecl == null) { return false; } RoslynDebug.AssertNotNull(typeDeclaration); if (position < typeDecl.OpenBraceToken.Span.End || position > typeDecl.CloseBraceToken.Span.Start) { return false; } var line = sourceText.Lines.GetLineFromPosition(position); if (!line.IsEmptyOrWhitespace()) { return false; } var member = typeDecl.Members.FirstOrDefault(d => d.FullSpan.Contains(position)); if (member == null) { // There are no members, or we're after the last member. return true; } else { // We're within a member. Make sure we're in the leading whitespace of // the member. if (position < member.SpanStart) { foreach (var trivia in member.GetLeadingTrivia()) { if (!trivia.IsWhitespaceOrEndOfLine()) { return false; } if (trivia.FullSpan.Contains(position)) { return true; } } } } return false; } protected override bool ContainsInterleavedDirective(TextSpan span, SyntaxToken token, CancellationToken cancellationToken) => token.ContainsInterleavedDirective(span, cancellationToken); public SyntaxTokenList GetModifiers(SyntaxNode? node) => node.GetModifiers(); public SyntaxNode? WithModifiers(SyntaxNode? node, SyntaxTokenList modifiers) => node.WithModifiers(modifiers); public bool IsLiteralExpression([NotNullWhen(true)] SyntaxNode? node) => node is LiteralExpressionSyntax; public SeparatedSyntaxList<SyntaxNode> GetVariablesOfLocalDeclarationStatement(SyntaxNode node) => ((LocalDeclarationStatementSyntax)node).Declaration.Variables; public SyntaxNode? GetInitializerOfVariableDeclarator(SyntaxNode node) => ((VariableDeclaratorSyntax)node).Initializer; public SyntaxNode GetTypeOfVariableDeclarator(SyntaxNode node) => ((VariableDeclarationSyntax)((VariableDeclaratorSyntax)node).Parent!).Type; public SyntaxNode? GetValueOfEqualsValueClause(SyntaxNode? node) => ((EqualsValueClauseSyntax?)node)?.Value; public bool IsScopeBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block); public bool IsExecutableBlock([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.Block, SyntaxKind.SwitchSection, SyntaxKind.CompilationUnit); public IReadOnlyList<SyntaxNode> GetExecutableBlockStatements(SyntaxNode? node) { return node switch { BlockSyntax block => block.Statements, SwitchSectionSyntax switchSection => switchSection.Statements, CompilationUnitSyntax compilationUnit => compilationUnit.Members.OfType<GlobalStatementSyntax>().SelectAsArray(globalStatement => globalStatement.Statement), _ => throw ExceptionUtilities.UnexpectedValue(node), }; } public SyntaxNode? FindInnermostCommonExecutableBlock(IEnumerable<SyntaxNode> nodes) => nodes.FindInnermostCommonNode(node => IsExecutableBlock(node)); public bool IsStatementContainer([NotNullWhen(true)] SyntaxNode? node) => IsExecutableBlock(node) || node.IsEmbeddedStatementOwner(); public IReadOnlyList<SyntaxNode> GetStatementContainerStatements(SyntaxNode? node) { if (IsExecutableBlock(node)) return GetExecutableBlockStatements(node); else if (node.GetEmbeddedStatement() is { } embeddedStatement) return ImmutableArray.Create<SyntaxNode>(embeddedStatement); else return ImmutableArray<SyntaxNode>.Empty; } public bool IsConversionExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public bool IsCastExpression([NotNullWhen(true)] SyntaxNode? node) => node is CastExpressionSyntax; public void GetPartsOfCastExpression(SyntaxNode node, out SyntaxNode type, out SyntaxNode expression) { var cast = (CastExpressionSyntax)node; type = cast.Type; expression = cast.Expression; } public SyntaxToken? GetDeclarationIdentifierIfOverride(SyntaxToken token) { if (token.Kind() == SyntaxKind.OverrideKeyword && token.Parent is MemberDeclarationSyntax member) { return member.GetNameToken(); } return null; } public override SyntaxList<SyntaxNode> GetAttributeLists(SyntaxNode? node) => node.GetAttributeLists(); public override bool IsParameterNameXmlElementSyntax([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.XmlElement, out XmlElementSyntax? xmlElement) && xmlElement.StartTag.Name.LocalName.ValueText == DocumentationCommentXmlNames.ParameterElementName; public override SyntaxList<SyntaxNode> GetContentFromDocumentationCommentTriviaSyntax(SyntaxTrivia trivia) { if (trivia.GetStructure() is DocumentationCommentTriviaSyntax documentationCommentTrivia) { return documentationCommentTrivia.Content; } throw ExceptionUtilities.UnexpectedValue(trivia.Kind()); } public override bool CanHaveAccessibility(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.DelegateDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: return true; case SyntaxKind.VariableDeclaration: case SyntaxKind.VariableDeclarator: var declarationKind = this.GetDeclarationKind(declaration); return declarationKind == DeclarationKind.Field || declarationKind == DeclarationKind.Event; case SyntaxKind.ConstructorDeclaration: // Static constructor can't have accessibility return !((ConstructorDeclarationSyntax)declaration).Modifiers.Any(SyntaxKind.StaticKeyword); case SyntaxKind.PropertyDeclaration: return ((PropertyDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.IndexerDeclaration: return ((IndexerDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; case SyntaxKind.MethodDeclaration: var method = (MethodDeclarationSyntax)declaration; if (method.ExplicitInterfaceSpecifier != null) { // explicit interface methods can't have accessibility. return false; } if (method.Modifiers.Any(SyntaxKind.PartialKeyword)) { // partial methods can't have accessibility modifiers. return false; } return true; case SyntaxKind.EventDeclaration: return ((EventDeclarationSyntax)declaration).ExplicitInterfaceSpecifier == null; default: return false; } } public override Accessibility GetAccessibility(SyntaxNode declaration) { if (!CanHaveAccessibility(declaration)) { return Accessibility.NotApplicable; } var modifierTokens = GetModifierTokens(declaration); GetAccessibilityAndModifiers(modifierTokens, out var accessibility, out _, out _); return accessibility; } public override void GetAccessibilityAndModifiers(SyntaxTokenList modifierList, out Accessibility accessibility, out DeclarationModifiers modifiers, out bool isDefault) { accessibility = Accessibility.NotApplicable; modifiers = DeclarationModifiers.None; isDefault = false; foreach (var token in modifierList) { accessibility = (token.Kind(), accessibility) switch { (SyntaxKind.PublicKeyword, _) => Accessibility.Public, (SyntaxKind.PrivateKeyword, Accessibility.Protected) => Accessibility.ProtectedAndInternal, (SyntaxKind.PrivateKeyword, _) => Accessibility.Private, (SyntaxKind.InternalKeyword, Accessibility.Protected) => Accessibility.ProtectedOrInternal, (SyntaxKind.InternalKeyword, _) => Accessibility.Internal, (SyntaxKind.ProtectedKeyword, Accessibility.Private) => Accessibility.ProtectedAndInternal, (SyntaxKind.ProtectedKeyword, Accessibility.Internal) => Accessibility.ProtectedOrInternal, (SyntaxKind.ProtectedKeyword, _) => Accessibility.Protected, _ => accessibility, }; modifiers |= token.Kind() switch { SyntaxKind.AbstractKeyword => DeclarationModifiers.Abstract, SyntaxKind.NewKeyword => DeclarationModifiers.New, SyntaxKind.OverrideKeyword => DeclarationModifiers.Override, SyntaxKind.VirtualKeyword => DeclarationModifiers.Virtual, SyntaxKind.StaticKeyword => DeclarationModifiers.Static, SyntaxKind.AsyncKeyword => DeclarationModifiers.Async, SyntaxKind.ConstKeyword => DeclarationModifiers.Const, SyntaxKind.ReadOnlyKeyword => DeclarationModifiers.ReadOnly, SyntaxKind.SealedKeyword => DeclarationModifiers.Sealed, SyntaxKind.UnsafeKeyword => DeclarationModifiers.Unsafe, SyntaxKind.PartialKeyword => DeclarationModifiers.Partial, SyntaxKind.RefKeyword => DeclarationModifiers.Ref, SyntaxKind.VolatileKeyword => DeclarationModifiers.Volatile, SyntaxKind.ExternKeyword => DeclarationModifiers.Extern, _ => DeclarationModifiers.None, }; isDefault |= token.Kind() == SyntaxKind.DefaultKeyword; } } public override SyntaxTokenList GetModifierTokens(SyntaxNode? declaration) => declaration switch { MemberDeclarationSyntax memberDecl => memberDecl.Modifiers, ParameterSyntax parameter => parameter.Modifiers, LocalDeclarationStatementSyntax localDecl => localDecl.Modifiers, LocalFunctionStatementSyntax localFunc => localFunc.Modifiers, AccessorDeclarationSyntax accessor => accessor.Modifiers, VariableDeclarationSyntax varDecl => GetModifierTokens(varDecl.Parent), VariableDeclaratorSyntax varDecl => GetModifierTokens(varDecl.Parent), AnonymousFunctionExpressionSyntax anonymous => anonymous.Modifiers, _ => default, }; public override DeclarationKind GetDeclarationKind(SyntaxNode declaration) { switch (declaration.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.RecordDeclaration: return DeclarationKind.Class; case SyntaxKind.StructDeclaration: case SyntaxKind.RecordStructDeclaration: return DeclarationKind.Struct; case SyntaxKind.InterfaceDeclaration: return DeclarationKind.Interface; case SyntaxKind.EnumDeclaration: return DeclarationKind.Enum; case SyntaxKind.DelegateDeclaration: return DeclarationKind.Delegate; case SyntaxKind.MethodDeclaration: return DeclarationKind.Method; case SyntaxKind.OperatorDeclaration: return DeclarationKind.Operator; case SyntaxKind.ConversionOperatorDeclaration: return DeclarationKind.ConversionOperator; case SyntaxKind.ConstructorDeclaration: return DeclarationKind.Constructor; case SyntaxKind.DestructorDeclaration: return DeclarationKind.Destructor; case SyntaxKind.PropertyDeclaration: return DeclarationKind.Property; case SyntaxKind.IndexerDeclaration: return DeclarationKind.Indexer; case SyntaxKind.EventDeclaration: return DeclarationKind.CustomEvent; case SyntaxKind.EnumMemberDeclaration: return DeclarationKind.EnumMember; case SyntaxKind.CompilationUnit: return DeclarationKind.CompilationUnit; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: return DeclarationKind.Namespace; case SyntaxKind.UsingDirective: return DeclarationKind.NamespaceImport; case SyntaxKind.Parameter: return DeclarationKind.Parameter; case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return DeclarationKind.LambdaExpression; case SyntaxKind.FieldDeclaration: var fd = (FieldDeclarationSyntax)declaration; if (fd.Declaration != null && fd.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Field; } else { return DeclarationKind.None; } case SyntaxKind.EventFieldDeclaration: var ef = (EventFieldDeclarationSyntax)declaration; if (ef.Declaration != null && ef.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Event; } else { return DeclarationKind.None; } case SyntaxKind.LocalDeclarationStatement: var ld = (LocalDeclarationStatementSyntax)declaration; if (ld.Declaration != null && ld.Declaration.Variables.Count == 1) { // this node is considered the declaration if it contains only one variable. return DeclarationKind.Variable; } else { return DeclarationKind.None; } case SyntaxKind.VariableDeclaration: { var vd = (VariableDeclarationSyntax)declaration; if (vd.Variables.Count == 1 && vd.Parent == null) { // this node is the declaration if it contains only one variable and has no parent. return DeclarationKind.Variable; } else { return DeclarationKind.None; } } case SyntaxKind.VariableDeclarator: { var vd = declaration.Parent as VariableDeclarationSyntax; // this node is considered the declaration if it is one among many, or it has no parent if (vd == null || vd.Variables.Count > 1) { if (ParentIsFieldDeclaration(vd)) { return DeclarationKind.Field; } else if (ParentIsEventFieldDeclaration(vd)) { return DeclarationKind.Event; } else { return DeclarationKind.Variable; } } break; } case SyntaxKind.AttributeList: var list = (AttributeListSyntax)declaration; if (list.Attributes.Count == 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.Attribute: if (!(declaration.Parent is AttributeListSyntax parentList) || parentList.Attributes.Count > 1) { return DeclarationKind.Attribute; } break; case SyntaxKind.GetAccessorDeclaration: return DeclarationKind.GetAccessor; case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.InitAccessorDeclaration: return DeclarationKind.SetAccessor; case SyntaxKind.AddAccessorDeclaration: return DeclarationKind.AddAccessor; case SyntaxKind.RemoveAccessorDeclaration: return DeclarationKind.RemoveAccessor; } return DeclarationKind.None; } internal static bool ParentIsFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.FieldDeclaration) ?? false; internal static bool ParentIsEventFieldDeclaration([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.EventFieldDeclaration) ?? false; internal static bool ParentIsLocalDeclarationStatement([NotNullWhen(true)] SyntaxNode? node) => node?.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) ?? false; public bool IsIsPatternExpression([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.IsPatternExpression); public void GetPartsOfIsPatternExpression(SyntaxNode node, out SyntaxNode left, out SyntaxToken isToken, out SyntaxNode right) { var isPatternExpression = (IsPatternExpressionSyntax)node; left = isPatternExpression.Expression; isToken = isPatternExpression.IsKeyword; right = isPatternExpression.Pattern; } public bool IsAnyPattern([NotNullWhen(true)] SyntaxNode? node) => node is PatternSyntax; public bool IsConstantPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ConstantPattern); public bool IsDeclarationPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.DeclarationPattern); public bool IsRecursivePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.RecursivePattern); public bool IsVarPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.VarPattern); public SyntaxNode GetExpressionOfConstantPattern(SyntaxNode node) => ((ConstantPatternSyntax)node).Expression; public void GetPartsOfDeclarationPattern(SyntaxNode node, out SyntaxNode type, out SyntaxNode designation) { var declarationPattern = (DeclarationPatternSyntax)node; type = declarationPattern.Type; designation = declarationPattern.Designation; } public void GetPartsOfRecursivePattern(SyntaxNode node, out SyntaxNode? type, out SyntaxNode? positionalPart, out SyntaxNode? propertyPart, out SyntaxNode? designation) { var recursivePattern = (RecursivePatternSyntax)node; type = recursivePattern.Type; positionalPart = recursivePattern.PositionalPatternClause; propertyPart = recursivePattern.PropertyPatternClause; designation = recursivePattern.Designation; } public bool SupportsNotPattern(ParseOptions options) => ((CSharpParseOptions)options).LanguageVersion.IsCSharp9OrAbove(); public bool IsAndPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.AndPattern); public bool IsBinaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is BinaryPatternSyntax; public bool IsNotPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.NotPattern); public bool IsOrPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.OrPattern); public bool IsParenthesizedPattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ParenthesizedPattern); public bool IsTypePattern([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.TypePattern); public bool IsUnaryPattern([NotNullWhen(true)] SyntaxNode? node) => node is UnaryPatternSyntax; public void GetPartsOfParenthesizedPattern(SyntaxNode node, out SyntaxToken openParen, out SyntaxNode pattern, out SyntaxToken closeParen) { var parenthesizedPattern = (ParenthesizedPatternSyntax)node; openParen = parenthesizedPattern.OpenParenToken; pattern = parenthesizedPattern.Pattern; closeParen = parenthesizedPattern.CloseParenToken; } public void GetPartsOfBinaryPattern(SyntaxNode node, out SyntaxNode left, out SyntaxToken operatorToken, out SyntaxNode right) { var binaryPattern = (BinaryPatternSyntax)node; left = binaryPattern.Left; operatorToken = binaryPattern.OperatorToken; right = binaryPattern.Right; } public void GetPartsOfUnaryPattern(SyntaxNode node, out SyntaxToken operatorToken, out SyntaxNode pattern) { var unaryPattern = (UnaryPatternSyntax)node; operatorToken = unaryPattern.OperatorToken; pattern = unaryPattern.Pattern; } public SyntaxNode GetTypeOfTypePattern(SyntaxNode node) => ((TypePatternSyntax)node).Type; public bool IsImplicitObjectCreation([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ImplicitObjectCreationExpression); public SyntaxNode GetExpressionOfThrowExpression(SyntaxNode throwExpression) => ((ThrowExpressionSyntax)throwExpression).Expression; public bool IsThrowStatement([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.ThrowStatement); public bool IsLocalFunction([NotNullWhen(true)] SyntaxNode? node) => node.IsKind(SyntaxKind.LocalFunctionStatement); public void GetPartsOfInterpolationExpression(SyntaxNode node, out SyntaxToken stringStartToken, out SyntaxList<SyntaxNode> contents, out SyntaxToken stringEndToken) { var interpolatedStringExpression = (InterpolatedStringExpressionSyntax)node; stringStartToken = interpolatedStringExpression.StringStartToken; contents = interpolatedStringExpression.Contents; stringEndToken = interpolatedStringExpression.StringEndToken; } public bool IsVerbatimInterpolatedStringExpression(SyntaxNode node) => node is InterpolatedStringExpressionSyntax interpolatedString && interpolatedString.StringStartToken.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken); } }
1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/RegexTree.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.EmbeddedLanguages.Common; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions { internal sealed class RegexTree : EmbeddedSyntaxTree<RegexKind, RegexNode, RegexCompilationUnit> { public readonly ImmutableDictionary<string, TextSpan> CaptureNamesToSpan; public readonly ImmutableDictionary<int, TextSpan> CaptureNumbersToSpan; public RegexTree( VirtualCharSequence text, RegexCompilationUnit root, ImmutableArray<EmbeddedDiagnostic> diagnostics, ImmutableDictionary<string, TextSpan> captureNamesToSpan, ImmutableDictionary<int, TextSpan> captureNumbersToSpan) : base(text, root, diagnostics) { CaptureNamesToSpan = captureNamesToSpan; CaptureNumbersToSpan = captureNumbersToSpan; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.EmbeddedLanguages.Common; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions { internal sealed class RegexTree : EmbeddedSyntaxTree<RegexKind, RegexNode, RegexCompilationUnit> { public readonly ImmutableDictionary<string, TextSpan> CaptureNamesToSpan; public readonly ImmutableDictionary<int, TextSpan> CaptureNumbersToSpan; public RegexTree( VirtualCharSequence text, RegexCompilationUnit root, ImmutableArray<EmbeddedDiagnostic> diagnostics, ImmutableDictionary<string, TextSpan> captureNamesToSpan, ImmutableDictionary<int, TextSpan> captureNumbersToSpan) : base(text, root, diagnostics) { CaptureNamesToSpan = captureNamesToSpan; CaptureNumbersToSpan = captureNumbersToSpan; } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/MetadataReader/TypeAttributesExtensions.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.Reflection; using System.Runtime.InteropServices; namespace Microsoft.CodeAnalysis { internal static class TypeAttributesExtensions { public static bool IsInterface(this TypeAttributes flags) { return (flags & TypeAttributes.Interface) != 0; } public static bool IsWindowsRuntime(this TypeAttributes flags) { return (flags & TypeAttributes.WindowsRuntime) != 0; } public static bool IsPublic(this TypeAttributes flags) { return (flags & TypeAttributes.Public) != 0; } public static bool IsSpecialName(this TypeAttributes flags) { return (flags & TypeAttributes.SpecialName) != 0; } /// <summary> /// Extracts <see cref="CharSet"/> information from TypeDef flags. /// Returns 0 if the value is invalid. /// </summary> internal static CharSet ToCharSet(this TypeAttributes flags) { switch (flags & TypeAttributes.StringFormatMask) { case TypeAttributes.AutoClass: return Cci.Constants.CharSet_Auto; case TypeAttributes.AnsiClass: return CharSet.Ansi; case TypeAttributes.UnicodeClass: return CharSet.Unicode; default: return 0; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Reflection; using System.Runtime.InteropServices; namespace Microsoft.CodeAnalysis { internal static class TypeAttributesExtensions { public static bool IsInterface(this TypeAttributes flags) { return (flags & TypeAttributes.Interface) != 0; } public static bool IsWindowsRuntime(this TypeAttributes flags) { return (flags & TypeAttributes.WindowsRuntime) != 0; } public static bool IsPublic(this TypeAttributes flags) { return (flags & TypeAttributes.Public) != 0; } public static bool IsSpecialName(this TypeAttributes flags) { return (flags & TypeAttributes.SpecialName) != 0; } /// <summary> /// Extracts <see cref="CharSet"/> information from TypeDef flags. /// Returns 0 if the value is invalid. /// </summary> internal static CharSet ToCharSet(this TypeAttributes flags) { switch (flags & TypeAttributes.StringFormatMask) { case TypeAttributes.AutoClass: return Cci.Constants.CharSet_Auto; case TypeAttributes.AnsiClass: return CharSet.Ansi; case TypeAttributes.UnicodeClass: return CharSet.Unicode; default: return 0; } } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Emit/EditAndContinue/SymbolChange.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; namespace Microsoft.CodeAnalysis.Emit { internal enum SymbolChange { /// <summary> /// No change to symbol or members. /// </summary> None = 0, /// <summary> /// No change to symbol but may contain changed symbols. /// </summary> ContainsChanges, /// <summary> /// Symbol updated. /// </summary> Updated, /// <summary> /// Symbol added. /// </summary> Added, } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.Emit { internal enum SymbolChange { /// <summary> /// No change to symbol or members. /// </summary> None = 0, /// <summary> /// No change to symbol but may contain changed symbols. /// </summary> ContainsChanges, /// <summary> /// Symbol updated. /// </summary> Updated, /// <summary> /// Symbol added. /// </summary> Added, } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/AbstractObjectBrowserLibraryManager_ListItems.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal abstract partial class AbstractObjectBrowserLibraryManager { internal void CollectMemberListItems(IAssemblySymbol assemblySymbol, Compilation compilation, ProjectId projectId, ImmutableArray<ObjectListItem>.Builder builder, string searchString) => GetListItemFactory().CollectMemberListItems(assemblySymbol, compilation, projectId, builder, searchString); internal void CollectNamespaceListItems(IAssemblySymbol assemblySymbol, ProjectId projectId, ImmutableArray<ObjectListItem>.Builder builder, string searchString) => GetListItemFactory().CollectNamespaceListItems(assemblySymbol, projectId, builder, searchString); internal void CollectTypeListItems(IAssemblySymbol assemblySymbol, Compilation compilation, ProjectId projectId, ImmutableArray<ObjectListItem>.Builder builder, string searchString) => GetListItemFactory().CollectTypeListItems(assemblySymbol, compilation, projectId, builder, searchString); internal ImmutableHashSet<Tuple<ProjectId, IAssemblySymbol>> GetAssemblySet(Solution solution, string languageName, CancellationToken cancellationToken) => GetListItemFactory().GetAssemblySet(solution, languageName, cancellationToken); internal ImmutableHashSet<Tuple<ProjectId, IAssemblySymbol>> GetAssemblySet(Project project, bool lookInReferences, CancellationToken cancellationToken) => GetListItemFactory().GetAssemblySet(project, lookInReferences, cancellationToken); internal ImmutableArray<ObjectListItem> GetBaseTypeListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetBaseTypeListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetFolderListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetFolderListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetMemberListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetMemberListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetNamespaceListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetNamespaceListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetProjectListItems(Solution solution, string languageName, uint listFlags) => GetListItemFactory().GetProjectListItems(solution, languageName, listFlags); internal ImmutableArray<ObjectListItem> GetReferenceListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetReferenceListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetTypeListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetTypeListItems(parentListItem, compilation); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal abstract partial class AbstractObjectBrowserLibraryManager { internal void CollectMemberListItems(IAssemblySymbol assemblySymbol, Compilation compilation, ProjectId projectId, ImmutableArray<ObjectListItem>.Builder builder, string searchString) => GetListItemFactory().CollectMemberListItems(assemblySymbol, compilation, projectId, builder, searchString); internal void CollectNamespaceListItems(IAssemblySymbol assemblySymbol, ProjectId projectId, ImmutableArray<ObjectListItem>.Builder builder, string searchString) => GetListItemFactory().CollectNamespaceListItems(assemblySymbol, projectId, builder, searchString); internal void CollectTypeListItems(IAssemblySymbol assemblySymbol, Compilation compilation, ProjectId projectId, ImmutableArray<ObjectListItem>.Builder builder, string searchString) => GetListItemFactory().CollectTypeListItems(assemblySymbol, compilation, projectId, builder, searchString); internal ImmutableHashSet<Tuple<ProjectId, IAssemblySymbol>> GetAssemblySet(Solution solution, string languageName, CancellationToken cancellationToken) => GetListItemFactory().GetAssemblySet(solution, languageName, cancellationToken); internal ImmutableHashSet<Tuple<ProjectId, IAssemblySymbol>> GetAssemblySet(Project project, bool lookInReferences, CancellationToken cancellationToken) => GetListItemFactory().GetAssemblySet(project, lookInReferences, cancellationToken); internal ImmutableArray<ObjectListItem> GetBaseTypeListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetBaseTypeListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetFolderListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetFolderListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetMemberListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetMemberListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetNamespaceListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetNamespaceListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetProjectListItems(Solution solution, string languageName, uint listFlags) => GetListItemFactory().GetProjectListItems(solution, languageName, listFlags); internal ImmutableArray<ObjectListItem> GetReferenceListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetReferenceListItems(parentListItem, compilation); internal ImmutableArray<ObjectListItem> GetTypeListItems(ObjectListItem parentListItem, Compilation compilation) => GetListItemFactory().GetTypeListItems(parentListItem, compilation); } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.StateManager.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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// This is in charge of anything related to <see cref="StateSet"/> /// </summary> private partial class StateManager { private readonly DiagnosticAnalyzerInfoCache _analyzerInfoCache; /// <summary> /// Analyzers supplied by the host (IDE). These are built-in to the IDE, the compiler, or from an installed IDE extension (VSIX). /// Maps language name to the analyzers and their state. /// </summary> private ImmutableDictionary<string, HostAnalyzerStateSets> _hostAnalyzerStateMap; /// <summary> /// Analyzers referenced by the project via a PackageReference. /// </summary> private readonly ConcurrentDictionary<ProjectId, ProjectAnalyzerStateSets> _projectAnalyzerStateMap; /// <summary> /// This will be raised whenever <see cref="StateManager"/> finds <see cref="Project.AnalyzerReferences"/> change /// </summary> public event EventHandler<ProjectAnalyzerReferenceChangedEventArgs>? ProjectAnalyzerReferenceChanged; public StateManager(DiagnosticAnalyzerInfoCache analyzerInfoCache) { _analyzerInfoCache = analyzerInfoCache; _hostAnalyzerStateMap = ImmutableDictionary<string, HostAnalyzerStateSets>.Empty; _projectAnalyzerStateMap = new ConcurrentDictionary<ProjectId, ProjectAnalyzerStateSets>(concurrencyLevel: 2, capacity: 10); } /// <summary> /// Return all <see cref="StateSet"/>. /// This will never create new <see cref="StateSet"/> but will return ones already created. /// </summary> public IEnumerable<StateSet> GetAllStateSets() => GetAllHostStateSets().Concat(GetAllProjectStateSets()); /// <summary> /// Return <see cref="StateSet"/>s for the given <see cref="ProjectId"/>. /// This will never create new <see cref="StateSet"/> but will return ones already created. /// </summary> public IEnumerable<StateSet> GetStateSets(ProjectId projectId) { var hostStateSets = GetAllHostStateSets(); return _projectAnalyzerStateMap.TryGetValue(projectId, out var entry) ? hostStateSets.Concat(entry.StateSetMap.Values) : hostStateSets; } /// <summary> /// Return <see cref="StateSet"/>s for the given <see cref="Project"/>. /// This will never create new <see cref="StateSet"/> but will return ones already created. /// Difference with <see cref="GetStateSets(ProjectId)"/> is that /// this will only return <see cref="StateSet"/>s that have same language as <paramref name="project"/>. /// </summary> public IEnumerable<StateSet> GetStateSets(Project project) => GetStateSets(project.Id).Where(s => s.Language == project.Language); /// <summary> /// Return <see cref="StateSet"/>s for the given <see cref="Project"/>. /// This will either return already created <see cref="StateSet"/>s for the specific snapshot of <see cref="Project"/> or /// It will create new <see cref="StateSet"/>s for the <see cref="Project"/> and update internal state. /// /// since this has a side-effect, this should never be called concurrently. and incremental analyzer (solution crawler) should guarantee that. /// </summary> public IEnumerable<StateSet> GetOrUpdateStateSets(Project project) { var projectStateSets = GetOrUpdateProjectStateSets(project); return GetOrCreateHostStateSets(project, projectStateSets).OrderedStateSets.Concat(projectStateSets.StateSetMap.Values); } /// <summary> /// Return <see cref="StateSet"/>s for the given <see cref="Project"/>. /// This will either return already created <see cref="StateSet"/>s for the specific snapshot of <see cref="Project"/> or /// It will create new <see cref="StateSet"/>s for the <see cref="Project"/>. /// Unlike <see cref="GetOrUpdateStateSets(Project)"/>, this has no side effect. /// </summary> public IEnumerable<StateSet> GetOrCreateStateSets(Project project) { var projectStateSets = GetOrCreateProjectStateSets(project); return GetOrCreateHostStateSets(project, projectStateSets).OrderedStateSets.Concat(projectStateSets.StateSetMap.Values); } /// <summary> /// Return <see cref="StateSet"/> for the given <see cref="DiagnosticAnalyzer"/> in the context of <see cref="Project"/>. /// This will either return already created <see cref="StateSet"/> for the specific snapshot of <see cref="Project"/> or /// It will create new <see cref="StateSet"/> for the <see cref="Project"/>. /// This will not have any side effect. /// </summary> public StateSet? GetOrCreateStateSet(Project project, DiagnosticAnalyzer analyzer) { var projectStateSets = GetOrCreateProjectStateSets(project); if (projectStateSets.StateSetMap.TryGetValue(analyzer, out var stateSet)) { return stateSet; } var hostStateSetMap = GetOrCreateHostStateSets(project, projectStateSets).StateSetMap; if (hostStateSetMap.TryGetValue(analyzer, out stateSet)) { return stateSet; } return null; } /// <summary> /// Return <see cref="StateSet"/>s that are added as the given <see cref="Project"/>'s AnalyzerReferences. /// This will never create new <see cref="StateSet"/> but will return ones already created. /// </summary> public ImmutableArray<StateSet> CreateBuildOnlyProjectStateSet(Project project) { var projectStateSets = project.SupportsCompilation ? GetOrUpdateProjectStateSets(project) : ProjectAnalyzerStateSets.Default; var hostStateSets = GetOrCreateHostStateSets(project, projectStateSets); if (!project.SupportsCompilation) { // languages which don't use our compilation model but diagnostic framework, // all their analyzer should be host analyzers. return all host analyzers // for the language return hostStateSets.OrderedStateSets; } var hostStateSetMap = hostStateSets.StateSetMap; // create project analyzer reference identity map var projectAnalyzerReferenceIds = project.AnalyzerReferences.Select(r => r.Id).ToSet(); // create build only stateSet array var stateSets = ImmutableArray.CreateBuilder<StateSet>(); // include compiler analyzer in build only state, if available StateSet? compilerStateSet = null; var hostAnalyzers = project.Solution.State.Analyzers; var compilerAnalyzer = hostAnalyzers.GetCompilerDiagnosticAnalyzer(project.Language); if (compilerAnalyzer != null && hostStateSetMap.TryGetValue(compilerAnalyzer, out compilerStateSet)) { stateSets.Add(compilerStateSet); } // now add all project analyzers stateSets.AddRange(projectStateSets.StateSetMap.Values); // now add analyzers that exist in both host and project var hostAnalyzersById = hostAnalyzers.GetOrCreateHostDiagnosticAnalyzersPerReference(project.Language); foreach (var (identity, analyzers) in hostAnalyzersById) { if (!projectAnalyzerReferenceIds.Contains(identity)) { // it is from host analyzer package rather than project analyzer reference // which build doesn't have continue; } // if same analyzer exists both in host (vsix) and in analyzer reference, // we include it in build only analyzer. foreach (var analyzer in analyzers) { if (hostStateSetMap.TryGetValue(analyzer, out var stateSet) && stateSet != compilerStateSet) { stateSets.Add(stateSet); } } } return stateSets.ToImmutable(); } /// <summary> /// Determines if any of the state sets in <see cref="GetAllHostStateSets()"/> match a specified predicate. /// </summary> /// <remarks> /// This method avoids the performance overhead of calling <see cref="GetAllHostStateSets()"/> for the /// specific case where the result is only used for testing if any element meets certain conditions. /// </remarks> public bool HasAnyHostStateSet<TArg>(Func<StateSet, TArg, bool> match, TArg arg) { foreach (var (_, hostStateSet) in _hostAnalyzerStateMap) { foreach (var stateSet in hostStateSet.OrderedStateSets) { if (match(stateSet, arg)) return true; } } return false; } /// <summary> /// Determines if any of the state sets in <see cref="_projectAnalyzerStateMap"/> for a specific project /// match a specified predicate. /// </summary> /// <remarks> /// <para>This method avoids the performance overhead of calling <see cref="GetStateSets(Project)"/> for the /// specific case where the result is only used for testing if any element meets certain conditions.</para> /// /// <para>Note that host state sets (i.e. ones retured by <see cref="GetAllHostStateSets()"/> are not tested /// by this method.</para> /// </remarks> public bool HasAnyProjectStateSet<TArg>(ProjectId projectId, Func<StateSet, TArg, bool> match, TArg arg) { if (_projectAnalyzerStateMap.TryGetValue(projectId, out var entry)) { foreach (var (_, stateSet) in entry.StateSetMap) { if (match(stateSet, arg)) return true; } } return false; } public bool OnProjectRemoved(IEnumerable<StateSet> stateSets, ProjectId projectId) { var removed = false; foreach (var stateSet in stateSets) { removed |= stateSet.OnProjectRemoved(projectId); } _projectAnalyzerStateMap.TryRemove(projectId, out _); return removed; } private void RaiseProjectAnalyzerReferenceChanged(ProjectAnalyzerReferenceChangedEventArgs args) => ProjectAnalyzerReferenceChanged?.Invoke(this, args); private static ImmutableDictionary<DiagnosticAnalyzer, StateSet> CreateStateSetMap( string language, IEnumerable<ImmutableArray<DiagnosticAnalyzer>> analyzerCollection, bool includeFileContentLoadAnalyzer) { var builder = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, StateSet>(); if (includeFileContentLoadAnalyzer) { builder.Add(FileContentLoadAnalyzer.Instance, new StateSet(language, FileContentLoadAnalyzer.Instance, PredefinedBuildTools.Live)); } foreach (var analyzers in analyzerCollection) { foreach (var analyzer in analyzers) { Debug.Assert(analyzer != FileContentLoadAnalyzer.Instance); // TODO: // #1, all de-duplication should move to DiagnosticAnalyzerInfoCache // #2, not sure whether de-duplication of analyzer itself makes sense. this can only happen // if user deliberately put same analyzer twice. if (builder.ContainsKey(analyzer)) { continue; } var buildToolName = analyzer.IsBuiltInAnalyzer() ? PredefinedBuildTools.Live : analyzer.GetAnalyzerAssemblyName(); builder.Add(analyzer, new StateSet(language, analyzer, buildToolName)); } } return builder.ToImmutable(); } [Conditional("DEBUG")] private static void VerifyUniqueStateNames(IEnumerable<StateSet> stateSets) { // Ensure diagnostic state name is indeed unique. var set = new HashSet<ValueTuple<string, string>>(); foreach (var stateSet in stateSets) { Contract.ThrowIfFalse(set.Add((stateSet.Language, stateSet.StateName))); } } [Conditional("DEBUG")] private void VerifyProjectDiagnosticStates(IEnumerable<StateSet> stateSets) { // We do not de-duplicate analyzer instances across host and project analyzers. var projectAnalyzers = stateSets.Select(state => state.Analyzer).ToImmutableHashSet(); var hostStates = GetAllHostStateSets().Where(state => !projectAnalyzers.Contains(state.Analyzer)); VerifyUniqueStateNames(hostStates.Concat(stateSets)); } } } }
// Licensed to the .NET Foundation under one or more 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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// This is in charge of anything related to <see cref="StateSet"/> /// </summary> private partial class StateManager { private readonly DiagnosticAnalyzerInfoCache _analyzerInfoCache; /// <summary> /// Analyzers supplied by the host (IDE). These are built-in to the IDE, the compiler, or from an installed IDE extension (VSIX). /// Maps language name to the analyzers and their state. /// </summary> private ImmutableDictionary<string, HostAnalyzerStateSets> _hostAnalyzerStateMap; /// <summary> /// Analyzers referenced by the project via a PackageReference. /// </summary> private readonly ConcurrentDictionary<ProjectId, ProjectAnalyzerStateSets> _projectAnalyzerStateMap; /// <summary> /// This will be raised whenever <see cref="StateManager"/> finds <see cref="Project.AnalyzerReferences"/> change /// </summary> public event EventHandler<ProjectAnalyzerReferenceChangedEventArgs>? ProjectAnalyzerReferenceChanged; public StateManager(DiagnosticAnalyzerInfoCache analyzerInfoCache) { _analyzerInfoCache = analyzerInfoCache; _hostAnalyzerStateMap = ImmutableDictionary<string, HostAnalyzerStateSets>.Empty; _projectAnalyzerStateMap = new ConcurrentDictionary<ProjectId, ProjectAnalyzerStateSets>(concurrencyLevel: 2, capacity: 10); } /// <summary> /// Return all <see cref="StateSet"/>. /// This will never create new <see cref="StateSet"/> but will return ones already created. /// </summary> public IEnumerable<StateSet> GetAllStateSets() => GetAllHostStateSets().Concat(GetAllProjectStateSets()); /// <summary> /// Return <see cref="StateSet"/>s for the given <see cref="ProjectId"/>. /// This will never create new <see cref="StateSet"/> but will return ones already created. /// </summary> public IEnumerable<StateSet> GetStateSets(ProjectId projectId) { var hostStateSets = GetAllHostStateSets(); return _projectAnalyzerStateMap.TryGetValue(projectId, out var entry) ? hostStateSets.Concat(entry.StateSetMap.Values) : hostStateSets; } /// <summary> /// Return <see cref="StateSet"/>s for the given <see cref="Project"/>. /// This will never create new <see cref="StateSet"/> but will return ones already created. /// Difference with <see cref="GetStateSets(ProjectId)"/> is that /// this will only return <see cref="StateSet"/>s that have same language as <paramref name="project"/>. /// </summary> public IEnumerable<StateSet> GetStateSets(Project project) => GetStateSets(project.Id).Where(s => s.Language == project.Language); /// <summary> /// Return <see cref="StateSet"/>s for the given <see cref="Project"/>. /// This will either return already created <see cref="StateSet"/>s for the specific snapshot of <see cref="Project"/> or /// It will create new <see cref="StateSet"/>s for the <see cref="Project"/> and update internal state. /// /// since this has a side-effect, this should never be called concurrently. and incremental analyzer (solution crawler) should guarantee that. /// </summary> public IEnumerable<StateSet> GetOrUpdateStateSets(Project project) { var projectStateSets = GetOrUpdateProjectStateSets(project); return GetOrCreateHostStateSets(project, projectStateSets).OrderedStateSets.Concat(projectStateSets.StateSetMap.Values); } /// <summary> /// Return <see cref="StateSet"/>s for the given <see cref="Project"/>. /// This will either return already created <see cref="StateSet"/>s for the specific snapshot of <see cref="Project"/> or /// It will create new <see cref="StateSet"/>s for the <see cref="Project"/>. /// Unlike <see cref="GetOrUpdateStateSets(Project)"/>, this has no side effect. /// </summary> public IEnumerable<StateSet> GetOrCreateStateSets(Project project) { var projectStateSets = GetOrCreateProjectStateSets(project); return GetOrCreateHostStateSets(project, projectStateSets).OrderedStateSets.Concat(projectStateSets.StateSetMap.Values); } /// <summary> /// Return <see cref="StateSet"/> for the given <see cref="DiagnosticAnalyzer"/> in the context of <see cref="Project"/>. /// This will either return already created <see cref="StateSet"/> for the specific snapshot of <see cref="Project"/> or /// It will create new <see cref="StateSet"/> for the <see cref="Project"/>. /// This will not have any side effect. /// </summary> public StateSet? GetOrCreateStateSet(Project project, DiagnosticAnalyzer analyzer) { var projectStateSets = GetOrCreateProjectStateSets(project); if (projectStateSets.StateSetMap.TryGetValue(analyzer, out var stateSet)) { return stateSet; } var hostStateSetMap = GetOrCreateHostStateSets(project, projectStateSets).StateSetMap; if (hostStateSetMap.TryGetValue(analyzer, out stateSet)) { return stateSet; } return null; } /// <summary> /// Return <see cref="StateSet"/>s that are added as the given <see cref="Project"/>'s AnalyzerReferences. /// This will never create new <see cref="StateSet"/> but will return ones already created. /// </summary> public ImmutableArray<StateSet> CreateBuildOnlyProjectStateSet(Project project) { var projectStateSets = project.SupportsCompilation ? GetOrUpdateProjectStateSets(project) : ProjectAnalyzerStateSets.Default; var hostStateSets = GetOrCreateHostStateSets(project, projectStateSets); if (!project.SupportsCompilation) { // languages which don't use our compilation model but diagnostic framework, // all their analyzer should be host analyzers. return all host analyzers // for the language return hostStateSets.OrderedStateSets; } var hostStateSetMap = hostStateSets.StateSetMap; // create project analyzer reference identity map var projectAnalyzerReferenceIds = project.AnalyzerReferences.Select(r => r.Id).ToSet(); // create build only stateSet array var stateSets = ImmutableArray.CreateBuilder<StateSet>(); // include compiler analyzer in build only state, if available StateSet? compilerStateSet = null; var hostAnalyzers = project.Solution.State.Analyzers; var compilerAnalyzer = hostAnalyzers.GetCompilerDiagnosticAnalyzer(project.Language); if (compilerAnalyzer != null && hostStateSetMap.TryGetValue(compilerAnalyzer, out compilerStateSet)) { stateSets.Add(compilerStateSet); } // now add all project analyzers stateSets.AddRange(projectStateSets.StateSetMap.Values); // now add analyzers that exist in both host and project var hostAnalyzersById = hostAnalyzers.GetOrCreateHostDiagnosticAnalyzersPerReference(project.Language); foreach (var (identity, analyzers) in hostAnalyzersById) { if (!projectAnalyzerReferenceIds.Contains(identity)) { // it is from host analyzer package rather than project analyzer reference // which build doesn't have continue; } // if same analyzer exists both in host (vsix) and in analyzer reference, // we include it in build only analyzer. foreach (var analyzer in analyzers) { if (hostStateSetMap.TryGetValue(analyzer, out var stateSet) && stateSet != compilerStateSet) { stateSets.Add(stateSet); } } } return stateSets.ToImmutable(); } /// <summary> /// Determines if any of the state sets in <see cref="GetAllHostStateSets()"/> match a specified predicate. /// </summary> /// <remarks> /// This method avoids the performance overhead of calling <see cref="GetAllHostStateSets()"/> for the /// specific case where the result is only used for testing if any element meets certain conditions. /// </remarks> public bool HasAnyHostStateSet<TArg>(Func<StateSet, TArg, bool> match, TArg arg) { foreach (var (_, hostStateSet) in _hostAnalyzerStateMap) { foreach (var stateSet in hostStateSet.OrderedStateSets) { if (match(stateSet, arg)) return true; } } return false; } /// <summary> /// Determines if any of the state sets in <see cref="_projectAnalyzerStateMap"/> for a specific project /// match a specified predicate. /// </summary> /// <remarks> /// <para>This method avoids the performance overhead of calling <see cref="GetStateSets(Project)"/> for the /// specific case where the result is only used for testing if any element meets certain conditions.</para> /// /// <para>Note that host state sets (i.e. ones retured by <see cref="GetAllHostStateSets()"/> are not tested /// by this method.</para> /// </remarks> public bool HasAnyProjectStateSet<TArg>(ProjectId projectId, Func<StateSet, TArg, bool> match, TArg arg) { if (_projectAnalyzerStateMap.TryGetValue(projectId, out var entry)) { foreach (var (_, stateSet) in entry.StateSetMap) { if (match(stateSet, arg)) return true; } } return false; } public bool OnProjectRemoved(IEnumerable<StateSet> stateSets, ProjectId projectId) { var removed = false; foreach (var stateSet in stateSets) { removed |= stateSet.OnProjectRemoved(projectId); } _projectAnalyzerStateMap.TryRemove(projectId, out _); return removed; } private void RaiseProjectAnalyzerReferenceChanged(ProjectAnalyzerReferenceChangedEventArgs args) => ProjectAnalyzerReferenceChanged?.Invoke(this, args); private static ImmutableDictionary<DiagnosticAnalyzer, StateSet> CreateStateSetMap( string language, IEnumerable<ImmutableArray<DiagnosticAnalyzer>> analyzerCollection, bool includeFileContentLoadAnalyzer) { var builder = ImmutableDictionary.CreateBuilder<DiagnosticAnalyzer, StateSet>(); if (includeFileContentLoadAnalyzer) { builder.Add(FileContentLoadAnalyzer.Instance, new StateSet(language, FileContentLoadAnalyzer.Instance, PredefinedBuildTools.Live)); } foreach (var analyzers in analyzerCollection) { foreach (var analyzer in analyzers) { Debug.Assert(analyzer != FileContentLoadAnalyzer.Instance); // TODO: // #1, all de-duplication should move to DiagnosticAnalyzerInfoCache // #2, not sure whether de-duplication of analyzer itself makes sense. this can only happen // if user deliberately put same analyzer twice. if (builder.ContainsKey(analyzer)) { continue; } var buildToolName = analyzer.IsBuiltInAnalyzer() ? PredefinedBuildTools.Live : analyzer.GetAnalyzerAssemblyName(); builder.Add(analyzer, new StateSet(language, analyzer, buildToolName)); } } return builder.ToImmutable(); } [Conditional("DEBUG")] private static void VerifyUniqueStateNames(IEnumerable<StateSet> stateSets) { // Ensure diagnostic state name is indeed unique. var set = new HashSet<ValueTuple<string, string>>(); foreach (var stateSet in stateSets) { Contract.ThrowIfFalse(set.Add((stateSet.Language, stateSet.StateName))); } } [Conditional("DEBUG")] private void VerifyProjectDiagnosticStates(IEnumerable<StateSet> stateSets) { // We do not de-duplicate analyzer instances across host and project analyzers. var projectAnalyzers = stateSets.Select(state => state.Analyzer).ToImmutableHashSet(); var hostStates = GetAllHostStateSets().Where(state => !projectAnalyzers.Contains(state.Analyzer)); VerifyUniqueStateNames(hostStates.Concat(stateSets)); } } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharp/FixInterpolatedVerbatimString/FixInterpolatedVerbatimStringCommandHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.FixInterpolatedVerbatimString { /// <summary> /// Replaces <c>@$"</c> with <c>$@"</c>, which is the preferred and until C# 8.0 the only supported form /// of an interpolated verbatim string start token. In C# 8.0 we still auto-correct to this form for consistency. /// </summary> [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.CSharpContentType)] [Name(nameof(FixInterpolatedVerbatimStringCommandHandler))] internal sealed class FixInterpolatedVerbatimStringCommandHandler : IChainedCommandHandler<TypeCharCommandArgs> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FixInterpolatedVerbatimStringCommandHandler() { } public string DisplayName => CSharpEditorResources.Fix_interpolated_verbatim_string; public void ExecuteCommand(TypeCharCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) { // We need to check for the token *after* the opening quote is typed, so defer to the editor first nextCommandHandler(); var cancellationToken = executionContext.OperationContext.UserCancellationToken; if (cancellationToken.IsCancellationRequested) { return; } try { ExecuteCommandWorker(args, cancellationToken); } catch (OperationCanceledException) { // According to Editor command handler API guidelines, it's best if we return early if cancellation // is requested instead of throwing. Otherwise, we could end up in an invalid state due to already // calling nextCommandHandler(). } } private static void ExecuteCommandWorker(TypeCharCommandArgs args, CancellationToken cancellationToken) { if (args.TypedChar == '"') { var caret = args.TextView.GetCaretPoint(args.SubjectBuffer); if (caret != null) { var position = caret.Value.Position; var snapshot = caret.Value.Snapshot; if (position >= 3 && snapshot[position - 1] == '"' && snapshot[position - 2] == '$' && snapshot[position - 3] == '@') { var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var root = document.GetSyntaxRootSynchronously(cancellationToken); var token = root.FindToken(position - 3); if (token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken)) { args.SubjectBuffer.Replace(new Span(position - 3, 2), "$@"); } } } } } } public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextCommandHandler) => nextCommandHandler(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.CSharp.FixInterpolatedVerbatimString { /// <summary> /// Replaces <c>@$"</c> with <c>$@"</c>, which is the preferred and until C# 8.0 the only supported form /// of an interpolated verbatim string start token. In C# 8.0 we still auto-correct to this form for consistency. /// </summary> [Export(typeof(ICommandHandler))] [ContentType(ContentTypeNames.CSharpContentType)] [Name(nameof(FixInterpolatedVerbatimStringCommandHandler))] internal sealed class FixInterpolatedVerbatimStringCommandHandler : IChainedCommandHandler<TypeCharCommandArgs> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FixInterpolatedVerbatimStringCommandHandler() { } public string DisplayName => CSharpEditorResources.Fix_interpolated_verbatim_string; public void ExecuteCommand(TypeCharCommandArgs args, Action nextCommandHandler, CommandExecutionContext executionContext) { // We need to check for the token *after* the opening quote is typed, so defer to the editor first nextCommandHandler(); var cancellationToken = executionContext.OperationContext.UserCancellationToken; if (cancellationToken.IsCancellationRequested) { return; } try { ExecuteCommandWorker(args, cancellationToken); } catch (OperationCanceledException) { // According to Editor command handler API guidelines, it's best if we return early if cancellation // is requested instead of throwing. Otherwise, we could end up in an invalid state due to already // calling nextCommandHandler(). } } private static void ExecuteCommandWorker(TypeCharCommandArgs args, CancellationToken cancellationToken) { if (args.TypedChar == '"') { var caret = args.TextView.GetCaretPoint(args.SubjectBuffer); if (caret != null) { var position = caret.Value.Position; var snapshot = caret.Value.Snapshot; if (position >= 3 && snapshot[position - 1] == '"' && snapshot[position - 2] == '$' && snapshot[position - 3] == '@') { var document = snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var root = document.GetSyntaxRootSynchronously(cancellationToken); var token = root.FindToken(position - 3); if (token.IsKind(SyntaxKind.InterpolatedVerbatimStringStartToken)) { args.SubjectBuffer.Replace(new Span(position - 3, 2), "$@"); } } } } } } public CommandState GetCommandState(TypeCharCommandArgs args, Func<CommandState> nextCommandHandler) => nextCommandHandler(); } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core/ExternalAccess/VSTypeScript/Api/IVSTypeScriptNavigationBarItemService.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; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal interface IVSTypeScriptNavigationBarItemService { Task<ImmutableArray<VSTypescriptNavigationBarItem>> GetItemsAsync(Document document, 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; namespace Microsoft.CodeAnalysis.ExternalAccess.VSTypeScript.Api { internal interface IVSTypeScriptNavigationBarItemService { Task<ImmutableArray<VSTypescriptNavigationBarItem>> GetItemsAsync(Document document, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/ExternalAccess/UnitTesting/API/UnitTestingIncrementalAnalyzerProvider.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; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal sealed class UnitTestingIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { private readonly IUnitTestingIncrementalAnalyzerProviderImplementation _incrementalAnalyzerProvider; private readonly Workspace _workspace; private IIncrementalAnalyzer? _lazyAnalyzer; internal UnitTestingIncrementalAnalyzerProvider(Workspace workspace, IUnitTestingIncrementalAnalyzerProviderImplementation incrementalAnalyzerProvider) { _workspace = workspace; _incrementalAnalyzerProvider = incrementalAnalyzerProvider; } // NOTE: We're currently expecting the analyzer to be singleton, so that // analyzers returned when calling this method twice would pass a reference equality check. // One instance should be created by SolutionCrawler, another one by us, when calling the // UnitTestingSolutionCrawlerServiceAccessor.Reanalyze method. IIncrementalAnalyzer IIncrementalAnalyzerProvider.CreateIncrementalAnalyzer(Workspace workspace) => _lazyAnalyzer ??= new UnitTestingIncrementalAnalyzer(_incrementalAnalyzerProvider.CreateIncrementalAnalyzer()); public void Reanalyze() { var solutionCrawlerService = _workspace.Services.GetService<ISolutionCrawlerService>(); if (solutionCrawlerService != null) { var analyzer = ((IIncrementalAnalyzerProvider)this).CreateIncrementalAnalyzer(_workspace)!; solutionCrawlerService.Reanalyze(_workspace, analyzer, projectIds: null, documentIds: null, highPriority: false); } } public static UnitTestingIncrementalAnalyzerProvider? TryRegister(Workspace workspace, string analyzerName, IUnitTestingIncrementalAnalyzerProviderImplementation provider) { var solutionCrawlerRegistrationService = workspace.Services.GetService<ISolutionCrawlerRegistrationService>(); if (solutionCrawlerRegistrationService == null) { return null; } var analyzerProvider = new UnitTestingIncrementalAnalyzerProvider(workspace, provider); var metadata = new IncrementalAnalyzerProviderMetadata( analyzerName, highPriorityForActiveFile: false, new[] { workspace.Kind }); solutionCrawlerRegistrationService.AddAnalyzerProvider(analyzerProvider, metadata); return analyzerProvider; } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal sealed class UnitTestingIncrementalAnalyzerProvider : IIncrementalAnalyzerProvider { private readonly IUnitTestingIncrementalAnalyzerProviderImplementation _incrementalAnalyzerProvider; private readonly Workspace _workspace; private IIncrementalAnalyzer? _lazyAnalyzer; internal UnitTestingIncrementalAnalyzerProvider(Workspace workspace, IUnitTestingIncrementalAnalyzerProviderImplementation incrementalAnalyzerProvider) { _workspace = workspace; _incrementalAnalyzerProvider = incrementalAnalyzerProvider; } // NOTE: We're currently expecting the analyzer to be singleton, so that // analyzers returned when calling this method twice would pass a reference equality check. // One instance should be created by SolutionCrawler, another one by us, when calling the // UnitTestingSolutionCrawlerServiceAccessor.Reanalyze method. IIncrementalAnalyzer IIncrementalAnalyzerProvider.CreateIncrementalAnalyzer(Workspace workspace) => _lazyAnalyzer ??= new UnitTestingIncrementalAnalyzer(_incrementalAnalyzerProvider.CreateIncrementalAnalyzer()); public void Reanalyze() { var solutionCrawlerService = _workspace.Services.GetService<ISolutionCrawlerService>(); if (solutionCrawlerService != null) { var analyzer = ((IIncrementalAnalyzerProvider)this).CreateIncrementalAnalyzer(_workspace)!; solutionCrawlerService.Reanalyze(_workspace, analyzer, projectIds: null, documentIds: null, highPriority: false); } } public static UnitTestingIncrementalAnalyzerProvider? TryRegister(Workspace workspace, string analyzerName, IUnitTestingIncrementalAnalyzerProviderImplementation provider) { var solutionCrawlerRegistrationService = workspace.Services.GetService<ISolutionCrawlerRegistrationService>(); if (solutionCrawlerRegistrationService == null) { return null; } var analyzerProvider = new UnitTestingIncrementalAnalyzerProvider(workspace, provider); var metadata = new IncrementalAnalyzerProviderMetadata( analyzerName, highPriorityForActiveFile: false, new[] { workspace.Kind }); solutionCrawlerRegistrationService.AddAnalyzerProvider(analyzerProvider, metadata); return analyzerProvider; } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Symbols/Synthesized/SynthesizedSubstitutedTypeParameterSymbol.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.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A type parameter for a synthesized class or method. /// </summary> internal sealed class SynthesizedSubstitutedTypeParameterSymbol : SubstitutedTypeParameterSymbol { public SynthesizedSubstitutedTypeParameterSymbol(Symbol owner, TypeMap map, TypeParameterSymbol substitutedFrom, int ordinal) : base(owner, map, substitutedFrom, ordinal) { Debug.Assert(this.TypeParameterKind == (ContainingSymbol is MethodSymbol ? TypeParameterKind.Method : (ContainingSymbol is NamedTypeSymbol ? TypeParameterKind.Type : TypeParameterKind.Cref)), $"Container is {ContainingSymbol?.Kind}, TypeParameterKind is {this.TypeParameterKind}"); } public override bool IsImplicitlyDeclared { get { return true; } } public override TypeParameterKind TypeParameterKind => ContainingSymbol is MethodSymbol ? TypeParameterKind.Method : TypeParameterKind.Type; internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (this.HasUnmanagedTypeConstraint) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsUnmanagedAttribute(this)); } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { if (ContainingSymbol is SynthesizedMethodBaseSymbol { InheritsBaseMethodAttributes: true }) { return _underlyingTypeParameter.GetAttributes(); } return ImmutableArray<CSharpAttributeData>.Empty; } } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Emit; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A type parameter for a synthesized class or method. /// </summary> internal sealed class SynthesizedSubstitutedTypeParameterSymbol : SubstitutedTypeParameterSymbol { public SynthesizedSubstitutedTypeParameterSymbol(Symbol owner, TypeMap map, TypeParameterSymbol substitutedFrom, int ordinal) : base(owner, map, substitutedFrom, ordinal) { Debug.Assert(this.TypeParameterKind == (ContainingSymbol is MethodSymbol ? TypeParameterKind.Method : (ContainingSymbol is NamedTypeSymbol ? TypeParameterKind.Type : TypeParameterKind.Cref)), $"Container is {ContainingSymbol?.Kind}, TypeParameterKind is {this.TypeParameterKind}"); } public override bool IsImplicitlyDeclared { get { return true; } } public override TypeParameterKind TypeParameterKind => ContainingSymbol is MethodSymbol ? TypeParameterKind.Method : TypeParameterKind.Type; internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); if (this.HasUnmanagedTypeConstraint) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsUnmanagedAttribute(this)); } } public override ImmutableArray<CSharpAttributeData> GetAttributes() { if (ContainingSymbol is SynthesizedMethodBaseSymbol { InheritsBaseMethodAttributes: true }) { return _underlyingTypeParameter.GetAttributes(); } return ImmutableArray<CSharpAttributeData>.Empty; } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/Utilities/Documentation/XmlDocumentationProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Threading; using System.Xml; using System.Xml.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A class used to provide XML documentation to the compiler for members from metadata from an XML document source. /// </summary> public abstract class XmlDocumentationProvider : DocumentationProvider { private readonly NonReentrantLock _gate = new(); private Dictionary<string, string> _docComments; /// <summary> /// Gets the source stream for the XML document. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> protected abstract Stream GetSourceStream(CancellationToken cancellationToken); /// <summary> /// Creates an <see cref="XmlDocumentationProvider"/> from bytes representing XML documentation data. /// </summary> /// <param name="xmlDocCommentBytes">The XML document bytes.</param> /// <returns>An <see cref="XmlDocumentationProvider"/>.</returns> public static XmlDocumentationProvider CreateFromBytes(byte[] xmlDocCommentBytes) => new ContentBasedXmlDocumentationProvider(xmlDocCommentBytes); private static XmlDocumentationProvider DefaultXmlDocumentationProvider { get; } = new NullXmlDocumentationProvider(); /// <summary> /// Creates an <see cref="XmlDocumentationProvider"/> from an XML documentation file. /// </summary> /// <param name="xmlDocCommentFilePath">The path to the XML file.</param> /// <returns>An <see cref="XmlDocumentationProvider"/>.</returns> public static XmlDocumentationProvider CreateFromFile(string xmlDocCommentFilePath) { if (!File.Exists(xmlDocCommentFilePath)) { return DefaultXmlDocumentationProvider; } return new FileBasedXmlDocumentationProvider(xmlDocCommentFilePath); } private XDocument GetXDocument(CancellationToken cancellationToken) { using var stream = GetSourceStream(cancellationToken); using var xmlReader = XmlReader.Create(stream, s_xmlSettings); return XDocument.Load(xmlReader); } protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default) { if (_docComments == null) { using (_gate.DisposableWait(cancellationToken)) { try { var comments = new Dictionary<string, string>(); var doc = GetXDocument(cancellationToken); foreach (var e in doc.Descendants("member")) { if (e.Attribute("name") != null) { using var reader = e.CreateReader(); reader.MoveToContent(); comments[e.Attribute("name").Value] = reader.ReadInnerXml(); } } _docComments = comments; } catch (Exception) { _docComments = new Dictionary<string, string>(); } } } return _docComments.TryGetValue(documentationMemberID, out var docComment) ? docComment : ""; } private static readonly XmlReaderSettings s_xmlSettings = new() { DtdProcessing = DtdProcessing.Prohibit, }; private sealed class ContentBasedXmlDocumentationProvider : XmlDocumentationProvider { private readonly byte[] _xmlDocCommentBytes; public ContentBasedXmlDocumentationProvider(byte[] xmlDocCommentBytes) { Contract.ThrowIfNull(xmlDocCommentBytes); _xmlDocCommentBytes = xmlDocCommentBytes; } protected override Stream GetSourceStream(CancellationToken cancellationToken) => SerializableBytes.CreateReadableStream(_xmlDocCommentBytes); public override bool Equals(object obj) { var other = obj as ContentBasedXmlDocumentationProvider; return other != null && EqualsHelper(other); } private bool EqualsHelper(ContentBasedXmlDocumentationProvider other) { // Check for reference equality first if (this == other || _xmlDocCommentBytes == other._xmlDocCommentBytes) { return true; } // Compare byte sequences if (_xmlDocCommentBytes.Length != other._xmlDocCommentBytes.Length) { return false; } for (var i = 0; i < _xmlDocCommentBytes.Length; i++) { if (_xmlDocCommentBytes[i] != other._xmlDocCommentBytes[i]) { return false; } } return true; } public override int GetHashCode() => Hash.CombineValues(_xmlDocCommentBytes); } private sealed class FileBasedXmlDocumentationProvider : XmlDocumentationProvider { private readonly string _filePath; public FileBasedXmlDocumentationProvider(string filePath) { Contract.ThrowIfNull(filePath); Debug.Assert(PathUtilities.IsAbsolute(filePath)); _filePath = filePath; } protected override Stream GetSourceStream(CancellationToken cancellationToken) => new FileStream(_filePath, FileMode.Open, FileAccess.Read); public override bool Equals(object obj) { var other = obj as FileBasedXmlDocumentationProvider; return other != null && _filePath == other._filePath; } public override int GetHashCode() => _filePath.GetHashCode(); } /// <summary> /// A trivial XmlDocumentationProvider which never returns documentation. /// </summary> private sealed class NullXmlDocumentationProvider : XmlDocumentationProvider { protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default) => ""; protected override Stream GetSourceStream(CancellationToken cancellationToken) => new MemoryStream(); public override bool Equals(object obj) { // Only one instance is expected to exist, so reference equality is fine. return (object)this == obj; } public override int GetHashCode() => 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Threading; using System.Xml; using System.Xml.Linq; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A class used to provide XML documentation to the compiler for members from metadata from an XML document source. /// </summary> public abstract class XmlDocumentationProvider : DocumentationProvider { private readonly NonReentrantLock _gate = new(); private Dictionary<string, string> _docComments; /// <summary> /// Gets the source stream for the XML document. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> protected abstract Stream GetSourceStream(CancellationToken cancellationToken); /// <summary> /// Creates an <see cref="XmlDocumentationProvider"/> from bytes representing XML documentation data. /// </summary> /// <param name="xmlDocCommentBytes">The XML document bytes.</param> /// <returns>An <see cref="XmlDocumentationProvider"/>.</returns> public static XmlDocumentationProvider CreateFromBytes(byte[] xmlDocCommentBytes) => new ContentBasedXmlDocumentationProvider(xmlDocCommentBytes); private static XmlDocumentationProvider DefaultXmlDocumentationProvider { get; } = new NullXmlDocumentationProvider(); /// <summary> /// Creates an <see cref="XmlDocumentationProvider"/> from an XML documentation file. /// </summary> /// <param name="xmlDocCommentFilePath">The path to the XML file.</param> /// <returns>An <see cref="XmlDocumentationProvider"/>.</returns> public static XmlDocumentationProvider CreateFromFile(string xmlDocCommentFilePath) { if (!File.Exists(xmlDocCommentFilePath)) { return DefaultXmlDocumentationProvider; } return new FileBasedXmlDocumentationProvider(xmlDocCommentFilePath); } private XDocument GetXDocument(CancellationToken cancellationToken) { using var stream = GetSourceStream(cancellationToken); using var xmlReader = XmlReader.Create(stream, s_xmlSettings); return XDocument.Load(xmlReader); } protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default) { if (_docComments == null) { using (_gate.DisposableWait(cancellationToken)) { try { var comments = new Dictionary<string, string>(); var doc = GetXDocument(cancellationToken); foreach (var e in doc.Descendants("member")) { if (e.Attribute("name") != null) { using var reader = e.CreateReader(); reader.MoveToContent(); comments[e.Attribute("name").Value] = reader.ReadInnerXml(); } } _docComments = comments; } catch (Exception) { _docComments = new Dictionary<string, string>(); } } } return _docComments.TryGetValue(documentationMemberID, out var docComment) ? docComment : ""; } private static readonly XmlReaderSettings s_xmlSettings = new() { DtdProcessing = DtdProcessing.Prohibit, }; private sealed class ContentBasedXmlDocumentationProvider : XmlDocumentationProvider { private readonly byte[] _xmlDocCommentBytes; public ContentBasedXmlDocumentationProvider(byte[] xmlDocCommentBytes) { Contract.ThrowIfNull(xmlDocCommentBytes); _xmlDocCommentBytes = xmlDocCommentBytes; } protected override Stream GetSourceStream(CancellationToken cancellationToken) => SerializableBytes.CreateReadableStream(_xmlDocCommentBytes); public override bool Equals(object obj) { var other = obj as ContentBasedXmlDocumentationProvider; return other != null && EqualsHelper(other); } private bool EqualsHelper(ContentBasedXmlDocumentationProvider other) { // Check for reference equality first if (this == other || _xmlDocCommentBytes == other._xmlDocCommentBytes) { return true; } // Compare byte sequences if (_xmlDocCommentBytes.Length != other._xmlDocCommentBytes.Length) { return false; } for (var i = 0; i < _xmlDocCommentBytes.Length; i++) { if (_xmlDocCommentBytes[i] != other._xmlDocCommentBytes[i]) { return false; } } return true; } public override int GetHashCode() => Hash.CombineValues(_xmlDocCommentBytes); } private sealed class FileBasedXmlDocumentationProvider : XmlDocumentationProvider { private readonly string _filePath; public FileBasedXmlDocumentationProvider(string filePath) { Contract.ThrowIfNull(filePath); Debug.Assert(PathUtilities.IsAbsolute(filePath)); _filePath = filePath; } protected override Stream GetSourceStream(CancellationToken cancellationToken) => new FileStream(_filePath, FileMode.Open, FileAccess.Read); public override bool Equals(object obj) { var other = obj as FileBasedXmlDocumentationProvider; return other != null && _filePath == other._filePath; } public override int GetHashCode() => _filePath.GetHashCode(); } /// <summary> /// A trivial XmlDocumentationProvider which never returns documentation. /// </summary> private sealed class NullXmlDocumentationProvider : XmlDocumentationProvider { protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default) => ""; protected override Stream GetSourceStream(CancellationToken cancellationToken) => new MemoryStream(); public override bool Equals(object obj) { // Only one instance is expected to exist, so reference equality is fine. return (object)this == obj; } public override int GetHashCode() => 0; } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Syntax/CompilationUnitSyntax.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; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public sealed partial class CompilationUnitSyntax : CSharpSyntaxNode, ICompilationUnitSyntax { /// <summary> /// Returns #r directives specified in the compilation. /// </summary> public IList<ReferenceDirectiveTriviaSyntax> GetReferenceDirectives() { return GetReferenceDirectives(null); } internal IList<ReferenceDirectiveTriviaSyntax> GetReferenceDirectives(Func<ReferenceDirectiveTriviaSyntax, bool>? filter) { // #r directives are always on the first token of the compilation unit. var firstToken = (SyntaxNodeOrToken)this.GetFirstToken(includeZeroWidth: true); return firstToken.GetDirectives<ReferenceDirectiveTriviaSyntax>(filter); } /// <summary> /// Returns #load directives specified in the compilation. /// </summary> public IList<LoadDirectiveTriviaSyntax> GetLoadDirectives() { // #load directives are always on the first token of the compilation unit. var firstToken = (SyntaxNodeOrToken)this.GetFirstToken(includeZeroWidth: true); return firstToken.GetDirectives<LoadDirectiveTriviaSyntax>(filter: null); } internal Syntax.InternalSyntax.DirectiveStack GetConditionalDirectivesStack() { IEnumerable<DirectiveTriviaSyntax> directives = this.GetDirectives(filter: IsActiveConditionalDirective); var directiveStack = Syntax.InternalSyntax.DirectiveStack.Empty; foreach (DirectiveTriviaSyntax directive in directives) { var internalDirective = (Syntax.InternalSyntax.DirectiveTriviaSyntax)directive.Green; directiveStack = internalDirective.ApplyDirectives(directiveStack); } return directiveStack; } private static bool IsActiveConditionalDirective(DirectiveTriviaSyntax directive) { switch (directive.Kind()) { case SyntaxKind.DefineDirectiveTrivia: return ((DefineDirectiveTriviaSyntax)directive).IsActive; case SyntaxKind.UndefDirectiveTrivia: return ((UndefDirectiveTriviaSyntax)directive).IsActive; default: return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public sealed partial class CompilationUnitSyntax : CSharpSyntaxNode, ICompilationUnitSyntax { /// <summary> /// Returns #r directives specified in the compilation. /// </summary> public IList<ReferenceDirectiveTriviaSyntax> GetReferenceDirectives() { return GetReferenceDirectives(null); } internal IList<ReferenceDirectiveTriviaSyntax> GetReferenceDirectives(Func<ReferenceDirectiveTriviaSyntax, bool>? filter) { // #r directives are always on the first token of the compilation unit. var firstToken = (SyntaxNodeOrToken)this.GetFirstToken(includeZeroWidth: true); return firstToken.GetDirectives<ReferenceDirectiveTriviaSyntax>(filter); } /// <summary> /// Returns #load directives specified in the compilation. /// </summary> public IList<LoadDirectiveTriviaSyntax> GetLoadDirectives() { // #load directives are always on the first token of the compilation unit. var firstToken = (SyntaxNodeOrToken)this.GetFirstToken(includeZeroWidth: true); return firstToken.GetDirectives<LoadDirectiveTriviaSyntax>(filter: null); } internal Syntax.InternalSyntax.DirectiveStack GetConditionalDirectivesStack() { IEnumerable<DirectiveTriviaSyntax> directives = this.GetDirectives(filter: IsActiveConditionalDirective); var directiveStack = Syntax.InternalSyntax.DirectiveStack.Empty; foreach (DirectiveTriviaSyntax directive in directives) { var internalDirective = (Syntax.InternalSyntax.DirectiveTriviaSyntax)directive.Green; directiveStack = internalDirective.ApplyDirectives(directiveStack); } return directiveStack; } private static bool IsActiveConditionalDirective(DirectiveTriviaSyntax directive) { switch (directive.Kind()) { case SyntaxKind.DefineDirectiveTrivia: return ((DefineDirectiveTriviaSyntax)directive).IsActive; case SyntaxKind.UndefDirectiveTrivia: return ((UndefDirectiveTriviaSyntax)directive).IsActive; default: return false; } } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/Legacy/AbstractLegacyProject_IVsReportExternalErrors.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.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy { internal partial class AbstractLegacyProject : IVsReportExternalErrors, IVsLanguageServiceBuildErrorReporter2 { private readonly ProjectExternalErrorReporter _externalErrorReporter; int IVsReportExternalErrors.AddNewErrors(IVsEnumExternalErrors pErrors) => _externalErrorReporter.AddNewErrors(pErrors); int IVsReportExternalErrors.ClearAllErrors() => _externalErrorReporter.ClearAllErrors(); int IVsLanguageServiceBuildErrorReporter.ClearErrors() => _externalErrorReporter.ClearErrors(); int IVsLanguageServiceBuildErrorReporter2.ClearErrors() => _externalErrorReporter.ClearErrors(); int IVsReportExternalErrors.GetErrors(out IVsEnumExternalErrors pErrors) => _externalErrorReporter.GetErrors(out pErrors); int IVsLanguageServiceBuildErrorReporter.ReportError(string bstrErrorMessage, string bstrErrorId, VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName) { return _externalErrorReporter.ReportError( bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, bstrFileName); } int IVsLanguageServiceBuildErrorReporter2.ReportError( string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")] VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName) { return _externalErrorReporter.ReportError( bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, bstrFileName); } void IVsLanguageServiceBuildErrorReporter2.ReportError2( string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")] VSTASKPRIORITY nPriority, int iStartLine, int iStartColumn, int iEndLine, int iEndColumn, string bstrFileName) { _externalErrorReporter.ReportError2( bstrErrorMessage, bstrErrorId, nPriority, iStartLine, iStartColumn, iEndLine, iEndColumn, bstrFileName); } } }
// Licensed to the .NET Foundation under one or more 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.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Legacy { internal partial class AbstractLegacyProject : IVsReportExternalErrors, IVsLanguageServiceBuildErrorReporter2 { private readonly ProjectExternalErrorReporter _externalErrorReporter; int IVsReportExternalErrors.AddNewErrors(IVsEnumExternalErrors pErrors) => _externalErrorReporter.AddNewErrors(pErrors); int IVsReportExternalErrors.ClearAllErrors() => _externalErrorReporter.ClearAllErrors(); int IVsLanguageServiceBuildErrorReporter.ClearErrors() => _externalErrorReporter.ClearErrors(); int IVsLanguageServiceBuildErrorReporter2.ClearErrors() => _externalErrorReporter.ClearErrors(); int IVsReportExternalErrors.GetErrors(out IVsEnumExternalErrors pErrors) => _externalErrorReporter.GetErrors(out pErrors); int IVsLanguageServiceBuildErrorReporter.ReportError(string bstrErrorMessage, string bstrErrorId, VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName) { return _externalErrorReporter.ReportError( bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, bstrFileName); } int IVsLanguageServiceBuildErrorReporter2.ReportError( string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")] VSTASKPRIORITY nPriority, int iLine, int iColumn, string bstrFileName) { return _externalErrorReporter.ReportError( bstrErrorMessage, bstrErrorId, nPriority, iLine, iColumn, bstrFileName); } void IVsLanguageServiceBuildErrorReporter2.ReportError2( string bstrErrorMessage, string bstrErrorId, [ComAliasName("VsShell.VSTASKPRIORITY")] VSTASKPRIORITY nPriority, int iStartLine, int iStartColumn, int iEndLine, int iEndColumn, string bstrFileName) { _externalErrorReporter.ReportError2( bstrErrorMessage, bstrErrorId, nPriority, iStartLine, iStartColumn, iEndLine, iEndColumn, bstrFileName); } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenAsyncTests.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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenAsyncTests : EmitMetadataTestBase { private static CSharpCompilation CreateCompilation(string source, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions options = null) { options = options ?? TestOptions.ReleaseExe; IEnumerable<MetadataReference> asyncRefs = new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }; references = (references != null) ? references.Concat(asyncRefs) : asyncRefs; return CreateCompilationWithMscorlib45(source, options: options, references: references); } private CompilationVerifier CompileAndVerify(string source, string expectedOutput, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions options = null, Verification verify = Verification.Passes) { var compilation = CreateCompilation(source, references: references, options: options); return base.CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: verify); } [Fact] public void StructVsClass() { var source = @" using System.Threading; using System.Threading.Tasks; class Test { public static async Task F(int a) { await Task.Factory.StartNew(() => { System.Console.WriteLine(a); }); } public static void Main() { F(123).Wait(); } }"; var c = CreateCompilationWithMscorlib45(source); CompilationOptions options; options = TestOptions.ReleaseExe; Assert.False(options.EnableEditAndContinue); CompileAndVerify(c.WithOptions(options), symbolValidator: module => { var stateMachine = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Test").GetMember<NamedTypeSymbol>("<F>d__0"); Assert.Equal(TypeKind.Struct, stateMachine.TypeKind); }, expectedOutput: "123"); options = TestOptions.ReleaseDebugExe; Assert.False(options.EnableEditAndContinue); CompileAndVerify(c.WithOptions(options), symbolValidator: module => { var stateMachine = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Test").GetMember<NamedTypeSymbol>("<F>d__0"); Assert.Equal(TypeKind.Struct, stateMachine.TypeKind); }, expectedOutput: "123"); options = TestOptions.DebugExe; Assert.True(options.EnableEditAndContinue); CompileAndVerify(c.WithOptions(options), symbolValidator: module => { var stateMachine = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Test").GetMember<NamedTypeSymbol>("<F>d__0"); Assert.Equal(TypeKind.Class, stateMachine.TypeKind); }, expectedOutput: "123"); } [Fact] public void VoidReturningAsync() { var source = @" using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; class Test { static int i = 0; public static async void F(AutoResetEvent handle) { try { await Task.Factory.StartNew(() => { Interlocked.Increment(ref Test.i); }); } finally { handle.Set(); } } public static void Main() { var handle = new AutoResetEvent(false); F(handle); handle.WaitOne(1000 * 60); Console.WriteLine(i); } }"; var expected = @" 1 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void TaskReturningAsync() { var source = @" using System; using System.Diagnostics; using System.Threading.Tasks; class Test { static int i = 0; public static async Task F() { await Task.Factory.StartNew(() => { Test.i = 42; }); } public static void Main() { Task t = F(); t.Wait(1000 * 60); Console.WriteLine(Test.i); } }"; var expected = @" 42 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void GenericTaskReturningAsync() { var source = @" using System; using System.Diagnostics; using System.Threading.Tasks; class Test { public static async Task<string> F() { return await Task.Factory.StartNew(() => { return ""O brave new world...""; }); } public static void Main() { Task<string> t = F(); t.Wait(1000 * 60); Console.WriteLine(t.Result); } }"; var expected = @" O brave new world... "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void Conformance_Awaiting_Methods_Generic01() { var source = @" using System; using System.Runtime.CompilerServices; using System.Threading; //Implementation of you own async pattern public class MyTask<T> { public MyTaskAwaiter<T> GetAwaiter() { return new MyTaskAwaiter<T>(); } public async void Run<U>(U u) where U : MyTask<int>, new() { try { int tests = 0; tests++; var rez = await u; if (rez == 0) Driver.Count++; Driver.Result = Driver.Count - tests; } finally { //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } public class MyTaskAwaiter<T> : INotifyCompletion { public void OnCompleted(Action continuationAction) { } public T GetResult() { return default(T); } public bool IsCompleted { get { return true; } } } //------------------------------------- class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { new MyTask<int>().Run<MyTask<int>>(new MyTask<int>()); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Conformance_Awaiting_Methods_Method01() { var source = @" using System.Threading; using System.Threading.Tasks; using System; public interface IExplicit { Task Method(int x = 4); } class C1 : IExplicit { Task IExplicit.Method(int x) { //This will fail until Run and RunEx are merged back together return Task.Run(async () => { await Task.Delay(1); Driver.Count++; }); } } class TestCase { public async void Run() { try { int tests = 0; tests++; C1 c = new C1(); IExplicit e = (IExplicit)c; await e.Method(); Driver.Result = Driver.Count - tests; } finally { //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Conformance_Awaiting_Methods_Parameter003() { var source = @" using System; using System.Threading.Tasks; using System.Collections.Generic; using System.Threading; class TestCase { public static int Count = 0; public static T Goo<T>(T t) { return t; } public async static Task<T> Bar<T>(T t) { await Task.Delay(1); return t; } public static async void Run() { try { int x1 = Goo(await Bar(4)); Task<int> t = Bar(5); int x2 = Goo(await t); if (x1 != 4) Count++; if (x2 != 5) Count++; } finally { Driver.CompletedSignal.Set(); } } } class Driver { public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { TestCase.Run(); CompletedSignal.WaitOne(); // 0 - success Console.WriteLine(TestCase.Count); } }"; CompileAndVerify(source, expectedOutput: "0"); } [Fact] public void Conformance_Awaiting_Methods_Method05() { var source = @" using System.Threading; using System.Threading.Tasks; using System; class C { public int Status; public C(){} } interface IImplicit { T Method<T>(params decimal[] d) where T : Task<C>; } class Impl : IImplicit { public T Method<T>(params decimal[] d) where T : Task<C> { //this will fail until Run and RunEx<C> are merged return (T) Task.Run(async() => { await Task.Delay(1); Driver.Count++; return new C() { Status = 1 }; }); } } class TestCase { public async void Run() { try { int tests = 0; Impl i = new Impl(); tests++; await i.Method<Task<C>>(3m, 4m); Driver.Result = Driver.Count - tests; } finally { //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Conformance_Awaiting_Methods_Accessible010() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; class TestCase:Test { public static int Count = 0; public async static void Run() { try { int x = await Test.GetValue<int>(1); if (x != 1) Count++; } finally { Driver.CompletedSignal.Set(); } } } class Test { protected async static Task<T> GetValue<T>(T t) { await Task.Delay(1); return t; } } class Driver { public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { TestCase.Run(); CompletedSignal.WaitOne(); // 0 - success Console.WriteLine(TestCase.Count); } }"; CompileAndVerify(source, "0"); } [Fact] public void AwaitInDelegateConstructor() { var source = @" using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; class TestCase { static int test = 0; static int count = 0; public static async Task Run() { try { test++; var f = new Func<int, object>(checked(await Bar())); var x = f(1); if ((string)x != ""1"") count--; } finally { Driver.Result = test - count; Driver.CompleteSignal.Set(); } } static async Task<Converter<int, string>> Bar() { count++; await Task.Delay(1); return delegate(int p1) { return p1.ToString(); }; } } class Driver { static public AutoResetEvent CompleteSignal = new AutoResetEvent(false); public static int Result = -1; public static void Main() { TestCase.Run(); CompleteSignal.WaitOne(); Console.Write(Result); } }"; CompileAndVerify(source, expectedOutput: "0"); } [Fact] public void Generic01() { var source = @" using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; class TestCase { static int test = 0; static int count = 0; public static async Task Run() { try { test++; Qux(async () => { return 1; }); await Task.Delay(50); } finally { Driver.Result = test - count; Driver.CompleteSignal.Set(); } } static async void Qux<T>(Func<Task<T>> x) { var y = await x(); if ((int)(object)y == 1) count++; } } class Driver { static public AutoResetEvent CompleteSignal = new AutoResetEvent(false); public static int Result = -1; public static void Main() { TestCase.Run(); CompleteSignal.WaitOne(); Console.WriteLine(Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void Struct02() { var source = @" using System; using System.Threading; using System.Threading.Tasks; struct TestCase { private Task<int> t; public async void Run() { int tests = 0; try { tests++; t = Task.Run(async () => { await Task.Delay(1); return 1; }); var x = await t; if (x == 1) Driver.Count++; tests++; t = Task.Run(async () => { await Task.Delay(1); return 1; }); var x2 = await this.t; if (x2 == 1) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.Write(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Delegate10() { var source = @" using System.Threading; using System.Threading.Tasks; using System; delegate Task MyDel<U>(out U u); class MyClass<T> { public static Task Meth(out T t) { t = default(T); return Task.Run(async () => { await Task.Delay(1); TestCase.Count++; }); } public MyDel<T> myDel; public event MyDel<T> myEvent; public async Task TriggerEvent(T p) { try { await myEvent(out p); } catch { TestCase.Count += 5; } } } struct TestCase { public static int Count = 0; private int tests; public async void Run() { tests = 0; try { tests++; MyClass<string> ms = new MyClass<string>(); ms.myDel = MyClass<string>.Meth; string str = """"; await ms.myDel(out str); tests++; ms.myEvent += MyClass<string>.Meth; await ms.TriggerEvent(str); } finally { Driver.Result = TestCase.Count - this.tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void AwaitSwitch() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async void Run() { int test = 0; int result = 0; try { test++; switch (await ((Func<Task<int>>)(async () => { await Task.Delay(1); return 5; }))()) { case 1: case 2: break; case 5: result++; break; default: break; } } finally { Driver.Result = test - result; Driver.CompleteSignal.Set(); } } } class Driver { static public AutoResetEvent CompleteSignal = new AutoResetEvent(false); public static int Result = -1; public static void Main() { TestCase tc = new TestCase(); tc.Run(); CompleteSignal.WaitOne(); Console.WriteLine(Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Return07() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { unsafe struct S { public int value; public S* next; } public async void Run() { int test = 0; int result = 0; try { Func<Task<dynamic>> func, func2 = null; test++; S s = new S(); S s1 = new S(); unsafe { S* head = &s; s.next = &s1; func = async () => { (*(head->next)).value = 1; result++; return head->next->value; }; func2 = async () => (*(head->next)); } var x = await func(); if (x != 1) result--; var xx = await func2(); if (xx.value != 1) result--; } finally { Driver.Result = test - result; Driver.CompleteSignal.Set(); } } } class Driver { static public AutoResetEvent CompleteSignal = new AutoResetEvent(false); public static int Result = -1; public static void Main() { TestCase tc = new TestCase(); tc.Run(); CompleteSignal.WaitOne(); Console.WriteLine(Result); } }"; CompileAndVerify(source, expectedOutput: "0", options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails); } [Fact] public void Inference() { var source = @" using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; struct Test { public Task<string> Goo { get { return Task.Run<string>(async () => { await Task.Delay(1); return ""abc""; }); } } } class TestCase<U> { public static async Task<object> GetValue(object x) { await Task.Delay(1); return x; } public static T GetValue1<T>(T t) where T : Task<U> { return t; } public async void Run() { int tests = 0; Test t = new Test(); tests++; var x1 = await TestCase<string>.GetValue(await t.Goo); if (x1 == ""abc"") Driver.Count++; tests++; var x2 = await TestCase<string>.GetValue1(t.Goo); if (x2 == ""abc"") Driver.Count++; Driver.Result = Driver.Count - tests; //When test completes, set the flag. Driver.CompletedSignal.Set(); } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase<int>(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, expectedOutput: "0", options: TestOptions.UnsafeDebugExe, verify: Verification.Passes); } [Fact] public void IsAndAsOperators() { var source = @" using System.Threading; using System.Threading.Tasks; using System; class TestCase { public static int Count = 0; public async void Run() { int tests = 0; var x1 = ((await Goo1()) is object); var x2 = ((await Goo2()) as string); if (x1 == true) tests++; if (x2 == ""string"") tests++; Driver.Result = TestCase.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } public async Task<int> Goo1() { await Task.Delay(1); TestCase.Count++; int i = 0; return i; } public async Task<object> Goo2() { await Task.Delay(1); TestCase.Count++; return ""string""; } } class Driver { public static int Result = -1; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.Write(Driver.Result); } }"; CompileAndVerify(source, expectedOutput: "0", options: TestOptions.UnsafeDebugExe, verify: Verification.Passes); } [Fact] public void Property21() { var source = @" using System.Threading; using System.Threading.Tasks; using System; class Base { public virtual int MyProp { get; private set; } } class TestClass : Base { async Task<int> getBaseMyProp() { await Task.Delay(1); return base.MyProp; } async public void Run() { Driver.Result = await getBaseMyProp(); Driver.CompleteSignal.Set(); } } class Driver { public static AutoResetEvent CompleteSignal = new AutoResetEvent(false); public static void Main() { TestClass tc = new TestClass(); tc.Run(); CompleteSignal.WaitOne(); Console.WriteLine(Result); } public static int Result = -1; }"; CompileAndVerify(source, expectedOutput: "0", options: TestOptions.UnsafeDebugExe, verify: Verification.Passes); } [Fact] public void AnonType32() { var source = @"using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; class TestCase { public async void Run() { int tests = 0; try { tests++; try { var tmp = await (new { task = Task.Run<string>(async () => { await Task.Delay(1); return """"; }) }).task; throw new Exception(tmp); } catch (Exception ex) { if (ex.Message == """") Driver.Count++; } } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0", options: TestOptions.UnsafeDebugExe); } [Fact] public void Init19() { var source = @" using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; class ObjInit { public int async; public Task t; public long l; } class TestCase { private T Throw<T>(T i) { MethodCount++; throw new OverflowException(); } private async Task<T> GetVal<T>(T x) { await Task.Delay(1); Throw(x); return x; } public Task<long> MyProperty { get; set; } public async void Run() { int tests = 0; Task<int> t = Task.Run<int>(async () => { await Task.Delay(1); throw new FieldAccessException(); return 1; }); //object type init tests++; try { MyProperty = Task.Run<long>(async () => { await Task.Delay(1); throw new DataMisalignedException(); return 1; }); var obj = new ObjInit() { async = await t, t = GetVal((Task.Run(async () => { await Task.Delay(1); }))), l = await MyProperty }; await obj.t; } catch (FieldAccessException) { Driver.Count++; } catch { Driver.Count--; } Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } public int MethodCount = 0; } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0", options: TestOptions.UnsafeDebugExe); } [Fact] public void Conformance_OverloadResolution_1Class_Generic_regularMethod05() { var source = @" using System.Threading; using System.Threading.Tasks; using System; struct Test<U, V, W> { //Regular methods public int Goo(Func<Task<U>> f) { return 1; } public int Goo(Func<Task<V>> f) { return 2; } public int Goo(Func<Task<W>> f) { return 3; } } class TestCase { //where there is a conversion between types (int->double) public void Run() { Test<decimal, string, dynamic> test = new Test<decimal, string, dynamic>(); int rez = 0; // Pick double Driver.Tests++; rez = test.Goo(async () => { return 1.0; }); if (rez == 3) Driver.Count++; //pick int Driver.Tests++; rez = test.Goo(async delegate() { return 1; }); if (rez == 1) Driver.Count++; // The best overload is Func<Task<object>> Driver.Tests++; rez = test.Goo(async () => { return """"; }); if (rez == 2) Driver.Count++; Driver.Tests++; rez = test.Goo(async delegate() { return """"; }); if (rez == 2) Driver.Count++; } } class Driver { public static int Count = 0; public static int Tests = 0; static int Main() { var t = new TestCase(); t.Run(); var ret = Driver.Tests - Driver.Count; Console.WriteLine(ret); return ret; } }"; CompileAndVerify(source, "0", options: TestOptions.UnsafeDebugExe); } [Fact] public void Dynamic() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task<dynamic> F1(dynamic d) { return await d; } public static async Task<int> F2(Task<int> d) { return await d; } public static async Task<int> Run() { int a = await F1(Task.Factory.StartNew(() => 21)); int b = await F2(Task.Factory.StartNew(() => 21)); return a + b; } static void Main() { var t = Run(); t.Wait(); Console.WriteLine(t.Result); } }"; CompileAndVerify(source, "42"); } [Fact] [WorkItem(638261, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638261")] public void Await15() { var source = @" using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; struct DynamicClass { public async Task<dynamic> Goo<T>(T t) { await Task.Delay(1); return t; } public async Task<Task<dynamic>> Bar(int i) { await Task.Delay(1); return Task.Run<dynamic>(async () => { await Task.Delay(1); return i; }); } } class TestCase { public async void Run() { int tests = 0; DynamicClass dc = new DynamicClass(); dynamic d = 123; try { tests++; var x1 = await dc.Goo(""""); if (x1 == """") Driver.Count++; tests++; var x2 = await await dc.Bar(d); if (x2 == 123) Driver.Count++; tests++; var x3 = await await dc.Bar(await dc.Goo(234)); if (x3 == 234) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Await01() { // The legacy compiler allows this; we don't. This kills conformance_await_dynamic_await01. var source = @" using System; using System.Threading; using System.Threading.Tasks; class DynamicMembers { public dynamic Prop { get; set; } } class Driver { static void Main() { DynamicMembers dc2 = new DynamicMembers(); dc2.Prop = (Func<Task<int>>)(async () => { await Task.Delay(1); return 1; }); var rez2 = dc2.Prop(); } }"; CompileAndVerify(source, ""); } [Fact] public void Await40() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class C1 { public async Task<int> Method(int x) { await Task.Delay(1); return x; } } class C2 { public int Status; public C2(int x = 5) { this.Status = x; } public C2(int x, int y) { this.Status = x + y; } public int Bar(int x) { return x; } } class TestCase { public async void Run() { int tests = 0; try { tests++; dynamic c = new C1(); C2 cc = new C2(x: await c.Method(1)); if (cc.Status == 1) Driver.Count++; tests++; dynamic f = (Func<Task<dynamic>>)(async () => { await Task.Delay(1); return 4; }); cc = new C2(await c.Method(2), await f()); if (cc.Status == 6) Driver.Count++; tests++; var x = new C2(2).Bar(await c.Method(1)); if (cc.Status == 6 && x == 1) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Await43() { var source = @" using System.Threading; using System.Threading.Tasks; using System; struct MyClass { public static Task operator *(MyClass c, int x) { return Task.Run(async delegate { await Task.Delay(1); TestCase.Count++; }); } public static Task operator +(MyClass c, long x) { return Task.Run(async () => { await Task.Delay(1); TestCase.Count++; }); } } class TestCase { public static int Count = 0; private int tests; public async void Run() { this.tests = 0; dynamic dy = Task.Run<MyClass>(async () => { await Task.Delay(1); return new MyClass(); }); try { this.tests++; await (await dy * 5); this.tests++; dynamic d = new MyClass(); dynamic dd = Task.Run<long>(async () => { await Task.Delay(1); return 1L; }); await (d + await dd); } catch (Exception ex) { Console.WriteLine(ex); Console.WriteLine(ex.StackTrace); } finally { Driver.Result = TestCase.Count - this.tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Await44() { var source = @" using System.Threading; using System.Threading.Tasks; using System; class MyClass { public static implicit operator Task(MyClass c) { return Task.Run(async delegate { await Task.Delay(1); TestCase.Count++; }); } } class TestCase { public static int Count = 0; private int tests; public async void Run() { this.tests = 0; dynamic mc = new MyClass(); try { tests++; Task t1 = mc; await t1; tests++; dynamic t2 = (Task)mc; await t2; } finally { Driver.Result = TestCase.Count - this.tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void ThisShouldProbablyCompileToVerifiableCode() { var source = @" using System; class Driver { public static bool Run() { dynamic dynamicThing = false; return true && dynamicThing; } static void Main() { Console.WriteLine(Run()); } }"; CompileAndVerify(source, "False"); } [Fact] public void Async_Conformance_Awaiting_indexer23() { var source = @" using System.Threading; using System.Threading.Tasks; using System; struct MyStruct<T> where T : Task<Func<int>> { T t { get; set; } public T this[T index] { get { return t; } set { t = value; } } } struct TestCase { public static int Count = 0; private int tests; public async void Run() { this.tests = 0; MyStruct<Task<Func<int>>> ms = new MyStruct<Task<Func<int>>>(); try { ms[index: null] = Task.Run<Func<int>>(async () => { await Task.Delay(1); Interlocked.Increment(ref TestCase.Count); return () => (123); }); this.tests++; var x = await ms[index: await Goo(null)]; if (x() == 123) this.tests++; } finally { Driver.Result = TestCase.Count - this.tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } public async Task<Task<Func<int>>> Goo(Task<Func<int>> d) { await Task.Delay(1); Interlocked.Increment(ref TestCase.Count); return d; } } class Driver { public static int Result = -1; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Conformance_Exceptions_Async_Await_Names() { var source = @" using System; class TestCase { public void Run() { Driver.Tests++; try { throw new ArgumentException(); } catch (Exception await) { if (await is ArgumentException) Driver.Count++; } Driver.Tests++; try { throw new ArgumentException(); } catch (Exception async) { if (async is ArgumentException) Driver.Count++; } } } class Driver { public static int Tests; public static int Count; static void Main() { TestCase t = new TestCase(); t.Run(); Console.WriteLine(Tests - Count); } }"; CompileAndVerify(source, "0"); } [Fact] public void MyTask_08() { var source = @" using System; using System.Threading; using System.Threading.Tasks; //Implementation of you own async pattern public class MyTask { public async void Run() { int tests = 0; try { tests++; var myTask = new MyTask(); var x = await myTask; if (x == 123) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } public class MyTaskAwaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action continuationAction) { } public int GetResult() { return 123; } public bool IsCompleted { get { return true; } } } public static class Extension { public static MyTaskAwaiter GetAwaiter(this MyTask my) { return new MyTaskAwaiter(); } } //------------------------------------- class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { new MyTask().Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void MyTask_16() { var source = @" using System; using System.Threading; using System.Threading.Tasks; //Implementation of you own async pattern public class MyTask { public MyTaskAwaiter GetAwaiter() { return new MyTaskAwaiter(); } public async void Run() { int tests = 0; try { tests++; var myTask = new MyTask(); var x = await myTask; if (x == 123) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } public class MyTaskBaseAwaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action continuationAction) { } public int GetResult() { return 123; } public bool IsCompleted { get { return true; } } } public class MyTaskAwaiter : MyTaskBaseAwaiter { } //------------------------------------- class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { new MyTask().Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] [WorkItem(625282, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/625282")] public void Generic05() { var source = @" using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; class TestCase { public T Goo<T>(T x, T y, int z) { return x; } public T GetVal<T>(T t) { return t; } public IEnumerable<T> Run<T>(T t) { dynamic d = GetVal(t); yield return Goo(t, d, 3); } } class Driver { static void Main() { var t = new TestCase(); t.Run(6); } }"; CompileAndVerifyWithMscorlib40(source, new[] { CSharpRef, SystemCoreRef }); } [Fact] public void AsyncStateMachineIL_Struct_TaskT() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task<int> F() { return await Task.Factory.StartNew(() => 42); } public static void Main() { var t = F(); t.Wait(); Console.WriteLine(t.Result); } }"; var expected = @" 42 "; var c = CompileAndVerify(source, expectedOutput: expected); c.VerifyIL("Test.F", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (Test.<F>d__0 V_0) IL_0000: ldloca.s V_0 IL_0002: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Create()"" IL_0007: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_000c: ldloca.s V_0 IL_000e: ldc.i4.m1 IL_000f: stfld ""int Test.<F>d__0.<>1__state"" IL_0014: ldloca.s V_0 IL_0016: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_001b: ldloca.s V_0 IL_001d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Start<Test.<F>d__0>(ref Test.<F>d__0)"" IL_0022: ldloca.s V_0 IL_0024: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_0029: call ""System.Threading.Tasks.Task<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Task.get"" IL_002e: ret } "); c.VerifyIL("Test.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 180 (0xb4) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0062 IL_000a: call ""System.Threading.Tasks.TaskFactory System.Threading.Tasks.Task.Factory.get"" IL_000f: ldsfld ""System.Func<int> Test.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Test.<>c Test.<>c.<>9"" IL_001d: ldftn ""int Test.<>c.<F>b__0_0()"" IL_0023: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int> Test.<>c.<>9__0_0"" IL_002e: callvirt ""System.Threading.Tasks.Task<int> System.Threading.Tasks.TaskFactory.StartNew<int>(System.Func<int>)"" IL_0033: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0038: stloc.2 IL_0039: ldloca.s V_2 IL_003b: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0040: brtrue.s IL_007e IL_0042: ldarg.0 IL_0043: ldc.i4.0 IL_0044: dup IL_0045: stloc.0 IL_0046: stfld ""int Test.<F>d__0.<>1__state"" IL_004b: ldarg.0 IL_004c: ldloc.2 IL_004d: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0052: ldarg.0 IL_0053: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_0058: ldloca.s V_2 IL_005a: ldarg.0 IL_005b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<F>d__0)"" IL_0060: leave.s IL_00b3 IL_0062: ldarg.0 IL_0063: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0068: stloc.2 IL_0069: ldarg.0 IL_006a: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_006f: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0075: ldarg.0 IL_0076: ldc.i4.m1 IL_0077: dup IL_0078: stloc.0 IL_0079: stfld ""int Test.<F>d__0.<>1__state"" IL_007e: ldloca.s V_2 IL_0080: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0085: stloc.1 IL_0086: leave.s IL_009f } catch System.Exception { IL_0088: stloc.3 IL_0089: ldarg.0 IL_008a: ldc.i4.s -2 IL_008c: stfld ""int Test.<F>d__0.<>1__state"" IL_0091: ldarg.0 IL_0092: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_0097: ldloc.3 IL_0098: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_009d: leave.s IL_00b3 } IL_009f: ldarg.0 IL_00a0: ldc.i4.s -2 IL_00a2: stfld ""int Test.<F>d__0.<>1__state"" IL_00a7: ldarg.0 IL_00a8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_00ad: ldloc.1 IL_00ae: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00b3: ret } "); c.VerifyIL("Test.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_0006: ldarg.1 IL_0007: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine)"" IL_000c: ret } "); } [Fact] public void AsyncStateMachineIL_Struct_TaskT_A() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task<int> F() { return await Task.Factory.StartNew(() => 42); } public static void Main() { var t = F(); t.Wait(); Console.WriteLine(t.Result); } }"; var expected = @" 42 "; var c = CompileAndVerify(source, options: TestOptions.ReleaseDebugExe, expectedOutput: expected); c.VerifyIL("Test.F", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (Test.<F>d__0 V_0) IL_0000: ldloca.s V_0 IL_0002: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Create()"" IL_0007: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_000c: ldloca.s V_0 IL_000e: ldc.i4.m1 IL_000f: stfld ""int Test.<F>d__0.<>1__state"" IL_0014: ldloca.s V_0 IL_0016: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_001b: ldloca.s V_0 IL_001d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Start<Test.<F>d__0>(ref Test.<F>d__0)"" IL_0022: ldloca.s V_0 IL_0024: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_0029: call ""System.Threading.Tasks.Task<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Task.get"" IL_002e: ret } "); c.VerifyIL("Test.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 184 (0xb8) .maxstack 3 .locals init (int V_0, int V_1, int V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0062 IL_000a: call ""System.Threading.Tasks.TaskFactory System.Threading.Tasks.Task.Factory.get"" IL_000f: ldsfld ""System.Func<int> Test.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Test.<>c Test.<>c.<>9"" IL_001d: ldftn ""int Test.<>c.<F>b__0_0()"" IL_0023: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int> Test.<>c.<>9__0_0"" IL_002e: callvirt ""System.Threading.Tasks.Task<int> System.Threading.Tasks.TaskFactory.StartNew<int>(System.Func<int>)"" IL_0033: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0038: stloc.3 IL_0039: ldloca.s V_3 IL_003b: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0040: brtrue.s IL_007e IL_0042: ldarg.0 IL_0043: ldc.i4.0 IL_0044: dup IL_0045: stloc.0 IL_0046: stfld ""int Test.<F>d__0.<>1__state"" IL_004b: ldarg.0 IL_004c: ldloc.3 IL_004d: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0052: ldarg.0 IL_0053: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_0058: ldloca.s V_3 IL_005a: ldarg.0 IL_005b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<F>d__0)"" IL_0060: leave.s IL_00b7 IL_0062: ldarg.0 IL_0063: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0068: stloc.3 IL_0069: ldarg.0 IL_006a: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_006f: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0075: ldarg.0 IL_0076: ldc.i4.m1 IL_0077: dup IL_0078: stloc.0 IL_0079: stfld ""int Test.<F>d__0.<>1__state"" IL_007e: ldloca.s V_3 IL_0080: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0085: stloc.2 IL_0086: ldloc.2 IL_0087: stloc.1 IL_0088: leave.s IL_00a3 } catch System.Exception { IL_008a: stloc.s V_4 IL_008c: ldarg.0 IL_008d: ldc.i4.s -2 IL_008f: stfld ""int Test.<F>d__0.<>1__state"" IL_0094: ldarg.0 IL_0095: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_009a: ldloc.s V_4 IL_009c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00a1: leave.s IL_00b7 } IL_00a3: ldarg.0 IL_00a4: ldc.i4.s -2 IL_00a6: stfld ""int Test.<F>d__0.<>1__state"" IL_00ab: ldarg.0 IL_00ac: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_00b1: ldloc.1 IL_00b2: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00b7: ret } "); c.VerifyIL("Test.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_0006: ldarg.1 IL_0007: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine)"" IL_000c: ret } "); } [Fact] public void AsyncStateMachineIL_Class_TaskT() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task<int> F() { return await Task.Factory.StartNew(() => 42); } public static void Main() { var t = F(); t.Wait(); Console.WriteLine(t.Result); } }"; var expected = @" 42 "; var c = CompileAndVerify(source, expectedOutput: expected, options: TestOptions.DebugExe); c.VerifyIL("Test.F", @" { // Code size 49 (0x31) .maxstack 2 .locals init (Test.<F>d__0 V_0) IL_0000: newobj ""Test.<F>d__0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Create()"" IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_0011: ldloc.0 IL_0012: ldc.i4.m1 IL_0013: stfld ""int Test.<F>d__0.<>1__state"" IL_0018: ldloc.0 IL_0019: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_001e: ldloca.s V_0 IL_0020: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Start<Test.<F>d__0>(ref Test.<F>d__0)"" IL_0025: ldloc.0 IL_0026: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_002b: call ""System.Threading.Tasks.Task<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Task.get"" IL_0030: ret } "); c.VerifyIL("Test.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 205 (0xcd) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, Test.<F>d__0 V_3, System.Exception V_4) ~IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_006b -IL_000e: nop -IL_000f: call ""System.Threading.Tasks.TaskFactory System.Threading.Tasks.Task.Factory.get"" IL_0014: ldsfld ""System.Func<int> Test.<>c.<>9__0_0"" IL_0019: dup IL_001a: brtrue.s IL_0033 IL_001c: pop IL_001d: ldsfld ""Test.<>c Test.<>c.<>9"" IL_0022: ldftn ""int Test.<>c.<F>b__0_0()"" IL_0028: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_002d: dup IL_002e: stsfld ""System.Func<int> Test.<>c.<>9__0_0"" IL_0033: callvirt ""System.Threading.Tasks.Task<int> System.Threading.Tasks.TaskFactory.StartNew<int>(System.Func<int>)"" IL_0038: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_003d: stloc.2 ~IL_003e: ldloca.s V_2 IL_0040: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0045: brtrue.s IL_0087 IL_0047: ldarg.0 IL_0048: ldc.i4.0 IL_0049: dup IL_004a: stloc.0 IL_004b: stfld ""int Test.<F>d__0.<>1__state"" <IL_0050: ldarg.0 IL_0051: ldloc.2 IL_0052: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0057: ldarg.0 IL_0058: stloc.3 IL_0059: ldarg.0 IL_005a: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_005f: ldloca.s V_2 IL_0061: ldloca.s V_3 IL_0063: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<F>d__0)"" IL_0068: nop IL_0069: leave.s IL_00cc >IL_006b: ldarg.0 IL_006c: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0071: stloc.2 IL_0072: ldarg.0 IL_0073: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0078: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_007e: ldarg.0 IL_007f: ldc.i4.m1 IL_0080: dup IL_0081: stloc.0 IL_0082: stfld ""int Test.<F>d__0.<>1__state"" IL_0087: ldarg.0 IL_0088: ldloca.s V_2 IL_008a: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_008f: stfld ""int Test.<F>d__0.<>s__1"" IL_0094: ldarg.0 IL_0095: ldfld ""int Test.<F>d__0.<>s__1"" IL_009a: stloc.1 IL_009b: leave.s IL_00b7 } catch System.Exception { ~IL_009d: stloc.s V_4 IL_009f: ldarg.0 IL_00a0: ldc.i4.s -2 IL_00a2: stfld ""int Test.<F>d__0.<>1__state"" IL_00a7: ldarg.0 IL_00a8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_00ad: ldloc.s V_4 IL_00af: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00b4: nop IL_00b5: leave.s IL_00cc } -IL_00b7: ldarg.0 IL_00b8: ldc.i4.s -2 IL_00ba: stfld ""int Test.<F>d__0.<>1__state"" ~IL_00bf: ldarg.0 IL_00c0: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_00c5: ldloc.1 IL_00c6: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00cb: nop IL_00cc: ret }", sequencePoints: "Test+<F>d__0.MoveNext"); c.VerifyIL("Test.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret } "); } [Fact] public void IL_Task() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task F() { await Task.Factory.StartNew(() => 42); Console.WriteLine(42); } public static void Main() { var t = F(); t.Wait(); } }"; var expected = @" 42 "; var c = CompileAndVerify(source, expectedOutput: expected); c.VerifyIL("Test.F", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (Test.<F>d__0 V_0) IL_0000: ldloca.s V_0 IL_0002: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Create()"" IL_0007: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<F>d__0.<>t__builder"" IL_000c: ldloca.s V_0 IL_000e: ldc.i4.m1 IL_000f: stfld ""int Test.<F>d__0.<>1__state"" IL_0014: ldloca.s V_0 IL_0016: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<F>d__0.<>t__builder"" IL_001b: ldloca.s V_0 IL_001d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start<Test.<F>d__0>(ref Test.<F>d__0)"" IL_0022: ldloca.s V_0 IL_0024: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<F>d__0.<>t__builder"" IL_0029: call ""System.Threading.Tasks.Task System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Task.get"" IL_002e: ret } "); c.VerifyIL("Test.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 186 (0xba) .maxstack 3 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter<int> V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0062 IL_000a: call ""System.Threading.Tasks.TaskFactory System.Threading.Tasks.Task.Factory.get"" IL_000f: ldsfld ""System.Func<int> Test.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Test.<>c Test.<>c.<>9"" IL_001d: ldftn ""int Test.<>c.<F>b__0_0()"" IL_0023: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int> Test.<>c.<>9__0_0"" IL_002e: callvirt ""System.Threading.Tasks.Task<int> System.Threading.Tasks.TaskFactory.StartNew<int>(System.Func<int>)"" IL_0033: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0038: stloc.1 IL_0039: ldloca.s V_1 IL_003b: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0040: brtrue.s IL_007e IL_0042: ldarg.0 IL_0043: ldc.i4.0 IL_0044: dup IL_0045: stloc.0 IL_0046: stfld ""int Test.<F>d__0.<>1__state"" IL_004b: ldarg.0 IL_004c: ldloc.1 IL_004d: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0052: ldarg.0 IL_0053: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<F>d__0.<>t__builder"" IL_0058: ldloca.s V_1 IL_005a: ldarg.0 IL_005b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<F>d__0)"" IL_0060: leave.s IL_00b9 IL_0062: ldarg.0 IL_0063: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0068: stloc.1 IL_0069: ldarg.0 IL_006a: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_006f: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0075: ldarg.0 IL_0076: ldc.i4.m1 IL_0077: dup IL_0078: stloc.0 IL_0079: stfld ""int Test.<F>d__0.<>1__state"" IL_007e: ldloca.s V_1 IL_0080: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0085: pop IL_0086: ldc.i4.s 42 IL_0088: call ""void System.Console.WriteLine(int)"" IL_008d: leave.s IL_00a6 } catch System.Exception { IL_008f: stloc.2 IL_0090: ldarg.0 IL_0091: ldc.i4.s -2 IL_0093: stfld ""int Test.<F>d__0.<>1__state"" IL_0098: ldarg.0 IL_0099: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<F>d__0.<>t__builder"" IL_009e: ldloc.2 IL_009f: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a4: leave.s IL_00b9 } IL_00a6: ldarg.0 IL_00a7: ldc.i4.s -2 IL_00a9: stfld ""int Test.<F>d__0.<>1__state"" IL_00ae: ldarg.0 IL_00af: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<F>d__0.<>t__builder"" IL_00b4: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b9: ret } "); } [Fact] public void IL_Void() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class Test { static int i = 0; public static async void F(AutoResetEvent handle) { await Task.Factory.StartNew(() => { Test.i = 42; }); handle.Set(); } public static void Main() { var handle = new AutoResetEvent(false); F(handle); handle.WaitOne(1000 * 60); Console.WriteLine(i); } }"; var expected = @" 42 "; CompileAndVerify(source, expectedOutput: expected).VerifyIL("Test.F", @" { // Code size 43 (0x2b) .maxstack 2 .locals init (Test.<F>d__1 V_0) IL_0000: ldloca.s V_0 IL_0002: call ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Create()"" IL_0007: stfld ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<F>d__1.<>t__builder"" IL_000c: ldloca.s V_0 IL_000e: ldarg.0 IL_000f: stfld ""System.Threading.AutoResetEvent Test.<F>d__1.handle"" IL_0014: ldloca.s V_0 IL_0016: ldc.i4.m1 IL_0017: stfld ""int Test.<F>d__1.<>1__state"" IL_001c: ldloca.s V_0 IL_001e: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<F>d__1.<>t__builder"" IL_0023: ldloca.s V_0 IL_0025: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start<Test.<F>d__1>(ref Test.<F>d__1)"" IL_002a: ret } ").VerifyIL("Test.<F>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 190 (0xbe) .maxstack 3 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<F>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0062 IL_000a: call ""System.Threading.Tasks.TaskFactory System.Threading.Tasks.Task.Factory.get"" IL_000f: ldsfld ""System.Action Test.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Test.<>c Test.<>c.<>9"" IL_001d: ldftn ""void Test.<>c.<F>b__1_0()"" IL_0023: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Action Test.<>c.<>9__1_0"" IL_002e: callvirt ""System.Threading.Tasks.Task System.Threading.Tasks.TaskFactory.StartNew(System.Action)"" IL_0033: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()"" IL_0038: stloc.1 IL_0039: ldloca.s V_1 IL_003b: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get"" IL_0040: brtrue.s IL_007e IL_0042: ldarg.0 IL_0043: ldc.i4.0 IL_0044: dup IL_0045: stloc.0 IL_0046: stfld ""int Test.<F>d__1.<>1__state"" IL_004b: ldarg.0 IL_004c: ldloc.1 IL_004d: stfld ""System.Runtime.CompilerServices.TaskAwaiter Test.<F>d__1.<>u__1"" IL_0052: ldarg.0 IL_0053: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<F>d__1.<>t__builder"" IL_0058: ldloca.s V_1 IL_005a: ldarg.0 IL_005b: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, Test.<F>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter, ref Test.<F>d__1)"" IL_0060: leave.s IL_00bd IL_0062: ldarg.0 IL_0063: ldfld ""System.Runtime.CompilerServices.TaskAwaiter Test.<F>d__1.<>u__1"" IL_0068: stloc.1 IL_0069: ldarg.0 IL_006a: ldflda ""System.Runtime.CompilerServices.TaskAwaiter Test.<F>d__1.<>u__1"" IL_006f: initobj ""System.Runtime.CompilerServices.TaskAwaiter"" IL_0075: ldarg.0 IL_0076: ldc.i4.m1 IL_0077: dup IL_0078: stloc.0 IL_0079: stfld ""int Test.<F>d__1.<>1__state"" IL_007e: ldloca.s V_1 IL_0080: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()"" IL_0085: ldarg.0 IL_0086: ldfld ""System.Threading.AutoResetEvent Test.<F>d__1.handle"" IL_008b: callvirt ""bool System.Threading.EventWaitHandle.Set()"" IL_0090: pop IL_0091: leave.s IL_00aa } catch System.Exception { IL_0093: stloc.2 IL_0094: ldarg.0 IL_0095: ldc.i4.s -2 IL_0097: stfld ""int Test.<F>d__1.<>1__state"" IL_009c: ldarg.0 IL_009d: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<F>d__1.<>t__builder"" IL_00a2: ldloc.2 IL_00a3: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_00a8: leave.s IL_00bd } IL_00aa: ldarg.0 IL_00ab: ldc.i4.s -2 IL_00ad: stfld ""int Test.<F>d__1.<>1__state"" IL_00b2: ldarg.0 IL_00b3: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<F>d__1.<>t__builder"" IL_00b8: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_00bd: ret } "); } [Fact] [WorkItem(564036, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/564036")] public void InferFromAsyncLambda() { var source = @"using System; using System.Threading.Tasks; class Program { public static T CallWithCatch<T>(Func<T> func) { Console.WriteLine(typeof(T).ToString()); return func(); } private static async Task LoadTestDataAsync() { await CallWithCatch(async () => await LoadTestData()); } private static async Task LoadTestData() { await Task.Run(() => { }); } public static void Main(string[] args) { Task t = LoadTestDataAsync(); t.Wait(1000); } }"; var expected = @"System.Threading.Tasks.Task"; CompileAndVerify(source, expectedOutput: expected); } [Fact] [WorkItem(620987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/620987")] public void PrematureNull() { var source = @"using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; class Program { public static void Main(string[] args) { try { var ar = FindReferencesInDocumentAsync(""Document""); ar.Wait(1000 * 60); Console.WriteLine(ar.Result); } catch (Exception ex) { Console.WriteLine(ex); } } internal static async Task<string> GetTokensWithIdentifierAsync() { Console.WriteLine(""in GetTokensWithIdentifierAsync""); return ""GetTokensWithIdentifierAsync""; } protected static async Task<string> FindReferencesInTokensAsync( string document, string tokens) { Console.WriteLine(""in FindReferencesInTokensAsync""); if (tokens == null) throw new NullReferenceException(""tokens""); Console.WriteLine(""tokens were fine""); if (document == null) throw new NullReferenceException(""document""); Console.WriteLine(""document was fine""); return ""FindReferencesInTokensAsync""; } public static async Task<string> FindReferencesInDocumentAsync( string document) { Console.WriteLine(""in FindReferencesInDocumentAsync""); if (document == null) throw new NullReferenceException(""document""); var nonAliasReferences = await FindReferencesInTokensAsync( document, await GetTokensWithIdentifierAsync() ).ConfigureAwait(true); return ""done!""; } }"; var expected = @"in FindReferencesInDocumentAsync in GetTokensWithIdentifierAsync in FindReferencesInTokensAsync tokens were fine document was fine done!"; CompileAndVerify(source, expectedOutput: expected); } [Fact] [WorkItem(621705, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/621705")] public void GenericAsyncLambda() { var source = @"using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; class G<T> { T t; public G(T t, Func<T, Task<T>> action) { var tt = action(t); var completed = tt.Wait(1000 * 60); Debug.Assert(completed); this.t = tt.Result; } public override string ToString() { return t.ToString(); } } class Test { static G<U> M<U>(U t) { return new G<U>(t, async x => { return await IdentityAsync(x); } ); } static async Task<V> IdentityAsync<V>(V x) { await Task.Delay(1); return x; } public static void Main() { var g = M(12); Console.WriteLine(g); } }"; var expected = @"12"; CompileAndVerify(source, expectedOutput: expected); } [Fact] [WorkItem(602028, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602028")] public void BetterConversionFromAsyncLambda() { var source = @"using System.Threading; using System.Threading.Tasks; using System; class TestCase { public static int Goo(Func<Task<double>> f) { return 12; } public static int Goo(Func<Task<object>> f) { return 13; } public static void Main() { Console.WriteLine(Goo(async delegate() { return 14; })); } } "; var expected = @"12"; CompileAndVerify(source, expectedOutput: expected); } [Fact] [WorkItem(602206, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602206")] public void ExtensionAddMethod() { var source = @"using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; static public class Extension { static public void Add<T>(this Stack<T> stack, T item) { Console.WriteLine(""Add "" + item.ToString()); stack.Push(item); } } class TestCase { AutoResetEvent handle = new AutoResetEvent(false); private async Task<T> GetVal<T>(T x) { await Task.Delay(1); Console.WriteLine(""GetVal "" + x.ToString()); return x; } public async void Run() { try { Stack<int> stack = new Stack<int>() { await GetVal(1), 2, 3 }; // CS0117 } finally { handle.Set(); } } public static void Main(string[] args) { var tc = new TestCase(); tc.Run(); tc.handle.WaitOne(1000 * 60); } }"; var expected = @"GetVal 1 Add 1 Add 2 Add 3"; CompileAndVerify(source, expectedOutput: expected); } [Fact] [WorkItem(748527, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/748527")] public void Bug748527() { var source = @"using System.Threading.Tasks; using System; namespace A { public struct TestClass { async public System.Threading.Tasks.Task<int> IntRet(int IntI) { return await ((Func<Task<int>>)(async ()=> { await Task.Yield(); return IntI ; } ))() ; } } public class B { async public static System.Threading.Tasks.Task<int> MainMethod() { int MyRet = 0; TestClass TC = new TestClass(); if (( await ((Func<Task<int>>)(async ()=> { await Task.Yield(); return (await(new TestClass().IntRet( await ((Func<Task<int>>)(async ()=> { await Task.Yield(); return 3 ; } ))() ))) ; } ))() ) != await ((Func<Task<int>>)(async ()=> { await Task.Yield(); return 3 ; } ))() ) { MyRet = 1; } return await ((Func<Task<int>>)(async ()=> {await Task.Yield(); return MyRet;}))(); } static void Main () { MainMethod(); return; } } }"; var expectedOutput = ""; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] [WorkItem(602216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602216")] public void AsyncMethodOnlyWritesToEnclosingStruct() { var source = @"public struct GenC<T> where T : struct { public T? valueN; public async void Test(T t) { valueN = t; } } public class Test { public static void Main() { int test = 12; GenC<int> _int = new GenC<int>(); _int.Test(test); System.Console.WriteLine(_int.valueN ?? 1); } }"; var expected = @"1"; CompileAndVerify(source, expectedOutput: expected); } [Fact] [WorkItem(602246, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602246")] public void Bug602246() { var source = @"using System; using System.Threading.Tasks; public class TestCase { public static async Task<T> Run<T>(T t) { await Task.Delay(1); Func<Func<Task<T>>, Task<T>> f = async (x) => { return await x(); }; var rez = await f(async () => { await Task.Delay(1); return t; }); return rez; } public static void Main() { var t = TestCase.Run<int>(12); if (!t.Wait(1000 * 60)) throw new Exception(); Console.Write(t.Result); } }"; var expected = @"12"; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(628654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/628654")] [Fact] public void AsyncWithDynamic01() { var source = @" using System; using System.Threading.Tasks; class Program { static void Main() { Goo<int>().Wait(); } static async Task Goo<T>() { Console.WriteLine(""{0}"" as dynamic, await Task.FromResult(new T[] { })); } }"; var expected = @" System.Int32[] "; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(640282, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/640282")] [Fact] public void CustomAsyncWithDynamic01() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class MyTask { public dynamic GetAwaiter() { return new MyTaskAwaiter<Action>(); } public async void Run<T>() { int tests = 0; tests++; dynamic myTask = new MyTask(); var x = await myTask; if (x == 123) Driver.Count++; Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } class MyTaskAwaiter<U> { public void OnCompleted(U continuationAction) { } public int GetResult() { return 123; } public dynamic IsCompleted { get { return true; } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); public static void Main() { new MyTask().Run<int>(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @"0"; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(840843, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/840843")] [Fact] public void MissingAsyncVoidMethodBuilder() { var source = @" class C { async void M() {} } "; var comp = CSharpTestBase.CreateEmptyCompilation(source, new[] { Net40.mscorlib }, TestOptions.ReleaseDll); // NOTE: 4.0, not 4.5, so it's missing the async helpers. // CONSIDER: It would be nice if we didn't squiggle the whole method body, but this is a corner case. comp.VerifyEmitDiagnostics( // (4,16): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async void M() {} Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(4, 16), // (4,20): error CS0518: Predefined type 'System.Runtime.CompilerServices.AsyncVoidMethodBuilder' is not defined or imported // async void M() {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "{}").WithArguments("System.Runtime.CompilerServices.AsyncVoidMethodBuilder").WithLocation(4, 20), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Create' // async void M() {} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{}").WithArguments("System.Runtime.CompilerServices.AsyncVoidMethodBuilder", "Create").WithLocation(4, 20), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext' // async void M() {} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{}").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "MoveNext").WithLocation(4, 20), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine' // async void M() {} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{}").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "SetStateMachine").WithLocation(4, 20)); } [Fact] public void MissingAsyncTaskMethodBuilder() { var source = @"using System.Threading.Tasks; class C { async Task M() {} }"; var comp = CSharpTestBase.CreateEmptyCompilation(source, new[] { Net40.mscorlib }, TestOptions.ReleaseDll); // NOTE: 4.0, not 4.5, so it's missing the async helpers. comp.VerifyEmitDiagnostics( // (4,16): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async Task M() {} Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(4, 16), // (4,20): error CS0518: Predefined type 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder' is not defined or imported // async Task M() {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "{}").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder").WithLocation(4, 20), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Create' // async Task M() {} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{}").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder", "Create").WithLocation(4, 20), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Task' // async Task M() {} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{}").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder", "Task").WithLocation(4, 20), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext' // async Task M() {} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{}").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "MoveNext").WithLocation(4, 20), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine' // async Task M() {} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{}").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "SetStateMachine").WithLocation(4, 20)); } [Fact] public void MissingAsyncTaskMethodBuilder_T() { var source = @"using System.Threading.Tasks; class C { async Task<int> F() => 3; }"; var comp = CSharpTestBase.CreateEmptyCompilation(source, new[] { Net40.mscorlib }, TestOptions.ReleaseDll); // NOTE: 4.0, not 4.5, so it's missing the async helpers. comp.VerifyEmitDiagnostics( // (4,21): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async Task<int> F() => 3; Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "F").WithLocation(4, 21), // (4,25): error CS0518: Predefined type 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1' is not defined or imported // async Task<int> F() => 3; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "=> 3").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1").WithLocation(4, 25), // (4,25): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Create' // async Task<int> F() => 3; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> 3").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1", "Create").WithLocation(4, 25), // (4,25): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Task' // async Task<int> F() => 3; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> 3").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1", "Task").WithLocation(4, 25), // (4,25): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext' // async Task<int> F() => 3; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> 3").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "MoveNext").WithLocation(4, 25), // (4,25): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine' // async Task<int> F() => 3; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> 3").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "SetStateMachine").WithLocation(4, 25)); } private static string AsyncBuilderCode(string builderTypeName, string tasklikeTypeName, string genericTypeParameter = null, bool isStruct = false) { string ofT = genericTypeParameter == null ? "" : "<" + genericTypeParameter + ">"; return $@" public {(isStruct ? "struct" : "class")} {builderTypeName}{ofT} {{ public static {builderTypeName}{ofT} Create() => default({builderTypeName}{ofT}); public {tasklikeTypeName}{ofT} Task {{ get; }} public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine {{ }} public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine {{ }} public void SetException(System.Exception exception) {{ }} public void SetResult({(genericTypeParameter == null ? "" : genericTypeParameter + " result")}) {{ }} public void SetStateMachine(IAsyncStateMachine stateMachine) {{ }} public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine {{ }} }} "; } [Fact] public void PresentAsyncTasklikeBuilderMethod() { var source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { async ValueTask f() { await (Task)null; } async ValueTask<int> g() { await (Task)null; return 1; } } [AsyncMethodBuilder(typeof(ValueTaskMethodBuilder))] struct ValueTask { } [AsyncMethodBuilder(typeof(ValueTaskMethodBuilder<>))] struct ValueTask<T> { } class ValueTaskMethodBuilder { public static ValueTaskMethodBuilder Create() => null; public ValueTask Task { get; } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } public void SetException(System.Exception exception) { } public void SetResult() { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } } class ValueTaskMethodBuilder<T> { public static ValueTaskMethodBuilder<T> Create() => null; public ValueTask<T> Task { get; } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } public void SetException(System.Exception exception) { } public void SetResult(T result) { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var v = CompileAndVerify(source, null, options: TestOptions.ReleaseDll); v.VerifyIL("C.g", @"{ // Code size 45 (0x2d) .maxstack 2 .locals init (C.<g>d__1 V_0) IL_0000: ldloca.s V_0 IL_0002: call ""ValueTaskMethodBuilder<int> ValueTaskMethodBuilder<int>.Create()"" IL_0007: stfld ""ValueTaskMethodBuilder<int> C.<g>d__1.<>t__builder"" IL_000c: ldloca.s V_0 IL_000e: ldc.i4.m1 IL_000f: stfld ""int C.<g>d__1.<>1__state"" IL_0014: ldloc.0 IL_0015: ldfld ""ValueTaskMethodBuilder<int> C.<g>d__1.<>t__builder"" IL_001a: ldloca.s V_0 IL_001c: callvirt ""void ValueTaskMethodBuilder<int>.Start<C.<g>d__1>(ref C.<g>d__1)"" IL_0021: ldloc.0 IL_0022: ldfld ""ValueTaskMethodBuilder<int> C.<g>d__1.<>t__builder"" IL_0027: callvirt ""ValueTask<int> ValueTaskMethodBuilder<int>.Task.get"" IL_002c: ret }"); v.VerifyIL("C.f", @"{ // Code size 45 (0x2d) .maxstack 2 .locals init (C.<f>d__0 V_0) IL_0000: ldloca.s V_0 IL_0002: call ""ValueTaskMethodBuilder ValueTaskMethodBuilder.Create()"" IL_0007: stfld ""ValueTaskMethodBuilder C.<f>d__0.<>t__builder"" IL_000c: ldloca.s V_0 IL_000e: ldc.i4.m1 IL_000f: stfld ""int C.<f>d__0.<>1__state"" IL_0014: ldloc.0 IL_0015: ldfld ""ValueTaskMethodBuilder C.<f>d__0.<>t__builder"" IL_001a: ldloca.s V_0 IL_001c: callvirt ""void ValueTaskMethodBuilder.Start<C.<f>d__0>(ref C.<f>d__0)"" IL_0021: ldloc.0 IL_0022: ldfld ""ValueTaskMethodBuilder C.<f>d__0.<>t__builder"" IL_0027: callvirt ""ValueTask ValueTaskMethodBuilder.Task.get"" IL_002c: ret }"); } [Fact] public void AsyncTasklikeGenericBuilder() { var source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; class N { class BN { } class BG<U> { } [AsyncMethodBuilder(typeof(N.BG<int>))] class T_NIT<V> { } [AsyncMethodBuilder(typeof(N.BG<int>))] class T_NIN { } [AsyncMethodBuilder(typeof(N.BG<>))] class T_NOT<V> { } [AsyncMethodBuilder(typeof(N.BG<>))] class T_NON { } [AsyncMethodBuilder(typeof(N.BN))] class T_NNT<V> { } [AsyncMethodBuilder(typeof(N.BN))] class T_NNN { } async T_NIT<int> f1() => await Task.FromResult(1); async T_NIN f2() => await Task.FromResult(1); async T_NOT<int> f3() => await Task.FromResult(1); // ok builderType genericity (but missing members) async T_NON f4() => await Task.FromResult(1); async T_NNT<int> f5() => await Task.FromResult(1); async T_NNN f6() => await Task.FromResult(1); // ok builderType genericity (but missing members) } class G<T> { class BN { } class BG<U> { } [AsyncMethodBuilder(typeof(G<int>.BG<int>))] class T_IIT<V> { } [AsyncMethodBuilder(typeof(G<int>.BG<int>))] class T_IIN { } [AsyncMethodBuilder(typeof(G<int>.BN))] class T_INT<V> { } [AsyncMethodBuilder(typeof(G<int>.BN))] class T_INN { } [AsyncMethodBuilder(typeof(G<>.BG<>))] class T_OOT<V> { } [AsyncMethodBuilder(typeof(G<>.BG<>))] class T_OON { } [AsyncMethodBuilder(typeof(G<>.BN))] class T_ONT<V> { } [AsyncMethodBuilder(typeof(G<>.BN))] class T_ONN { } async T_IIT<int> g1() => await Task.FromResult(1); async T_IIN g2() => await Task.FromResult(1); async T_INT<int> g3() => await Task.FromResult(1); async T_INN g4() => await Task.FromResult(1); // might have been ok builder genericity but we decided not async T_OOT<int> g5() => await Task.FromResult(1); async T_OON g6() => await Task.FromResult(1); async T_ONT<int> g7() => await Task.FromResult(1); async T_ONN g8() => await Task.FromResult(1); } class Program { static void Main() { } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (17,27): error CS8940: A generic task-like return type was expected, but the type 'N.BG<int>' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. // async T_NIT<int> f1() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_WrongArityAsyncReturn, "=> await Task.FromResult(1)").WithArguments("N.BG<int>").WithLocation(17, 27), // (18,22): error CS1983: The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T> // async T_NIN f2() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.FromResult(1)").WithLocation(18, 22), // (19,27): error CS0656: Missing compiler required member 'N.BG<int>.Task' // async T_NOT<int> f3() => await Task.FromResult(1); // ok builderType genericity (but missing members) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.FromResult(1)").WithArguments("N.BG<int>", "Task").WithLocation(19, 27), // (19,27): error CS0656: Missing compiler required member 'N.BG<int>.Create' // async T_NOT<int> f3() => await Task.FromResult(1); // ok builderType genericity (but missing members) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.FromResult(1)").WithArguments("N.BG<int>", "Create").WithLocation(19, 27), // (20,22): error CS1983: The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T> // async T_NON f4() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.FromResult(1)").WithLocation(20, 22), // (21,27): error CS8940: A generic task-like return type was expected, but the type 'N.BN' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. // async T_NNT<int> f5() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_WrongArityAsyncReturn, "=> await Task.FromResult(1)").WithArguments("N.BN").WithLocation(21, 27), // (22,22): error CS0656: Missing compiler required member 'N.BN.Task' // async T_NNN f6() => await Task.FromResult(1); // ok builderType genericity (but missing members) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.FromResult(1)").WithArguments("N.BN", "Task").WithLocation(22, 22), // (22,22): error CS0656: Missing compiler required member 'N.BN.Create' // async T_NNN f6() => await Task.FromResult(1); // ok builderType genericity (but missing members) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.FromResult(1)").WithArguments("N.BN", "Create").WithLocation(22, 22), // (39,27): error CS8940: A generic task-like return type was expected, but the type 'G<int>.BG<int>' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. // async T_IIT<int> g1() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_WrongArityAsyncReturn, "=> await Task.FromResult(1)").WithArguments("G<int>.BG<int>").WithLocation(39, 27), // (40,22): error CS1983: The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T> // async T_IIN g2() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.FromResult(1)").WithLocation(40, 22), // (41,27): error CS8940: A generic task-like return type was expected, but the type 'G<int>.BN' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. // async T_INT<int> g3() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_WrongArityAsyncReturn, "=> await Task.FromResult(1)").WithArguments("G<int>.BN").WithLocation(41, 27), // (42,22): error CS1983: The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T> // async T_INN g4() => await Task.FromResult(1); // might have been ok builder genericity but we decided not Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.FromResult(1)").WithLocation(42, 22), // (43,27): error CS8940: A generic task-like return type was expected, but the type 'G<>.BG<>' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. // async T_OOT<int> g5() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_WrongArityAsyncReturn, "=> await Task.FromResult(1)").WithArguments("G<>.BG<>").WithLocation(43, 27), // (44,22): error CS1983: The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T> // async T_OON g6() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.FromResult(1)").WithLocation(44, 22), // (45,27): error CS8940: A generic task-like return type was expected, but the type 'G<>.BN' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. // async T_ONT<int> g7() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_WrongArityAsyncReturn, "=> await Task.FromResult(1)").WithArguments("G<>.BN").WithLocation(45, 27), // (46,22): error CS1983: The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T> // async T_ONN g8() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.FromResult(1)").WithLocation(46, 22) ); } [Fact] public void AsyncTasklikeBadAttributeArgument1() { var source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; [AsyncMethodBuilder(typeof(void))] class T { } class Program { static void Main() { } async T f() => await Task.Delay(1); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (9,17): error CS1983: The return type of an async method must be void, Task or Task<T> // async T f() => await Task.Delay(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.Delay(1)").WithLocation(9, 17) ); } [Fact] public void AsyncTasklikeBadAttributeArgument2() { var source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; [AsyncMethodBuilder(""hello"")] class T { } class Program { static void Main() { } async T f() => await Task.Delay(1); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (5,15): error CS1503: Argument 1: cannot convert from 'string' to 'System.Type' // [AsyncMethodBuilder("hello")] class T { } Diagnostic(ErrorCode.ERR_BadArgType, @"""hello""").WithArguments("1", "string", "System.Type").WithLocation(5, 21), // (9,13): error CS1983: The return type of an async method must be void, Task or Task<T> // async T f() => await Task.Delay(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "f").WithLocation(9, 13) ); } [Fact] public void AsyncTasklikeBadAttributeArgument3() { var source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; [AsyncMethodBuilder(typeof(Nonexistent))] class T { } class Program { static void Main() { } async T f() => await Task.Delay(1); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (5,22): error CS0246: The type or namespace name 'Nonexistent' could not be found (are you missing a using directive or an assembly reference?) // [AsyncMethodBuilder(typeof(Nonexistent))] class T { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nonexistent").WithArguments("Nonexistent").WithLocation(5, 28) ); } [Fact] public void AsyncTasklikeBadAttributeArgument4() { var source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; [AsyncMethodBuilder(null)] class T { } class Program { static void Main() { } async T f() => await Task.Delay(1); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (9,17): error CS1983: The return type of an async method must be void, Task or Task<T> // async T f() => await Task.Delay(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.Delay(1)").WithLocation(9, 17) ); } [Fact] public void AsyncTasklikeMissingBuilderType() { // Builder var libB = @"public class B { }"; var cB = CreateCompilationWithMscorlib45(libB); var rB = cB.EmitToImageReference(); // Tasklike var libT = @" using System.Runtime.CompilerServices; [AsyncMethodBuilder(typeof(B))] public class T { } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var cT = CreateCompilationWithMscorlib45(libT, references: new[] { rB }); var rT = cT.EmitToImageReference(); // Consumer, fails to reference builder var source = @" using System.Threading.Tasks; class Program { static void Main() { } async T f() => await Task.Delay(1); } "; var c = CreateCompilationWithMscorlib45(source, references: new[] { rT }); c.VerifyEmitDiagnostics( // (6,17): error CS1983: The return type of an async method must be void, Task or Task<T> // async T f() => await Task.Delay(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.Delay(1)").WithLocation(6, 17) ); } [Fact] public void AsyncTasklikeCreateMethod() { var source = $@" using System.Runtime.CompilerServices; using System.Threading.Tasks; class Program {{ static void Main() {{ }} async T0 f0() => await Task.Delay(0); async T1 f1() => await Task.Delay(1); async T2 f2() => await Task.Delay(2); async T3 f3() => await Task.Delay(3); async T4 f4() => await Task.Delay(4); async T5 f5() => await Task.Delay(5); async T6 f6() => await Task.Delay(6); async T7 f7() => await Task.Delay(7); async T8 f8() => await Task.Delay(8); }} [AsyncMethodBuilder(typeof(B0))] public class T0 {{ }} [AsyncMethodBuilder(typeof(B1))] public class T1 {{ }} [AsyncMethodBuilder(typeof(B2))] public class T2 {{ }} [AsyncMethodBuilder(typeof(B3))] public class T3 {{ }} [AsyncMethodBuilder(typeof(B4))] public class T4 {{ }} [AsyncMethodBuilder(typeof(B5))] public class T5 {{ }} [AsyncMethodBuilder(typeof(B6))] public class T6 {{ }} [AsyncMethodBuilder(typeof(B7))] public class T7 {{ }} [AsyncMethodBuilder(typeof(B8))] public class T8 {{ }} {AsyncBuilderCode("B0", "T0").Replace("public static B0 Create()", "public static B0 Create()")} {AsyncBuilderCode("B1", "T1").Replace("public static B1 Create()", "private static B1 Create()")} {AsyncBuilderCode("B2", "T2").Replace("public static B2 Create() => default(B2);", "public static void Create() { }")} {AsyncBuilderCode("B3", "T3").Replace("public static B3 Create() => default(B3);", "public static B1 Create() => default(B1);")} {AsyncBuilderCode("B4", "T4").Replace("public static B4 Create()", "public static B4 Create(int i)")} {AsyncBuilderCode("B5", "T5").Replace("public static B5 Create()", "public static B5 Create<T>()")} {AsyncBuilderCode("B6", "T6").Replace("public static B6 Create()", "public static B6 Create(object arg = null)")} {AsyncBuilderCode("B7", "T7").Replace("public static B7 Create()", "public static B7 Create(params object[] arg)")} {AsyncBuilderCode("B8", "T8").Replace("public static B8 Create()", "public B8 Create()")} namespace System.Runtime.CompilerServices {{ class AsyncMethodBuilderAttribute : System.Attribute {{ public AsyncMethodBuilderAttribute(System.Type t) {{ }} }} }} "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (8,19): error CS0656: Missing compiler required member 'B1.Create' // async T1 f1() => await Task.Delay(1); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.Delay(1)").WithArguments("B1", "Create").WithLocation(8, 19), // (9,19): error CS0656: Missing compiler required member 'B2.Create' // async T2 f2() => await Task.Delay(2); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.Delay(2)").WithArguments("B2", "Create").WithLocation(9, 19), // (10,19): error CS0656: Missing compiler required member 'B3.Create' // async T3 f3() => await Task.Delay(3); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.Delay(3)").WithArguments("B3", "Create").WithLocation(10, 19), // (11,19): error CS0656: Missing compiler required member 'B4.Create' // async T4 f4() => await Task.Delay(4); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.Delay(4)").WithArguments("B4", "Create").WithLocation(11, 19), // (12,19): error CS0656: Missing compiler required member 'B5.Create' // async T5 f5() => await Task.Delay(5); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.Delay(5)").WithArguments("B5", "Create").WithLocation(12, 19), // (13,19): error CS0656: Missing compiler required member 'B6.Create' // async T6 f6() => await Task.Delay(6); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.Delay(6)").WithArguments("B6", "Create").WithLocation(13, 19), // (14,19): error CS0656: Missing compiler required member 'B7.Create' // async T7 f7() => await Task.Delay(7); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.Delay(7)").WithArguments("B7", "Create").WithLocation(14, 19), // (15,19): error CS0656: Missing compiler required member 'B8.Create' // async T8 f8() => await Task.Delay(8); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.Delay(8)").WithArguments("B8", "Create").WithLocation(15, 19) ); } [Fact] public void AsyncInterfaceTasklike() { var source = $@" using System.Runtime.CompilerServices; using System.Threading.Tasks; class Program {{ static void Main() {{ }} async I0 f0() => await Task.Delay(0); async I1<int> f1() {{ await Task.Delay(1); return 1; }} }} [AsyncMethodBuilder(typeof(B0))] public interface I0 {{ }} [AsyncMethodBuilder(typeof(B1<>))] public interface I1<T> {{ }} {AsyncBuilderCode("B0", "I0", genericTypeParameter: null)} {AsyncBuilderCode("B1", "I1", genericTypeParameter: "T")} namespace System.Runtime.CompilerServices {{ class AsyncMethodBuilderAttribute : System.Attribute {{ public AsyncMethodBuilderAttribute(System.Type t) {{ }} }} }} "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( ); } [Fact] public void AsyncTasklikeBuilderAccessibility() { var source = $@" using System.Runtime.CompilerServices; using System.Threading.Tasks; [AsyncMethodBuilder(typeof(B1))] public class T1 {{ }} [AsyncMethodBuilder(typeof(B2))] public class T2 {{ }} [AsyncMethodBuilder(typeof(B3))] internal class T3 {{ }} [AsyncMethodBuilder(typeof(B4))] internal class T4 {{ }} {AsyncBuilderCode("B1", "T1").Replace("public class B1", "public class B1")} {AsyncBuilderCode("B2", "T2").Replace("public class B2", "internal class B2")} {AsyncBuilderCode("B3", "T3").Replace("public class B3", "public class B3").Replace("public T3 Task { get; }", "internal T3 Task {get; }")} {AsyncBuilderCode("B4", "T4").Replace("public class B4", "internal class B4")} class Program {{ static void Main() {{ }} async T1 f1() => await Task.Delay(1); async T2 f2() => await Task.Delay(2); async T3 f3() => await Task.Delay(3); async T4 f4() => await Task.Delay(4); }} namespace System.Runtime.CompilerServices {{ class AsyncMethodBuilderAttribute : System.Attribute {{ public AsyncMethodBuilderAttribute(System.Type t) {{ }} }} }} "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (66,19): error CS1983: The return type of an async method must be void, Task or Task<T> // async T2 f2() => await Task.Delay(2); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.Delay(2)").WithLocation(66, 19), // (67,19): error CS1983: The return type of an async method must be void, Task or Task<T> // async T3 f3() => await Task.Delay(3); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.Delay(3)").WithLocation(67, 19) ); } [Fact] public void AsyncTasklikeLambdaOverloads() { var source = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { static void Main() { f(async () => { await (Task)null; }); g(async () => { await (Task)null; }); k(async () => { await (Task)null; }); } static void f(Func<MyTask> lambda) { } static void g(Func<Task> lambda) { } static void k<T>(Func<T> lambda) { } } [AsyncMethodBuilder(typeof(MyTaskBuilder))] class MyTask { } class MyTaskBuilder { public static MyTaskBuilder Create() => null; public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void SetResult() { } public void SetException(Exception exception) { } public MyTask Task => default(MyTask); public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var v = CompileAndVerify(source, null, options: TestOptions.ReleaseDll); v.VerifyIL("C.Main", @" { // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""System.Func<MyTask> C.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""C.<>c C.<>c.<>9"" IL_000e: ldftn ""MyTask C.<>c.<Main>b__0_0()"" IL_0014: newobj ""System.Func<MyTask>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Func<MyTask> C.<>c.<>9__0_0"" IL_001f: call ""void C.f(System.Func<MyTask>)"" IL_0024: ldsfld ""System.Func<System.Threading.Tasks.Task> C.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""C.<>c C.<>c.<>9"" IL_0032: ldftn ""System.Threading.Tasks.Task C.<>c.<Main>b__0_1()"" IL_0038: newobj ""System.Func<System.Threading.Tasks.Task>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""System.Func<System.Threading.Tasks.Task> C.<>c.<>9__0_1"" IL_0043: call ""void C.g(System.Func<System.Threading.Tasks.Task>)"" IL_0048: ldsfld ""System.Func<System.Threading.Tasks.Task> C.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""C.<>c C.<>c.<>9"" IL_0056: ldftn ""System.Threading.Tasks.Task C.<>c.<Main>b__0_2()"" IL_005c: newobj ""System.Func<System.Threading.Tasks.Task>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""System.Func<System.Threading.Tasks.Task> C.<>c.<>9__0_2"" IL_0067: call ""void C.k<System.Threading.Tasks.Task>(System.Func<System.Threading.Tasks.Task>)"" IL_006c: ret }"); } [Fact] public void AsyncTasklikeIncompleteBuilder() { var source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { static void Main() { } async ValueTask0 f() { await Task.Delay(0); } async ValueTask1 g() { await Task.Delay(0); } async ValueTask2 h() { await Task.Delay(0); } } [AsyncMethodBuilder(typeof(ValueTaskMethodBuilder0))] struct ValueTask0 { } [AsyncMethodBuilder(typeof(ValueTaskMethodBuilder1))] struct ValueTask1 { } [AsyncMethodBuilder(typeof(ValueTaskMethodBuilder2))] struct ValueTask2 { } class ValueTaskMethodBuilder0 { public static ValueTaskMethodBuilder0 Create() => null; public ValueTask0 Task => default(ValueTask0); } class ValueTaskMethodBuilder1 { public static ValueTaskMethodBuilder1 Create() => null; public ValueTask1 Task => default(ValueTask1); public void SetException(System.Exception ex) { } } class ValueTaskMethodBuilder2 { public static ValueTaskMethodBuilder2 Create() => null; public ValueTask2 Task => default(ValueTask2); public void SetException(System.Exception ex) { } public void SetResult() { } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (7,26): error CS0656: Missing compiler required member 'ValueTaskMethodBuilder0.SetException' // async ValueTask0 f() { await Task.Delay(0); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); }").WithArguments("ValueTaskMethodBuilder0", "SetException").WithLocation(7, 26), // (8,26): error CS0656: Missing compiler required member 'ValueTaskMethodBuilder1.SetResult' // async ValueTask1 g() { await Task.Delay(0); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); }").WithArguments("ValueTaskMethodBuilder1", "SetResult").WithLocation(8, 26), // (9,26): error CS0656: Missing compiler required member 'ValueTaskMethodBuilder2.AwaitOnCompleted' // async ValueTask2 h() { await Task.Delay(0); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); }").WithArguments("ValueTaskMethodBuilder2", "AwaitOnCompleted").WithLocation(9, 26) ); } [Fact] public void AsyncTasklikeBuilderArityMismatch() { var source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { async Mismatch1<int> f() { await (Task)null; return 1; } async Mismatch2 g() { await (Task)null; return 1; } } [AsyncMethodBuilder(typeof(Mismatch1MethodBuilder))] struct Mismatch1<T> { } [AsyncMethodBuilder(typeof(Mismatch2MethodBuilder<>))] struct Mismatch2 { } class Mismatch1MethodBuilder { public static Mismatch1MethodBuilder Create() => null; } class Mismatch2MethodBuilder<T> { public static Mismatch2MethodBuilder<T> Create() => null; } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp = CreateCompilationWithMscorlib45(source); comp.VerifyEmitDiagnostics( // (5,30): error CS8940: A generic task-like return type was expected, but the type 'Mismatch1MethodBuilder' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. // async Mismatch1<int> f() { await (Task)null; return 1; } Diagnostic(ErrorCode.ERR_WrongArityAsyncReturn, "{ await (Task)null; return 1; }").WithArguments("Mismatch1MethodBuilder").WithLocation(5, 30), // (6,45): error CS1997: Since 'C.g()' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>'? // async Mismatch2 g() { await (Task)null; return 1; } Diagnostic(ErrorCode.ERR_TaskRetNoObjectRequired, "return").WithArguments("C.g()").WithLocation(6, 45) ); } [WorkItem(12616, "https://github.com/dotnet/roslyn/issues/12616")] [Fact] public void AsyncTasklikeBuilderConstraints() { var source1 = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { static void Main() { } async MyTask f() { await (Task)null; } } [AsyncMethodBuilder(typeof(MyTaskBuilder))] class MyTask { } interface I { } class MyTaskBuilder { public static MyTaskBuilder Create() => null; public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void Start<TSM>(ref TSM stateMachine) where TSM : I { } public void AwaitOnCompleted<TA, TSM>(ref TA awaiter, ref TSM stateMachine) { } public void AwaitUnsafeOnCompleted<TA, TSM>(ref TA awaiter, ref TSM stateMachine) { } public void SetResult() { } public void SetException(Exception ex) { } public MyTask Task => null; } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp1 = CreateCompilation(source1, options: TestOptions.DebugExe); comp1.VerifyEmitDiagnostics( // (8,22): error CS0311: The type 'C.<f>d__1' cannot be used as type parameter 'TSM' in the generic type or method 'MyTaskBuilder.Start<TSM>(ref TSM)'. There is no implicit reference conversion from 'C.<f>d__1' to 'I'. // async MyTask f() { await (Task)null; } Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "{ await (Task)null; }").WithArguments("MyTaskBuilder.Start<TSM>(ref TSM)", "I", "TSM", "C.<f>d__1").WithLocation(8, 22)); var source2 = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { static void Main() { } async MyTask f() { await (Task)null; } } [AsyncMethodBuilder(typeof(MyTaskBuilder))] class MyTask { } class MyTaskBuilder { public static MyTaskBuilder Create() => null; public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void Start<TSM>(ref TSM stateMachine) where TSM : IAsyncStateMachine { } public void AwaitOnCompleted<TA, TSM>(ref TA awaiter, ref TSM stateMachine) where TA : INotifyCompletion where TSM : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TA, TSM>(ref TA awaiter, ref TSM stateMachine) { } public void SetResult() { } public void SetException(Exception ex) { } public MyTask Task => null; } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp2 = CreateCompilation(source2, options: TestOptions.DebugExe); comp2.VerifyEmitDiagnostics(); } [Fact] [WorkItem(868822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/868822")] public void AsyncDelegates() { var source = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { test1(); test2(); } static void test1() { Invoke(async delegate { if (0.ToString().Length == 0) { await Task.Yield(); } else { System.Console.WriteLine(0.ToString()); } }); } static string test2() { return Invoke(async delegate { if (0.ToString().Length == 0) { await Task.Yield(); return 1.ToString(); } else { System.Console.WriteLine(2.ToString()); return null; } }); } static void Invoke(Action method) { method(); } static void Invoke(Func<Task> method) { method().Wait(); } static TResult Invoke<TResult>(Func<TResult> method) { return method(); } internal static TResult Invoke<TResult>(Func<Task<TResult>> method) { if (method != null) { return Invoke1(async delegate { await Task.Yield(); return await method(); }); } return default(TResult); } internal static TResult Invoke1<TResult>(Func<Task<TResult>> method) { return method().Result; } } "; var expected = @"0 2"; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void MutatingArrayOfStructs() { var source = @" using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; struct S { public int A; public int Mutate(int b) { A += b; return 1; } } class Test { static int i = 0; public static Task<int> G() { return null; } public static async Task<int> F() { S[] array = new S[10]; return array[1].Mutate(await G()); } }"; var v = CompileAndVerify(source, null, options: TestOptions.DebugDll); v.VerifyIL("Test.<F>d__2.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 241 (0xf1) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, Test.<F>d__2 V_3, System.Exception V_4) ~IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<F>d__2.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_0070 -IL_000e: nop -IL_000f: ldarg.0 IL_0010: ldc.i4.s 10 IL_0012: newarr ""S"" IL_0017: stfld ""S[] Test.<F>d__2.<array>5__1"" -IL_001c: ldarg.0 IL_001d: ldarg.0 IL_001e: ldfld ""S[] Test.<F>d__2.<array>5__1"" IL_0023: stfld ""S[] Test.<F>d__2.<>s__3"" IL_0028: ldarg.0 IL_0029: ldfld ""S[] Test.<F>d__2.<>s__3"" IL_002e: ldc.i4.1 IL_002f: ldelema ""S"" IL_0034: pop IL_0035: call ""System.Threading.Tasks.Task<int> Test.G()"" IL_003a: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_003f: stloc.2 ~IL_0040: ldloca.s V_2 IL_0042: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0047: brtrue.s IL_008c IL_0049: ldarg.0 IL_004a: ldc.i4.0 IL_004b: dup IL_004c: stloc.0 IL_004d: stfld ""int Test.<F>d__2.<>1__state"" <IL_0052: ldarg.0 IL_0053: ldloc.2 IL_0054: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_0059: ldarg.0 IL_005a: stloc.3 IL_005b: ldarg.0 IL_005c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_0061: ldloca.s V_2 IL_0063: ldloca.s V_3 IL_0065: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<F>d__2>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<F>d__2)"" IL_006a: nop IL_006b: leave IL_00f0 >IL_0070: ldarg.0 IL_0071: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_0076: stloc.2 IL_0077: ldarg.0 IL_0078: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_007d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0083: ldarg.0 IL_0084: ldc.i4.m1 IL_0085: dup IL_0086: stloc.0 IL_0087: stfld ""int Test.<F>d__2.<>1__state"" IL_008c: ldarg.0 IL_008d: ldloca.s V_2 IL_008f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0094: stfld ""int Test.<F>d__2.<>s__2"" IL_0099: ldarg.0 IL_009a: ldfld ""S[] Test.<F>d__2.<>s__3"" IL_009f: ldc.i4.1 IL_00a0: ldelema ""S"" IL_00a5: ldarg.0 IL_00a6: ldfld ""int Test.<F>d__2.<>s__2"" IL_00ab: call ""int S.Mutate(int)"" IL_00b0: stloc.1 IL_00b1: leave.s IL_00d4 } catch System.Exception { ~IL_00b3: stloc.s V_4 IL_00b5: ldarg.0 IL_00b6: ldc.i4.s -2 IL_00b8: stfld ""int Test.<F>d__2.<>1__state"" IL_00bd: ldarg.0 IL_00be: ldnull IL_00bf: stfld ""S[] Test.<F>d__2.<array>5__1"" IL_00c4: ldarg.0 IL_00c5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_00ca: ldloc.s V_4 IL_00cc: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00d1: nop IL_00d2: leave.s IL_00f0 } -IL_00d4: ldarg.0 IL_00d5: ldc.i4.s -2 IL_00d7: stfld ""int Test.<F>d__2.<>1__state"" ~IL_00dc: ldarg.0 IL_00dd: ldnull IL_00de: stfld ""S[] Test.<F>d__2.<array>5__1"" IL_00e3: ldarg.0 IL_00e4: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_00e9: ldloc.1 IL_00ea: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00ef: nop IL_00f0: ret }", sequencePoints: "Test+<F>d__2.MoveNext"); } [Fact] public void MutatingStructWithUsing() { var source = @"using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; class Program { public static void Main() { (new Program()).Test().Wait(); } public async Task Test() { var list = new List<int> {1, 2, 3}; using (var enumerator = list.GetEnumerator()) { Console.WriteLine(enumerator.MoveNext()); Console.WriteLine(enumerator.Current); await Task.Delay(1); } } }"; var expectedOutput = @"True 1"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: expectedOutput); } [Fact, WorkItem(1942, "https://github.com/dotnet/roslyn/issues/1942")] public void HoistStructure() { var source = @" using System; using System.Threading.Tasks; namespace ConsoleApp { struct TestStruct { public long i; public long j; } class Program { static async Task TestAsync() { TestStruct t; t.i = 12; Console.WriteLine(""Before {0}"", t.i); // emits ""Before 12"" await Task.Delay(100); Console.WriteLine(""After {0}"", t.i); // emits ""After 0"" expecting ""After 12"" } static void Main(string[] args) { TestAsync().Wait(); } } }"; var expectedOutput = @"Before 12 After 12"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: expectedOutput); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe), expectedOutput: expectedOutput); } [Fact, WorkItem(2567, "https://github.com/dotnet/roslyn/issues/2567")] public void AwaitInUsingAndForeach() { var source = @" using System.Threading.Tasks; using System; class Program { System.Collections.Generic.IEnumerable<int> ien = null; async Task<int> Test(IDisposable id, Task<int> task) { try { foreach (var i in ien) { return await task; } using (id) { return await task; } } catch (Exception) { return await task; } } public static void Main() {} }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe)); } [Fact, WorkItem(4697, "https://github.com/dotnet/roslyn/issues/4697")] public void AwaitInObjInitializer() { var source = @" using System; using System.Threading.Tasks; namespace CompilerCrashRepro2 { public class Item<T> { public T Value { get; set; } } public class Crasher { public static void Main() { var r = Build<int>()().Result.Value; System.Console.WriteLine(r); } public static Func<Task<Item<T>>> Build<T>() { return async () => new Item<T>() { Value = await GetValue<T>() }; } public static Task<T> GetValue<T>() { return Task.FromResult(default(T)); } } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "0"); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe), expectedOutput: "0"); } [Fact] public void AwaitInScriptExpression() { var source = @"System.Console.WriteLine(await System.Threading.Tasks.Task.FromResult(1));"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); } [Fact] public void AwaitInScriptGlobalStatement() { var source = @"await System.Threading.Tasks.Task.FromResult(4);"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); } [Fact] public void AwaitInScriptDeclaration() { var source = @"int x = await System.Threading.Tasks.Task.Run(() => 2); System.Console.WriteLine(x);"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); } [Fact] public void AwaitInInteractiveExpression() { var references = new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef }; var source0 = @"static async System.Threading.Tasks.Task<int> F() { return await System.Threading.Tasks.Task.FromResult(3); }"; var source1 = @"await F()"; var s0 = CSharpCompilation.CreateScriptCompilation("s0.dll", SyntaxFactory.ParseSyntaxTree(source0, options: TestOptions.Script), references); var s1 = CSharpCompilation.CreateScriptCompilation("s1.dll", SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.Script), references, previousScriptCompilation: s0); s1.VerifyDiagnostics(); } [Fact] public void AwaitInInteractiveGlobalStatement() { var references = new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef }; var source0 = @"await System.Threading.Tasks.Task.FromResult(5);"; var s0 = CSharpCompilation.CreateScriptCompilation("s0.dll", SyntaxFactory.ParseSyntaxTree(source0, options: TestOptions.Script), references); s0.VerifyDiagnostics(); } /// <summary> /// await should be disallowed in static field initializer /// since the static initialization of the class must be /// handled synchronously in the .cctor. /// </summary> [WorkItem(5787, "https://github.com/dotnet/roslyn/issues/5787")] [Fact] public void AwaitInScriptStaticInitializer() { var source = @"static int x = 1 + await System.Threading.Tasks.Task.FromResult(1); int y = x + await System.Threading.Tasks.Task.FromResult(2);"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (2,5): error CS8100: The 'await' operator cannot be used in a static script variable initializer. // await System.Threading.Tasks.Task.FromResult(1); Diagnostic(ErrorCode.ERR_BadAwaitInStaticVariableInitializer, "await System.Threading.Tasks.Task.FromResult(1)").WithLocation(2, 5)); } [Fact, WorkItem(4839, "https://github.com/dotnet/roslyn/issues/4839")] public void SwitchOnAwaitedValueAsync() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main() { M(0).Wait(); } static async Task M(int input) { var value = 1; switch (value) { case 0: return; case 1: return; } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe)); } [Fact, WorkItem(4839, "https://github.com/dotnet/roslyn/issues/4839")] public void SwitchOnAwaitedValue() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main() { M(0); } static void M(int input) { try { var value = 1; switch (value) { case 1: return; case 2: return; } } catch (Exception) { } } } "; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp). VerifyIL("Program.M(int)", @" { // Code size 16 (0x10) .maxstack 2 .locals init (int V_0) //value .try { IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: beq.s IL_000a IL_0006: ldloc.0 IL_0007: ldc.i4.2 IL_0008: pop IL_0009: pop IL_000a: leave.s IL_000f } catch System.Exception { IL_000c: pop IL_000d: leave.s IL_000f } IL_000f: ret }"); } [Fact, WorkItem(4839, "https://github.com/dotnet/roslyn/issues/4839")] public void SwitchOnAwaitedValueString() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main() { M(0).Wait(); } static async Task M(int input) { var value = ""q""; switch (value) { case ""a"": return; case ""b"": return; } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe)); } [Fact, WorkItem(4838, "https://github.com/dotnet/roslyn/issues/4838")] public void SwitchOnAwaitedValueInLoop() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main() { M(0).Wait(); } static async Task M(int input) { for (;;) { var value = await Task.FromResult(input); switch (value) { case 0: return; case 3: return; case 4: continue; case 100: return; default: throw new ArgumentOutOfRangeException(""Unknown value: "" + value); } } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe)); } [Fact, WorkItem(7669, "https://github.com/dotnet/roslyn/issues/7669")] public void HoistUsing001() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main() { System.Console.WriteLine(M(0).Result); } class D : IDisposable { public void Dispose() { Console.WriteLine(""disposed""); } } static async Task<string> M(int input) { Console.WriteLine(""Pre""); var window = new D(); try { Console.WriteLine(""show""); for (int i = 0; i < 2; i++) { await Task.Delay(100); } } finally { window.Dispose(); } Console.WriteLine(""Post""); return ""result""; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); var expectedOutput = @"Pre show disposed Post result"; CompileAndVerify(comp, expectedOutput: expectedOutput); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe), expectedOutput: expectedOutput); } [Fact, WorkItem(7669, "https://github.com/dotnet/roslyn/issues/7669")] public void HoistUsing002() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main() { System.Console.WriteLine(M(0).Result); } class D : IDisposable { public void Dispose() { Console.WriteLine(""disposed""); } } static async Task<string> M(int input) { Console.WriteLine(""Pre""); using (var window = new D()) { Console.WriteLine(""show""); for (int i = 0; i < 2; i++) { await Task.Delay(100); } } Console.WriteLine(""Post""); return ""result""; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); var expectedOutput = @"Pre show disposed Post result"; CompileAndVerify(comp, expectedOutput: expectedOutput); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe), expectedOutput: expectedOutput); } [Fact, WorkItem(7669, "https://github.com/dotnet/roslyn/issues/7669")] public void HoistUsing003() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main() { System.Console.WriteLine(M(0).Result); } class D : IDisposable { public void Dispose() { Console.WriteLine(""disposed""); } } static async Task<string> M(int input) { Console.WriteLine(""Pre""); using (var window1 = new D()) { Console.WriteLine(""show""); using (var window = new D()) { Console.WriteLine(""show""); for (int i = 0; i < 2; i++) { await Task.Delay(100); } } } Console.WriteLine(""Post""); return ""result""; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); var expectedOutput = @"Pre show show disposed disposed Post result"; CompileAndVerify(comp, expectedOutput: expectedOutput); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe), expectedOutput: expectedOutput); } [Fact, WorkItem(9463, "https://github.com/dotnet/roslyn/issues/9463")] public void AsyncIteratorReportsDiagnosticsWhenCoreTypesAreMissing() { // Note that IAsyncStateMachine.MoveNext and IAsyncStateMachine.SetStateMachine are missing var source = @" using System.Threading.Tasks; namespace System { public class Object { } public struct Int32 { } public struct Boolean { } public class String { } public class Exception { } public class ValueType { } public class Enum { } public struct Void { } } namespace System.Threading.Tasks { public class Task { public TaskAwaiter GetAwaiter() { return null; } } public class TaskAwaiter : System.Runtime.CompilerServices.INotifyCompletion { public bool IsCompleted { get { return true; } } public void GetResult() { } } } namespace System.Runtime.CompilerServices { public interface INotifyCompletion { } public interface ICriticalNotifyCompletion { } public interface IAsyncStateMachine { } public class AsyncTaskMethodBuilder { public System.Threading.Tasks.Task Task { get { return null; } } public void SetException(System.Exception e) { } public void SetResult() { } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } } } class C { async Task GetNumber(Task task) { await task; } }"; var compilation = CreateEmptyCompilation(new[] { Parse(source) }); compilation.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (62,37): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Create' // async Task GetNumber(Task task) { await task; } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await task; }").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder", "Create").WithLocation(62, 37), // (62,37): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext' // async Task GetNumber(Task task) { await task; } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await task; }").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "MoveNext").WithLocation(62, 37), // (62,37): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine' // async Task GetNumber(Task task) { await task; } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await task; }").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "SetStateMachine").WithLocation(62, 37)); } [Fact, WorkItem(16531, "https://github.com/dotnet/roslyn/issues/16531")] public void ArityMismatch() { var source = @" using System; using System.Threading.Tasks; using System.Runtime.CompilerServices; public class Program { public async MyAwesomeType<string> CustomTask() { await Task.Delay(1000); return string.Empty; } } [AsyncMethodBuilder(typeof(CustomAsyncTaskMethodBuilder<,>))] public struct MyAwesomeType<T> { public T Result { get; set; } } public class CustomAsyncTaskMethodBuilder<T, V> { public MyAwesomeType<T> Task => default(MyAwesomeType<T>); public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } public static CustomAsyncTaskMethodBuilder<T, V> Create() { return default(CustomAsyncTaskMethodBuilder<T, V>); } public void SetException(Exception exception) { } public void SetResult(T t) { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } } namespace System.Runtime.CompilerServices { public class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(Type type) { } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugDll); compilation.VerifyEmitDiagnostics( // (8,53): error CS8940: A generic task-like return type was expected, but the type 'CustomAsyncTaskMethodBuilder<,>' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. // public async MyAwesomeType<string> CustomTask() { await Task.Delay(1000); return string.Empty; } Diagnostic(ErrorCode.ERR_WrongArityAsyncReturn, "{ await Task.Delay(1000); return string.Empty; }").WithArguments("CustomAsyncTaskMethodBuilder<,>").WithLocation(8, 53) ); } [Fact, WorkItem(16493, "https://github.com/dotnet/roslyn/issues/16493")] public void AsyncMethodBuilderReturnsDifferentTypeThanTasklikeType() { var source = @" using System; using System.Threading.Tasks; using System.Runtime.CompilerServices; public class G<T> { public async ValueTask Method() { await Task.Delay(5); return; } [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder))] public struct ValueTask { } } public class AsyncValueTaskMethodBuilder { public G<int>.ValueTask Task { get => default(G<int>.ValueTask); } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } public static AsyncValueTaskMethodBuilder Create() { return default(AsyncValueTaskMethodBuilder); } public void SetException(Exception exception) { } public void SetResult() { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } } namespace System.Runtime.CompilerServices { public class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(Type type) { } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugDll); compilation.VerifyEmitDiagnostics( // (8,37): error CS8204: For type 'AsyncValueTaskMethodBuilder' to be used as an AsyncMethodBuilder for type 'G<T>.ValueTask', its Task property should return type 'G<T>.ValueTask' instead of type 'G<int>.ValueTask'. // public async ValueTask Method() { await Task.Delay(5); return; } Diagnostic(ErrorCode.ERR_BadAsyncMethodBuilderTaskProperty, "{ await Task.Delay(5); return; }").WithArguments("AsyncValueTaskMethodBuilder", "G<T>.ValueTask", "G<int>.ValueTask").WithLocation(8, 37) ); } [Fact, WorkItem(16493, "https://github.com/dotnet/roslyn/issues/16493")] public void AsyncMethodBuilderReturnsDifferentTypeThanTasklikeType2() { var source = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { static async MyTask M() { await Task.Delay(5); throw null; } } [AsyncMethodBuilder(typeof(MyTaskBuilder))] class MyTask { } class MyTaskBuilder { public static MyTaskBuilder Create() => null; public int Task => 0; public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void SetResult() { } public void SetException(Exception exception) { } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugDll); compilation.VerifyEmitDiagnostics( // (7,29): error CS8204: For type 'MyTaskBuilder' to be used as an AsyncMethodBuilder for type 'MyTask', its Task property should return type 'MyTask' instead of type 'int'. // static async MyTask M() { await Task.Delay(5); throw null; } Diagnostic(ErrorCode.ERR_BadAsyncMethodBuilderTaskProperty, "{ await Task.Delay(5); throw null; }").WithArguments("MyTaskBuilder", "MyTask", "int").WithLocation(7, 29) ); } [Fact, WorkItem(18257, "https://github.com/dotnet/roslyn/issues/18257")] public void PatternTempsAreLongLived() { var source = @"using System; public class Goo {} public class C { public static void Main(string[] args) { var c = new C(); c.M(new Goo()); c.M(new object()); } public async void M(object o) { switch (o) { case Goo _: Console.Write(0); break; default: Console.Write(1); break; } } }"; var expectedOutput = @"01"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); base.CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(18257, "https://github.com/dotnet/roslyn/issues/18257")] public void PatternTempsSpill() { // This test exercises the spilling machinery of async for pattern-matching temps var source = @"using System; using System.Threading.Tasks; public class C { public class Goo { public int Value; } public static void Main(string[] args) { var c = new C(); c.M(new Goo() { Value = 1 }); c.M(new Goo() { Value = 2 }); c.M(new Goo() { Value = 3 }); c.M(new object()); } public void M(object o) { MAsync(o).Wait(); } public async Task MAsync(object o) { switch (o) { case Goo goo when await Copy(goo.Value) == 1: Console.Write($""{goo.Value}=1 ""); break; case Goo goo when await Copy(goo.Value) == 2: Console.Write($""{goo.Value}=2 ""); break; case Goo goo: Console.Write($""{goo.Value} ""); break; default: Console.Write(""X ""); break; } } public async Task<int> Copy(int i) { await Task.Delay(1); return i; } }"; var expectedOutput = @"1=1 2=2 3 X"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); base.CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(19831, "https://github.com/dotnet/roslyn/issues/19831")] public void CaptureAssignedInOuterFinally() { var source = @" using System; using System.Threading.Tasks; public class Program { static void Main(string[] args) { Test().Wait(); System.Console.WriteLine(""success""); } public static async Task Test() { // declaring variable before try/finally and nulling it in finally cause NRE in try's body var obj = new Object(); try { for(int i = 0; i < 3; i++) { // NRE on second iteration obj.ToString(); await Task.Yield(); } } finally { obj = null; } } } "; var expectedOutput = @"success"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); base.CompileAndVerify(compilation, expectedOutput: expectedOutput); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); base.CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] public void CaptureStructReceiver() { var source = @" using System; using System.Threading.Tasks; public class Program { static void Main(string[] args) { System.Console.WriteLine(Test1().Result); } static int x = 123; async static Task<string> Test1() { // cannot capture 'x' by value, since write in M1 is observable return x.ToString(await M1()); } async static Task<string> M1() { x = 42; await Task.Yield(); return """"; } } "; var expectedOutput = @"42"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); base.CompileAndVerify(compilation, expectedOutput: expectedOutput); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); base.CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(13759, "https://github.com/dotnet/roslyn/issues/13759")] public void Unnecessary_Lifted_01() { var source = @" using System.IO; using System.Threading.Tasks; namespace Test { class Program { public static void Main() { } public static async Task M(Stream source, Stream destination) { byte[] buffer = new byte[0x1000]; int bytesRead; // this variable should not be lifted while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length)) != 0) { await destination.WriteAsync(buffer, 0, bytesRead); } } } } "; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp). VerifyIL("Test.Program.<M>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 315 (0x13b) .maxstack 4 .locals init (int V_0, int V_1, //bytesRead System.Runtime.CompilerServices.TaskAwaiter V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.Program.<M>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0068 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: beq IL_00d4 IL_0011: ldarg.0 IL_0012: ldc.i4 0x1000 IL_0017: newarr ""byte"" IL_001c: stfld ""byte[] Test.Program.<M>d__1.<buffer>5__2"" IL_0021: br.s IL_008b IL_0023: ldarg.0 IL_0024: ldfld ""System.IO.Stream Test.Program.<M>d__1.destination"" IL_0029: ldarg.0 IL_002a: ldfld ""byte[] Test.Program.<M>d__1.<buffer>5__2"" IL_002f: ldc.i4.0 IL_0030: ldloc.1 IL_0031: callvirt ""System.Threading.Tasks.Task System.IO.Stream.WriteAsync(byte[], int, int)"" IL_0036: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()"" IL_003b: stloc.2 IL_003c: ldloca.s V_2 IL_003e: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get"" IL_0043: brtrue.s IL_0084 IL_0045: ldarg.0 IL_0046: ldc.i4.0 IL_0047: dup IL_0048: stloc.0 IL_0049: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_004e: ldarg.0 IL_004f: ldloc.2 IL_0050: stfld ""System.Runtime.CompilerServices.TaskAwaiter Test.Program.<M>d__1.<>u__1"" IL_0055: ldarg.0 IL_0056: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.Program.<M>d__1.<>t__builder"" IL_005b: ldloca.s V_2 IL_005d: ldarg.0 IL_005e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, Test.Program.<M>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter, ref Test.Program.<M>d__1)"" IL_0063: leave IL_013a IL_0068: ldarg.0 IL_0069: ldfld ""System.Runtime.CompilerServices.TaskAwaiter Test.Program.<M>d__1.<>u__1"" IL_006e: stloc.2 IL_006f: ldarg.0 IL_0070: ldflda ""System.Runtime.CompilerServices.TaskAwaiter Test.Program.<M>d__1.<>u__1"" IL_0075: initobj ""System.Runtime.CompilerServices.TaskAwaiter"" IL_007b: ldarg.0 IL_007c: ldc.i4.m1 IL_007d: dup IL_007e: stloc.0 IL_007f: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_0084: ldloca.s V_2 IL_0086: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()"" IL_008b: ldarg.0 IL_008c: ldfld ""System.IO.Stream Test.Program.<M>d__1.source"" IL_0091: ldarg.0 IL_0092: ldfld ""byte[] Test.Program.<M>d__1.<buffer>5__2"" IL_0097: ldc.i4.0 IL_0098: ldarg.0 IL_0099: ldfld ""byte[] Test.Program.<M>d__1.<buffer>5__2"" IL_009e: ldlen IL_009f: conv.i4 IL_00a0: callvirt ""System.Threading.Tasks.Task<int> System.IO.Stream.ReadAsync(byte[], int, int)"" IL_00a5: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_00aa: stloc.3 IL_00ab: ldloca.s V_3 IL_00ad: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_00b2: brtrue.s IL_00f0 IL_00b4: ldarg.0 IL_00b5: ldc.i4.1 IL_00b6: dup IL_00b7: stloc.0 IL_00b8: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_00bd: ldarg.0 IL_00be: ldloc.3 IL_00bf: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.Program.<M>d__1.<>u__2"" IL_00c4: ldarg.0 IL_00c5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.Program.<M>d__1.<>t__builder"" IL_00ca: ldloca.s V_3 IL_00cc: ldarg.0 IL_00cd: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.Program.<M>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.Program.<M>d__1)"" IL_00d2: leave.s IL_013a IL_00d4: ldarg.0 IL_00d5: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.Program.<M>d__1.<>u__2"" IL_00da: stloc.3 IL_00db: ldarg.0 IL_00dc: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.Program.<M>d__1.<>u__2"" IL_00e1: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00e7: ldarg.0 IL_00e8: ldc.i4.m1 IL_00e9: dup IL_00ea: stloc.0 IL_00eb: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_00f0: ldloca.s V_3 IL_00f2: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00f7: dup IL_00f8: stloc.1 IL_00f9: brtrue IL_0023 IL_00fe: leave.s IL_0120 } catch System.Exception { IL_0100: stloc.s V_4 IL_0102: ldarg.0 IL_0103: ldc.i4.s -2 IL_0105: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_010a: ldarg.0 IL_010b: ldnull IL_010c: stfld ""byte[] Test.Program.<M>d__1.<buffer>5__2"" IL_0111: ldarg.0 IL_0112: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.Program.<M>d__1.<>t__builder"" IL_0117: ldloc.s V_4 IL_0119: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_011e: leave.s IL_013a } IL_0120: ldarg.0 IL_0121: ldc.i4.s -2 IL_0123: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_0128: ldarg.0 IL_0129: ldnull IL_012a: stfld ""byte[] Test.Program.<M>d__1.<buffer>5__2"" IL_012f: ldarg.0 IL_0130: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.Program.<M>d__1.<>t__builder"" IL_0135: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_013a: ret }"); } [Fact, WorkItem(13759, "https://github.com/dotnet/roslyn/issues/13759")] public void Unnecessary_Lifted_02() { var source = @" using System.IO; using System.Threading.Tasks; namespace Test { class Program { public static void Main() { } public static async Task M(Stream source, Stream destination) { bool someCondition = true; bool notLiftedVariable; while (someCondition && (notLiftedVariable = await M1())) { M2(notLiftedVariable); } } private static async Task<bool> M1() { await System.Threading.Tasks.Task.Delay(1); return true; } private static void M2(bool b) { } } } "; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp). VerifyIL("Test.Program.<M>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 175 (0xaf) .maxstack 3 .locals init (int V_0, bool V_1, //notLiftedVariable bool V_2, System.Runtime.CompilerServices.TaskAwaiter<bool> V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.Program.<M>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0057 IL_000a: ldarg.0 IL_000b: ldc.i4.1 IL_000c: stfld ""bool Test.Program.<M>d__1.<someCondition>5__2"" IL_0011: br.s IL_0019 IL_0013: ldloc.1 IL_0014: call ""void Test.Program.M2(bool)"" IL_0019: ldarg.0 IL_001a: ldfld ""bool Test.Program.<M>d__1.<someCondition>5__2"" IL_001f: stloc.2 IL_0020: ldloc.2 IL_0021: brfalse.s IL_007d IL_0023: call ""System.Threading.Tasks.Task<bool> Test.Program.M1()"" IL_0028: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<bool> System.Threading.Tasks.Task<bool>.GetAwaiter()"" IL_002d: stloc.3 IL_002e: ldloca.s V_3 IL_0030: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.IsCompleted.get"" IL_0035: brtrue.s IL_0073 IL_0037: ldarg.0 IL_0038: ldc.i4.0 IL_0039: dup IL_003a: stloc.0 IL_003b: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_0040: ldarg.0 IL_0041: ldloc.3 IL_0042: stfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> Test.Program.<M>d__1.<>u__1"" IL_0047: ldarg.0 IL_0048: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.Program.<M>d__1.<>t__builder"" IL_004d: ldloca.s V_3 IL_004f: ldarg.0 IL_0050: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<bool>, Test.Program.<M>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<bool>, ref Test.Program.<M>d__1)"" IL_0055: leave.s IL_00ae IL_0057: ldarg.0 IL_0058: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> Test.Program.<M>d__1.<>u__1"" IL_005d: stloc.3 IL_005e: ldarg.0 IL_005f: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<bool> Test.Program.<M>d__1.<>u__1"" IL_0064: initobj ""System.Runtime.CompilerServices.TaskAwaiter<bool>"" IL_006a: ldarg.0 IL_006b: ldc.i4.m1 IL_006c: dup IL_006d: stloc.0 IL_006e: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_0073: ldloca.s V_3 IL_0075: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.GetResult()"" IL_007a: dup IL_007b: stloc.1 IL_007c: stloc.2 IL_007d: ldloc.2 IL_007e: brtrue.s IL_0013 IL_0080: leave.s IL_009b } catch System.Exception { IL_0082: stloc.s V_4 IL_0084: ldarg.0 IL_0085: ldc.i4.s -2 IL_0087: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_008c: ldarg.0 IL_008d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.Program.<M>d__1.<>t__builder"" IL_0092: ldloc.s V_4 IL_0094: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0099: leave.s IL_00ae } IL_009b: ldarg.0 IL_009c: ldc.i4.s -2 IL_009e: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_00a3: ldarg.0 IL_00a4: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.Program.<M>d__1.<>t__builder"" IL_00a9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00ae: ret }"); } [Fact, WorkItem(25991, "https://github.com/dotnet/roslyn/issues/25991")] public void CompilerCrash01() { var source = @"namespace Issue25991 { using System; using System.Threading.Tasks; public class CrashClass { public static void Main() { Console.WriteLine(""Passed""); } public async Task CompletedTask() { } public async Task OnCrash() { var switchObject = new object(); switch (switchObject) { case InvalidCastException _: switch (switchObject) { case NullReferenceException exception: await CompletedTask(); var myexception = exception; break; } break; case InvalidOperationException _: switch (switchObject) { case NullReferenceException exception: await CompletedTask(); var myexception = exception; break; } break; } } } } "; var expected = @"Passed"; CompileAndVerify(source, expectedOutput: expected); } [Fact, WorkItem(25991, "https://github.com/dotnet/roslyn/issues/25991")] public void CompilerCrash02() { var source = @"namespace Issue25991 { using System; using System.Threading.Tasks; public class CrashClass { public static void Main() { Console.WriteLine(""Passed""); } public async Task CompletedTask() { } public async Task OnCrash() { var switchObject = new object(); switch (switchObject) { case InvalidCastException x1: switch (switchObject) { case NullReferenceException exception: await CompletedTask(); var myexception1 = x1; var myexception = exception; break; } break; case InvalidOperationException x1: switch (switchObject) { case NullReferenceException exception: await CompletedTask(); var myexception1 = x1; var myexception = exception; var x2 = switchObject; break; } break; } } } } "; var expected = @"Passed"; CompileAndVerify(source, expectedOutput: expected); } [Fact, WorkItem(19905, "https://github.com/dotnet/roslyn/issues/19905")] public void FinallyEnteredFromExceptionalControlFlow() { var source = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task Run() { try { var tmp = await (new { task = Task.Run<string>(async () => { await Task.Delay(1); return """"; }) }).task; throw new Exception(tmp); } finally { Console.Write(0); } } } class Driver { static void Main() { var t = new TestCase(); try { t.Run().Wait(); } catch (Exception) { Console.Write(1); } } }"; var expectedOutput = @"01"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); base.CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(38543, "https://github.com/dotnet/roslyn/issues/38543")] public void AsyncLambdaWithAwaitedTasksInTernary() { var source = @" using System; using System.Threading.Tasks; class Program { static Task M(bool b) => M2(async () => b ? await Task.Delay(1) : await Task.Delay(2)); static T M2<T>(Func<T> f) => f(); }"; // The diagnostic message isn't great, but it is correct that we report an error var c = CreateCompilation(source, options: TestOptions.DebugDll); c.VerifyDiagnostics( // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // b ? await Task.Delay(1) : await Task.Delay(2)); Diagnostic(ErrorCode.ERR_IllegalStatement, "b ? await Task.Delay(1) : await Task.Delay(2)").WithLocation(8, 9) ); } [Fact] [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] public void GetAwaiterBoxingConversion_01() { var source = @"using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; interface IAwaitable { } struct StructAwaitable : IAwaitable { } static class Extensions { public static TaskAwaiter GetAwaiter(this IAwaitable x) { if (x == null) throw new ArgumentNullException(nameof(x)); Console.Write(x); return Task.CompletedTask.GetAwaiter(); } } class Program { static async Task Main() { await new StructAwaitable(); } }"; var comp = CSharpTestBase.CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "StructAwaitable"); } [Fact] [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] public void GetAwaiterBoxingConversion_02() { var source = @"using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; struct StructAwaitable { } static class Extensions { public static TaskAwaiter GetAwaiter(this object x) { if (x == null) throw new ArgumentNullException(nameof(x)); Console.Write(x); return Task.CompletedTask.GetAwaiter(); } } class Program { static async Task Main() { StructAwaitable? s = new StructAwaitable(); await s; } }"; var comp = CSharpTestBase.CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "StructAwaitable"); } [Fact, WorkItem(40251, "https://github.com/dotnet/roslyn/issues/40251")] public void AssignRefAfterAwait() { const string source = @" using System.Threading.Tasks; using System; class IntCode { public static async Task Main() { await Step(0); } public static async Task CompletedTask() { } public static async Task Step(int i) { Console.Write(field); await CompletedTask(); ReadMemory() = i switch { _ => GetValue() }; Console.Write(field); } public static long GetValue() { Console.Write(2); return 3L; } private static long field; private static ref long ReadMemory() { Console.Write(1); return ref field; } } "; var diags = new[] { // (12,30): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // public static async Task CompletedTask() Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "CompletedTask").WithLocation(12, 30) }; CompileAndVerify(source, options: TestOptions.DebugExe, verify: Verification.Skipped, expectedOutput: "0123").VerifyDiagnostics(diags); CompileAndVerify(source, options: TestOptions.ReleaseExe, verify: Verification.Skipped, expectedOutput: "0123").VerifyDiagnostics(diags); } [Fact, WorkItem(40251, "https://github.com/dotnet/roslyn/issues/40251")] public void AssignRefWithAwait() { const string source = @" using System.Threading.Tasks; class IntCode { public async Task Step(Task<int> t) { ReadMemory() = await t; ReadMemory() += await t; } private ref long ReadMemory() => throw null; } "; var expected = new[] { // (8,9): error CS8178: 'await' cannot be used in an expression containing a call to 'IntCode.ReadMemory()' because it returns by reference // ReadMemory() = await t; Diagnostic(ErrorCode.ERR_RefReturningCallAndAwait, "ReadMemory()").WithArguments("IntCode.ReadMemory()").WithLocation(8, 9), // (9,9): error CS8178: 'await' cannot be used in an expression containing a call to 'IntCode.ReadMemory()' because it returns by reference // ReadMemory() += await t; Diagnostic(ErrorCode.ERR_RefReturningCallAndAwait, "ReadMemory()").WithArguments("IntCode.ReadMemory()").WithLocation(9, 9) }; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyEmitDiagnostics(expected); comp = CreateCompilation(source, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics(expected); } [Fact] [WorkItem(30521, "https://github.com/dotnet/roslyn/issues/30521")] public void ComplexSwitchExpressionInvolvingNullCoalescingAndAwait() { var source = @"using System; using System.Threading.Tasks; public class C { public Task<int> Get() => Task.FromResult(1); public async Task M(int? val) { switch (val ?? await Get()) { case 1: default: throw new NotImplementedException(string.Empty); } } } "; var comp = CSharpTestBase.CreateCompilation(source, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("C.<M>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", source: source, expectedIL: @" { // Code size 176 (0xb0) .maxstack 3 .locals init (int V_0, C V_1, int? V_2, int V_3, System.Runtime.CompilerServices.TaskAwaiter<int> V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<M>d__1.<>1__state"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldfld ""C C.<M>d__1.<>4__this"" IL_000d: stloc.1 .try { IL_000e: ldloc.0 IL_000f: brfalse.s IL_0062 IL_0011: ldarg.0 IL_0012: ldfld ""int? C.<M>d__1.val"" IL_0017: stloc.2 IL_0018: ldloca.s V_2 IL_001a: call ""bool int?.HasValue.get"" IL_001f: brfalse.s IL_002b IL_0021: ldloca.s V_2 IL_0023: call ""int int?.GetValueOrDefault()"" IL_0028: stloc.3 IL_0029: br.s IL_0087 IL_002b: ldloc.1 IL_002c: call ""System.Threading.Tasks.Task<int> C.Get()"" IL_0031: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0036: stloc.s V_4 IL_0038: ldloca.s V_4 IL_003a: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_003f: brtrue.s IL_007f IL_0041: ldarg.0 IL_0042: ldc.i4.0 IL_0043: dup IL_0044: stloc.0 IL_0045: stfld ""int C.<M>d__1.<>1__state"" IL_004a: ldarg.0 IL_004b: ldloc.s V_4 IL_004d: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<M>d__1.<>u__1"" IL_0052: ldarg.0 IL_0053: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<M>d__1.<>t__builder"" IL_0058: ldloca.s V_4 IL_005a: ldarg.0 IL_005b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<M>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<M>d__1)"" IL_0060: leave.s IL_00af IL_0062: ldarg.0 IL_0063: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<M>d__1.<>u__1"" IL_0068: stloc.s V_4 IL_006a: ldarg.0 IL_006b: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<M>d__1.<>u__1"" IL_0070: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0076: ldarg.0 IL_0077: ldc.i4.m1 IL_0078: dup IL_0079: stloc.0 IL_007a: stfld ""int C.<M>d__1.<>1__state"" IL_007f: ldloca.s V_4 IL_0081: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0086: stloc.3 IL_0087: ldloc.3 IL_0088: ldc.i4.1 IL_0089: pop IL_008a: pop IL_008b: ldsfld ""string string.Empty"" IL_0090: newobj ""System.NotImplementedException..ctor(string)"" IL_0095: throw } catch System.Exception { IL_0096: stloc.s V_5 IL_0098: ldarg.0 IL_0099: ldc.i4.s -2 IL_009b: stfld ""int C.<M>d__1.<>1__state"" IL_00a0: ldarg.0 IL_00a1: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<M>d__1.<>t__builder"" IL_00a6: ldloc.s V_5 IL_00a8: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00ad: leave.s IL_00af } IL_00af: ret } "); } [Fact, WorkItem(46843, "https://github.com/dotnet/roslyn/issues/46843")] public void LockInAsyncMethodWithAwaitInFinally() { var source = @" using System.Threading.Tasks; public class C { public async Task M(object o) { lock(o) { } try { } finally { await Task.Yield(); } } } "; var comp = CSharpTestBase.CreateCompilation(source); comp.VerifyEmitDiagnostics(); } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class CodeGenAsyncTests : EmitMetadataTestBase { private static CSharpCompilation CreateCompilation(string source, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions options = null) { options = options ?? TestOptions.ReleaseExe; IEnumerable<MetadataReference> asyncRefs = new[] { Net451.System, Net451.SystemCore, Net451.MicrosoftCSharp }; references = (references != null) ? references.Concat(asyncRefs) : asyncRefs; return CreateCompilationWithMscorlib45(source, options: options, references: references); } private CompilationVerifier CompileAndVerify(string source, string expectedOutput, IEnumerable<MetadataReference> references = null, CSharpCompilationOptions options = null, Verification verify = Verification.Passes) { var compilation = CreateCompilation(source, references: references, options: options); return base.CompileAndVerify(compilation, expectedOutput: expectedOutput, verify: verify); } [Fact] public void StructVsClass() { var source = @" using System.Threading; using System.Threading.Tasks; class Test { public static async Task F(int a) { await Task.Factory.StartNew(() => { System.Console.WriteLine(a); }); } public static void Main() { F(123).Wait(); } }"; var c = CreateCompilationWithMscorlib45(source); CompilationOptions options; options = TestOptions.ReleaseExe; Assert.False(options.EnableEditAndContinue); CompileAndVerify(c.WithOptions(options), symbolValidator: module => { var stateMachine = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Test").GetMember<NamedTypeSymbol>("<F>d__0"); Assert.Equal(TypeKind.Struct, stateMachine.TypeKind); }, expectedOutput: "123"); options = TestOptions.ReleaseDebugExe; Assert.False(options.EnableEditAndContinue); CompileAndVerify(c.WithOptions(options), symbolValidator: module => { var stateMachine = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Test").GetMember<NamedTypeSymbol>("<F>d__0"); Assert.Equal(TypeKind.Struct, stateMachine.TypeKind); }, expectedOutput: "123"); options = TestOptions.DebugExe; Assert.True(options.EnableEditAndContinue); CompileAndVerify(c.WithOptions(options), symbolValidator: module => { var stateMachine = module.GlobalNamespace.GetMember<NamedTypeSymbol>("Test").GetMember<NamedTypeSymbol>("<F>d__0"); Assert.Equal(TypeKind.Class, stateMachine.TypeKind); }, expectedOutput: "123"); } [Fact] public void VoidReturningAsync() { var source = @" using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; class Test { static int i = 0; public static async void F(AutoResetEvent handle) { try { await Task.Factory.StartNew(() => { Interlocked.Increment(ref Test.i); }); } finally { handle.Set(); } } public static void Main() { var handle = new AutoResetEvent(false); F(handle); handle.WaitOne(1000 * 60); Console.WriteLine(i); } }"; var expected = @" 1 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void TaskReturningAsync() { var source = @" using System; using System.Diagnostics; using System.Threading.Tasks; class Test { static int i = 0; public static async Task F() { await Task.Factory.StartNew(() => { Test.i = 42; }); } public static void Main() { Task t = F(); t.Wait(1000 * 60); Console.WriteLine(Test.i); } }"; var expected = @" 42 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void GenericTaskReturningAsync() { var source = @" using System; using System.Diagnostics; using System.Threading.Tasks; class Test { public static async Task<string> F() { return await Task.Factory.StartNew(() => { return ""O brave new world...""; }); } public static void Main() { Task<string> t = F(); t.Wait(1000 * 60); Console.WriteLine(t.Result); } }"; var expected = @" O brave new world... "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void Conformance_Awaiting_Methods_Generic01() { var source = @" using System; using System.Runtime.CompilerServices; using System.Threading; //Implementation of you own async pattern public class MyTask<T> { public MyTaskAwaiter<T> GetAwaiter() { return new MyTaskAwaiter<T>(); } public async void Run<U>(U u) where U : MyTask<int>, new() { try { int tests = 0; tests++; var rez = await u; if (rez == 0) Driver.Count++; Driver.Result = Driver.Count - tests; } finally { //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } public class MyTaskAwaiter<T> : INotifyCompletion { public void OnCompleted(Action continuationAction) { } public T GetResult() { return default(T); } public bool IsCompleted { get { return true; } } } //------------------------------------- class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { new MyTask<int>().Run<MyTask<int>>(new MyTask<int>()); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Conformance_Awaiting_Methods_Method01() { var source = @" using System.Threading; using System.Threading.Tasks; using System; public interface IExplicit { Task Method(int x = 4); } class C1 : IExplicit { Task IExplicit.Method(int x) { //This will fail until Run and RunEx are merged back together return Task.Run(async () => { await Task.Delay(1); Driver.Count++; }); } } class TestCase { public async void Run() { try { int tests = 0; tests++; C1 c = new C1(); IExplicit e = (IExplicit)c; await e.Method(); Driver.Result = Driver.Count - tests; } finally { //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Conformance_Awaiting_Methods_Parameter003() { var source = @" using System; using System.Threading.Tasks; using System.Collections.Generic; using System.Threading; class TestCase { public static int Count = 0; public static T Goo<T>(T t) { return t; } public async static Task<T> Bar<T>(T t) { await Task.Delay(1); return t; } public static async void Run() { try { int x1 = Goo(await Bar(4)); Task<int> t = Bar(5); int x2 = Goo(await t); if (x1 != 4) Count++; if (x2 != 5) Count++; } finally { Driver.CompletedSignal.Set(); } } } class Driver { public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { TestCase.Run(); CompletedSignal.WaitOne(); // 0 - success Console.WriteLine(TestCase.Count); } }"; CompileAndVerify(source, expectedOutput: "0"); } [Fact] public void Conformance_Awaiting_Methods_Method05() { var source = @" using System.Threading; using System.Threading.Tasks; using System; class C { public int Status; public C(){} } interface IImplicit { T Method<T>(params decimal[] d) where T : Task<C>; } class Impl : IImplicit { public T Method<T>(params decimal[] d) where T : Task<C> { //this will fail until Run and RunEx<C> are merged return (T) Task.Run(async() => { await Task.Delay(1); Driver.Count++; return new C() { Status = 1 }; }); } } class TestCase { public async void Run() { try { int tests = 0; Impl i = new Impl(); tests++; await i.Method<Task<C>>(3m, 4m); Driver.Result = Driver.Count - tests; } finally { //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Conformance_Awaiting_Methods_Accessible010() { var source = @" using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; class TestCase:Test { public static int Count = 0; public async static void Run() { try { int x = await Test.GetValue<int>(1); if (x != 1) Count++; } finally { Driver.CompletedSignal.Set(); } } } class Test { protected async static Task<T> GetValue<T>(T t) { await Task.Delay(1); return t; } } class Driver { public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { TestCase.Run(); CompletedSignal.WaitOne(); // 0 - success Console.WriteLine(TestCase.Count); } }"; CompileAndVerify(source, "0"); } [Fact] public void AwaitInDelegateConstructor() { var source = @" using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; class TestCase { static int test = 0; static int count = 0; public static async Task Run() { try { test++; var f = new Func<int, object>(checked(await Bar())); var x = f(1); if ((string)x != ""1"") count--; } finally { Driver.Result = test - count; Driver.CompleteSignal.Set(); } } static async Task<Converter<int, string>> Bar() { count++; await Task.Delay(1); return delegate(int p1) { return p1.ToString(); }; } } class Driver { static public AutoResetEvent CompleteSignal = new AutoResetEvent(false); public static int Result = -1; public static void Main() { TestCase.Run(); CompleteSignal.WaitOne(); Console.Write(Result); } }"; CompileAndVerify(source, expectedOutput: "0"); } [Fact] public void Generic01() { var source = @" using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; class TestCase { static int test = 0; static int count = 0; public static async Task Run() { try { test++; Qux(async () => { return 1; }); await Task.Delay(50); } finally { Driver.Result = test - count; Driver.CompleteSignal.Set(); } } static async void Qux<T>(Func<Task<T>> x) { var y = await x(); if ((int)(object)y == 1) count++; } } class Driver { static public AutoResetEvent CompleteSignal = new AutoResetEvent(false); public static int Result = -1; public static void Main() { TestCase.Run(); CompleteSignal.WaitOne(); Console.WriteLine(Result); } }"; var expected = @" 0 "; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void Struct02() { var source = @" using System; using System.Threading; using System.Threading.Tasks; struct TestCase { private Task<int> t; public async void Run() { int tests = 0; try { tests++; t = Task.Run(async () => { await Task.Delay(1); return 1; }); var x = await t; if (x == 1) Driver.Count++; tests++; t = Task.Run(async () => { await Task.Delay(1); return 1; }); var x2 = await this.t; if (x2 == 1) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.Write(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Delegate10() { var source = @" using System.Threading; using System.Threading.Tasks; using System; delegate Task MyDel<U>(out U u); class MyClass<T> { public static Task Meth(out T t) { t = default(T); return Task.Run(async () => { await Task.Delay(1); TestCase.Count++; }); } public MyDel<T> myDel; public event MyDel<T> myEvent; public async Task TriggerEvent(T p) { try { await myEvent(out p); } catch { TestCase.Count += 5; } } } struct TestCase { public static int Count = 0; private int tests; public async void Run() { tests = 0; try { tests++; MyClass<string> ms = new MyClass<string>(); ms.myDel = MyClass<string>.Meth; string str = """"; await ms.myDel(out str); tests++; ms.myEvent += MyClass<string>.Meth; await ms.TriggerEvent(str); } finally { Driver.Result = TestCase.Count - this.tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void AwaitSwitch() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { public async void Run() { int test = 0; int result = 0; try { test++; switch (await ((Func<Task<int>>)(async () => { await Task.Delay(1); return 5; }))()) { case 1: case 2: break; case 5: result++; break; default: break; } } finally { Driver.Result = test - result; Driver.CompleteSignal.Set(); } } } class Driver { static public AutoResetEvent CompleteSignal = new AutoResetEvent(false); public static int Result = -1; public static void Main() { TestCase tc = new TestCase(); tc.Run(); CompleteSignal.WaitOne(); Console.WriteLine(Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Return07() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class TestCase { unsafe struct S { public int value; public S* next; } public async void Run() { int test = 0; int result = 0; try { Func<Task<dynamic>> func, func2 = null; test++; S s = new S(); S s1 = new S(); unsafe { S* head = &s; s.next = &s1; func = async () => { (*(head->next)).value = 1; result++; return head->next->value; }; func2 = async () => (*(head->next)); } var x = await func(); if (x != 1) result--; var xx = await func2(); if (xx.value != 1) result--; } finally { Driver.Result = test - result; Driver.CompleteSignal.Set(); } } } class Driver { static public AutoResetEvent CompleteSignal = new AutoResetEvent(false); public static int Result = -1; public static void Main() { TestCase tc = new TestCase(); tc.Run(); CompleteSignal.WaitOne(); Console.WriteLine(Result); } }"; CompileAndVerify(source, expectedOutput: "0", options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails); } [Fact] public void Inference() { var source = @" using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; struct Test { public Task<string> Goo { get { return Task.Run<string>(async () => { await Task.Delay(1); return ""abc""; }); } } } class TestCase<U> { public static async Task<object> GetValue(object x) { await Task.Delay(1); return x; } public static T GetValue1<T>(T t) where T : Task<U> { return t; } public async void Run() { int tests = 0; Test t = new Test(); tests++; var x1 = await TestCase<string>.GetValue(await t.Goo); if (x1 == ""abc"") Driver.Count++; tests++; var x2 = await TestCase<string>.GetValue1(t.Goo); if (x2 == ""abc"") Driver.Count++; Driver.Result = Driver.Count - tests; //When test completes, set the flag. Driver.CompletedSignal.Set(); } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase<int>(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, expectedOutput: "0", options: TestOptions.UnsafeDebugExe, verify: Verification.Passes); } [Fact] public void IsAndAsOperators() { var source = @" using System.Threading; using System.Threading.Tasks; using System; class TestCase { public static int Count = 0; public async void Run() { int tests = 0; var x1 = ((await Goo1()) is object); var x2 = ((await Goo2()) as string); if (x1 == true) tests++; if (x2 == ""string"") tests++; Driver.Result = TestCase.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } public async Task<int> Goo1() { await Task.Delay(1); TestCase.Count++; int i = 0; return i; } public async Task<object> Goo2() { await Task.Delay(1); TestCase.Count++; return ""string""; } } class Driver { public static int Result = -1; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.Write(Driver.Result); } }"; CompileAndVerify(source, expectedOutput: "0", options: TestOptions.UnsafeDebugExe, verify: Verification.Passes); } [Fact] public void Property21() { var source = @" using System.Threading; using System.Threading.Tasks; using System; class Base { public virtual int MyProp { get; private set; } } class TestClass : Base { async Task<int> getBaseMyProp() { await Task.Delay(1); return base.MyProp; } async public void Run() { Driver.Result = await getBaseMyProp(); Driver.CompleteSignal.Set(); } } class Driver { public static AutoResetEvent CompleteSignal = new AutoResetEvent(false); public static void Main() { TestClass tc = new TestClass(); tc.Run(); CompleteSignal.WaitOne(); Console.WriteLine(Result); } public static int Result = -1; }"; CompileAndVerify(source, expectedOutput: "0", options: TestOptions.UnsafeDebugExe, verify: Verification.Passes); } [Fact] public void AnonType32() { var source = @"using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; class TestCase { public async void Run() { int tests = 0; try { tests++; try { var tmp = await (new { task = Task.Run<string>(async () => { await Task.Delay(1); return """"; }) }).task; throw new Exception(tmp); } catch (Exception ex) { if (ex.Message == """") Driver.Count++; } } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0", options: TestOptions.UnsafeDebugExe); } [Fact] public void Init19() { var source = @" using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; class ObjInit { public int async; public Task t; public long l; } class TestCase { private T Throw<T>(T i) { MethodCount++; throw new OverflowException(); } private async Task<T> GetVal<T>(T x) { await Task.Delay(1); Throw(x); return x; } public Task<long> MyProperty { get; set; } public async void Run() { int tests = 0; Task<int> t = Task.Run<int>(async () => { await Task.Delay(1); throw new FieldAccessException(); return 1; }); //object type init tests++; try { MyProperty = Task.Run<long>(async () => { await Task.Delay(1); throw new DataMisalignedException(); return 1; }); var obj = new ObjInit() { async = await t, t = GetVal((Task.Run(async () => { await Task.Delay(1); }))), l = await MyProperty }; await obj.t; } catch (FieldAccessException) { Driver.Count++; } catch { Driver.Count--; } Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } public int MethodCount = 0; } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0", options: TestOptions.UnsafeDebugExe); } [Fact] public void Conformance_OverloadResolution_1Class_Generic_regularMethod05() { var source = @" using System.Threading; using System.Threading.Tasks; using System; struct Test<U, V, W> { //Regular methods public int Goo(Func<Task<U>> f) { return 1; } public int Goo(Func<Task<V>> f) { return 2; } public int Goo(Func<Task<W>> f) { return 3; } } class TestCase { //where there is a conversion between types (int->double) public void Run() { Test<decimal, string, dynamic> test = new Test<decimal, string, dynamic>(); int rez = 0; // Pick double Driver.Tests++; rez = test.Goo(async () => { return 1.0; }); if (rez == 3) Driver.Count++; //pick int Driver.Tests++; rez = test.Goo(async delegate() { return 1; }); if (rez == 1) Driver.Count++; // The best overload is Func<Task<object>> Driver.Tests++; rez = test.Goo(async () => { return """"; }); if (rez == 2) Driver.Count++; Driver.Tests++; rez = test.Goo(async delegate() { return """"; }); if (rez == 2) Driver.Count++; } } class Driver { public static int Count = 0; public static int Tests = 0; static int Main() { var t = new TestCase(); t.Run(); var ret = Driver.Tests - Driver.Count; Console.WriteLine(ret); return ret; } }"; CompileAndVerify(source, "0", options: TestOptions.UnsafeDebugExe); } [Fact] public void Dynamic() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task<dynamic> F1(dynamic d) { return await d; } public static async Task<int> F2(Task<int> d) { return await d; } public static async Task<int> Run() { int a = await F1(Task.Factory.StartNew(() => 21)); int b = await F2(Task.Factory.StartNew(() => 21)); return a + b; } static void Main() { var t = Run(); t.Wait(); Console.WriteLine(t.Result); } }"; CompileAndVerify(source, "42"); } [Fact] [WorkItem(638261, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/638261")] public void Await15() { var source = @" using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; struct DynamicClass { public async Task<dynamic> Goo<T>(T t) { await Task.Delay(1); return t; } public async Task<Task<dynamic>> Bar(int i) { await Task.Delay(1); return Task.Run<dynamic>(async () => { await Task.Delay(1); return i; }); } } class TestCase { public async void Run() { int tests = 0; DynamicClass dc = new DynamicClass(); dynamic d = 123; try { tests++; var x1 = await dc.Goo(""""); if (x1 == """") Driver.Count++; tests++; var x2 = await await dc.Bar(d); if (x2 == 123) Driver.Count++; tests++; var x3 = await await dc.Bar(await dc.Goo(234)); if (x3 == 234) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Await01() { // The legacy compiler allows this; we don't. This kills conformance_await_dynamic_await01. var source = @" using System; using System.Threading; using System.Threading.Tasks; class DynamicMembers { public dynamic Prop { get; set; } } class Driver { static void Main() { DynamicMembers dc2 = new DynamicMembers(); dc2.Prop = (Func<Task<int>>)(async () => { await Task.Delay(1); return 1; }); var rez2 = dc2.Prop(); } }"; CompileAndVerify(source, ""); } [Fact] public void Await40() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class C1 { public async Task<int> Method(int x) { await Task.Delay(1); return x; } } class C2 { public int Status; public C2(int x = 5) { this.Status = x; } public C2(int x, int y) { this.Status = x + y; } public int Bar(int x) { return x; } } class TestCase { public async void Run() { int tests = 0; try { tests++; dynamic c = new C1(); C2 cc = new C2(x: await c.Method(1)); if (cc.Status == 1) Driver.Count++; tests++; dynamic f = (Func<Task<dynamic>>)(async () => { await Task.Delay(1); return 4; }); cc = new C2(await c.Method(2), await f()); if (cc.Status == 6) Driver.Count++; tests++; var x = new C2(2).Bar(await c.Method(1)); if (cc.Status == 6 && x == 1) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Await43() { var source = @" using System.Threading; using System.Threading.Tasks; using System; struct MyClass { public static Task operator *(MyClass c, int x) { return Task.Run(async delegate { await Task.Delay(1); TestCase.Count++; }); } public static Task operator +(MyClass c, long x) { return Task.Run(async () => { await Task.Delay(1); TestCase.Count++; }); } } class TestCase { public static int Count = 0; private int tests; public async void Run() { this.tests = 0; dynamic dy = Task.Run<MyClass>(async () => { await Task.Delay(1); return new MyClass(); }); try { this.tests++; await (await dy * 5); this.tests++; dynamic d = new MyClass(); dynamic dd = Task.Run<long>(async () => { await Task.Delay(1); return 1L; }); await (d + await dd); } catch (Exception ex) { Console.WriteLine(ex); Console.WriteLine(ex.StackTrace); } finally { Driver.Result = TestCase.Count - this.tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Await44() { var source = @" using System.Threading; using System.Threading.Tasks; using System; class MyClass { public static implicit operator Task(MyClass c) { return Task.Run(async delegate { await Task.Delay(1); TestCase.Count++; }); } } class TestCase { public static int Count = 0; private int tests; public async void Run() { this.tests = 0; dynamic mc = new MyClass(); try { tests++; Task t1 = mc; await t1; tests++; dynamic t2 = (Task)mc; await t2; } finally { Driver.Result = TestCase.Count - this.tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } class Driver { public static int Result = -1; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void ThisShouldProbablyCompileToVerifiableCode() { var source = @" using System; class Driver { public static bool Run() { dynamic dynamicThing = false; return true && dynamicThing; } static void Main() { Console.WriteLine(Run()); } }"; CompileAndVerify(source, "False"); } [Fact] public void Async_Conformance_Awaiting_indexer23() { var source = @" using System.Threading; using System.Threading.Tasks; using System; struct MyStruct<T> where T : Task<Func<int>> { T t { get; set; } public T this[T index] { get { return t; } set { t = value; } } } struct TestCase { public static int Count = 0; private int tests; public async void Run() { this.tests = 0; MyStruct<Task<Func<int>>> ms = new MyStruct<Task<Func<int>>>(); try { ms[index: null] = Task.Run<Func<int>>(async () => { await Task.Delay(1); Interlocked.Increment(ref TestCase.Count); return () => (123); }); this.tests++; var x = await ms[index: await Goo(null)]; if (x() == 123) this.tests++; } finally { Driver.Result = TestCase.Count - this.tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } public async Task<Task<Func<int>>> Goo(Task<Func<int>> d) { await Task.Delay(1); Interlocked.Increment(ref TestCase.Count); return d; } } class Driver { public static int Result = -1; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { var t = new TestCase(); t.Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void Conformance_Exceptions_Async_Await_Names() { var source = @" using System; class TestCase { public void Run() { Driver.Tests++; try { throw new ArgumentException(); } catch (Exception await) { if (await is ArgumentException) Driver.Count++; } Driver.Tests++; try { throw new ArgumentException(); } catch (Exception async) { if (async is ArgumentException) Driver.Count++; } } } class Driver { public static int Tests; public static int Count; static void Main() { TestCase t = new TestCase(); t.Run(); Console.WriteLine(Tests - Count); } }"; CompileAndVerify(source, "0"); } [Fact] public void MyTask_08() { var source = @" using System; using System.Threading; using System.Threading.Tasks; //Implementation of you own async pattern public class MyTask { public async void Run() { int tests = 0; try { tests++; var myTask = new MyTask(); var x = await myTask; if (x == 123) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } public class MyTaskAwaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action continuationAction) { } public int GetResult() { return 123; } public bool IsCompleted { get { return true; } } } public static class Extension { public static MyTaskAwaiter GetAwaiter(this MyTask my) { return new MyTaskAwaiter(); } } //------------------------------------- class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { new MyTask().Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] public void MyTask_16() { var source = @" using System; using System.Threading; using System.Threading.Tasks; //Implementation of you own async pattern public class MyTask { public MyTaskAwaiter GetAwaiter() { return new MyTaskAwaiter(); } public async void Run() { int tests = 0; try { tests++; var myTask = new MyTask(); var x = await myTask; if (x == 123) Driver.Count++; } finally { Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } } public class MyTaskBaseAwaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action continuationAction) { } public int GetResult() { return 123; } public bool IsCompleted { get { return true; } } } public class MyTaskAwaiter : MyTaskBaseAwaiter { } //------------------------------------- class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); static void Main() { new MyTask().Run(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; CompileAndVerify(source, "0"); } [Fact] [WorkItem(625282, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/625282")] public void Generic05() { var source = @" using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; class TestCase { public T Goo<T>(T x, T y, int z) { return x; } public T GetVal<T>(T t) { return t; } public IEnumerable<T> Run<T>(T t) { dynamic d = GetVal(t); yield return Goo(t, d, 3); } } class Driver { static void Main() { var t = new TestCase(); t.Run(6); } }"; CompileAndVerifyWithMscorlib40(source, new[] { CSharpRef, SystemCoreRef }); } [Fact] public void AsyncStateMachineIL_Struct_TaskT() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task<int> F() { return await Task.Factory.StartNew(() => 42); } public static void Main() { var t = F(); t.Wait(); Console.WriteLine(t.Result); } }"; var expected = @" 42 "; var c = CompileAndVerify(source, expectedOutput: expected); c.VerifyIL("Test.F", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (Test.<F>d__0 V_0) IL_0000: ldloca.s V_0 IL_0002: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Create()"" IL_0007: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_000c: ldloca.s V_0 IL_000e: ldc.i4.m1 IL_000f: stfld ""int Test.<F>d__0.<>1__state"" IL_0014: ldloca.s V_0 IL_0016: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_001b: ldloca.s V_0 IL_001d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Start<Test.<F>d__0>(ref Test.<F>d__0)"" IL_0022: ldloca.s V_0 IL_0024: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_0029: call ""System.Threading.Tasks.Task<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Task.get"" IL_002e: ret } "); c.VerifyIL("Test.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 180 (0xb4) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0062 IL_000a: call ""System.Threading.Tasks.TaskFactory System.Threading.Tasks.Task.Factory.get"" IL_000f: ldsfld ""System.Func<int> Test.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Test.<>c Test.<>c.<>9"" IL_001d: ldftn ""int Test.<>c.<F>b__0_0()"" IL_0023: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int> Test.<>c.<>9__0_0"" IL_002e: callvirt ""System.Threading.Tasks.Task<int> System.Threading.Tasks.TaskFactory.StartNew<int>(System.Func<int>)"" IL_0033: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0038: stloc.2 IL_0039: ldloca.s V_2 IL_003b: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0040: brtrue.s IL_007e IL_0042: ldarg.0 IL_0043: ldc.i4.0 IL_0044: dup IL_0045: stloc.0 IL_0046: stfld ""int Test.<F>d__0.<>1__state"" IL_004b: ldarg.0 IL_004c: ldloc.2 IL_004d: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0052: ldarg.0 IL_0053: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_0058: ldloca.s V_2 IL_005a: ldarg.0 IL_005b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<F>d__0)"" IL_0060: leave.s IL_00b3 IL_0062: ldarg.0 IL_0063: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0068: stloc.2 IL_0069: ldarg.0 IL_006a: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_006f: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0075: ldarg.0 IL_0076: ldc.i4.m1 IL_0077: dup IL_0078: stloc.0 IL_0079: stfld ""int Test.<F>d__0.<>1__state"" IL_007e: ldloca.s V_2 IL_0080: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0085: stloc.1 IL_0086: leave.s IL_009f } catch System.Exception { IL_0088: stloc.3 IL_0089: ldarg.0 IL_008a: ldc.i4.s -2 IL_008c: stfld ""int Test.<F>d__0.<>1__state"" IL_0091: ldarg.0 IL_0092: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_0097: ldloc.3 IL_0098: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_009d: leave.s IL_00b3 } IL_009f: ldarg.0 IL_00a0: ldc.i4.s -2 IL_00a2: stfld ""int Test.<F>d__0.<>1__state"" IL_00a7: ldarg.0 IL_00a8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_00ad: ldloc.1 IL_00ae: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00b3: ret } "); c.VerifyIL("Test.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_0006: ldarg.1 IL_0007: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine)"" IL_000c: ret } "); } [Fact] public void AsyncStateMachineIL_Struct_TaskT_A() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task<int> F() { return await Task.Factory.StartNew(() => 42); } public static void Main() { var t = F(); t.Wait(); Console.WriteLine(t.Result); } }"; var expected = @" 42 "; var c = CompileAndVerify(source, options: TestOptions.ReleaseDebugExe, expectedOutput: expected); c.VerifyIL("Test.F", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (Test.<F>d__0 V_0) IL_0000: ldloca.s V_0 IL_0002: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Create()"" IL_0007: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_000c: ldloca.s V_0 IL_000e: ldc.i4.m1 IL_000f: stfld ""int Test.<F>d__0.<>1__state"" IL_0014: ldloca.s V_0 IL_0016: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_001b: ldloca.s V_0 IL_001d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Start<Test.<F>d__0>(ref Test.<F>d__0)"" IL_0022: ldloca.s V_0 IL_0024: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_0029: call ""System.Threading.Tasks.Task<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Task.get"" IL_002e: ret } "); c.VerifyIL("Test.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 184 (0xb8) .maxstack 3 .locals init (int V_0, int V_1, int V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0062 IL_000a: call ""System.Threading.Tasks.TaskFactory System.Threading.Tasks.Task.Factory.get"" IL_000f: ldsfld ""System.Func<int> Test.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Test.<>c Test.<>c.<>9"" IL_001d: ldftn ""int Test.<>c.<F>b__0_0()"" IL_0023: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int> Test.<>c.<>9__0_0"" IL_002e: callvirt ""System.Threading.Tasks.Task<int> System.Threading.Tasks.TaskFactory.StartNew<int>(System.Func<int>)"" IL_0033: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0038: stloc.3 IL_0039: ldloca.s V_3 IL_003b: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0040: brtrue.s IL_007e IL_0042: ldarg.0 IL_0043: ldc.i4.0 IL_0044: dup IL_0045: stloc.0 IL_0046: stfld ""int Test.<F>d__0.<>1__state"" IL_004b: ldarg.0 IL_004c: ldloc.3 IL_004d: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0052: ldarg.0 IL_0053: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_0058: ldloca.s V_3 IL_005a: ldarg.0 IL_005b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<F>d__0)"" IL_0060: leave.s IL_00b7 IL_0062: ldarg.0 IL_0063: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0068: stloc.3 IL_0069: ldarg.0 IL_006a: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_006f: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0075: ldarg.0 IL_0076: ldc.i4.m1 IL_0077: dup IL_0078: stloc.0 IL_0079: stfld ""int Test.<F>d__0.<>1__state"" IL_007e: ldloca.s V_3 IL_0080: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0085: stloc.2 IL_0086: ldloc.2 IL_0087: stloc.1 IL_0088: leave.s IL_00a3 } catch System.Exception { IL_008a: stloc.s V_4 IL_008c: ldarg.0 IL_008d: ldc.i4.s -2 IL_008f: stfld ""int Test.<F>d__0.<>1__state"" IL_0094: ldarg.0 IL_0095: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_009a: ldloc.s V_4 IL_009c: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00a1: leave.s IL_00b7 } IL_00a3: ldarg.0 IL_00a4: ldc.i4.s -2 IL_00a6: stfld ""int Test.<F>d__0.<>1__state"" IL_00ab: ldarg.0 IL_00ac: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_00b1: ldloc.1 IL_00b2: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00b7: ret } "); c.VerifyIL("Test.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_0006: ldarg.1 IL_0007: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine)"" IL_000c: ret } "); } [Fact] public void AsyncStateMachineIL_Class_TaskT() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task<int> F() { return await Task.Factory.StartNew(() => 42); } public static void Main() { var t = F(); t.Wait(); Console.WriteLine(t.Result); } }"; var expected = @" 42 "; var c = CompileAndVerify(source, expectedOutput: expected, options: TestOptions.DebugExe); c.VerifyIL("Test.F", @" { // Code size 49 (0x31) .maxstack 2 .locals init (Test.<F>d__0 V_0) IL_0000: newobj ""Test.<F>d__0..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Create()"" IL_000c: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_0011: ldloc.0 IL_0012: ldc.i4.m1 IL_0013: stfld ""int Test.<F>d__0.<>1__state"" IL_0018: ldloc.0 IL_0019: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_001e: ldloca.s V_0 IL_0020: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Start<Test.<F>d__0>(ref Test.<F>d__0)"" IL_0025: ldloc.0 IL_0026: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_002b: call ""System.Threading.Tasks.Task<int> System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.Task.get"" IL_0030: ret } "); c.VerifyIL("Test.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 205 (0xcd) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, Test.<F>d__0 V_3, System.Exception V_4) ~IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_006b -IL_000e: nop -IL_000f: call ""System.Threading.Tasks.TaskFactory System.Threading.Tasks.Task.Factory.get"" IL_0014: ldsfld ""System.Func<int> Test.<>c.<>9__0_0"" IL_0019: dup IL_001a: brtrue.s IL_0033 IL_001c: pop IL_001d: ldsfld ""Test.<>c Test.<>c.<>9"" IL_0022: ldftn ""int Test.<>c.<F>b__0_0()"" IL_0028: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_002d: dup IL_002e: stsfld ""System.Func<int> Test.<>c.<>9__0_0"" IL_0033: callvirt ""System.Threading.Tasks.Task<int> System.Threading.Tasks.TaskFactory.StartNew<int>(System.Func<int>)"" IL_0038: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_003d: stloc.2 ~IL_003e: ldloca.s V_2 IL_0040: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0045: brtrue.s IL_0087 IL_0047: ldarg.0 IL_0048: ldc.i4.0 IL_0049: dup IL_004a: stloc.0 IL_004b: stfld ""int Test.<F>d__0.<>1__state"" <IL_0050: ldarg.0 IL_0051: ldloc.2 IL_0052: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0057: ldarg.0 IL_0058: stloc.3 IL_0059: ldarg.0 IL_005a: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_005f: ldloca.s V_2 IL_0061: ldloca.s V_3 IL_0063: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<F>d__0)"" IL_0068: nop IL_0069: leave.s IL_00cc >IL_006b: ldarg.0 IL_006c: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0071: stloc.2 IL_0072: ldarg.0 IL_0073: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0078: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_007e: ldarg.0 IL_007f: ldc.i4.m1 IL_0080: dup IL_0081: stloc.0 IL_0082: stfld ""int Test.<F>d__0.<>1__state"" IL_0087: ldarg.0 IL_0088: ldloca.s V_2 IL_008a: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_008f: stfld ""int Test.<F>d__0.<>s__1"" IL_0094: ldarg.0 IL_0095: ldfld ""int Test.<F>d__0.<>s__1"" IL_009a: stloc.1 IL_009b: leave.s IL_00b7 } catch System.Exception { ~IL_009d: stloc.s V_4 IL_009f: ldarg.0 IL_00a0: ldc.i4.s -2 IL_00a2: stfld ""int Test.<F>d__0.<>1__state"" IL_00a7: ldarg.0 IL_00a8: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_00ad: ldloc.s V_4 IL_00af: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00b4: nop IL_00b5: leave.s IL_00cc } -IL_00b7: ldarg.0 IL_00b8: ldc.i4.s -2 IL_00ba: stfld ""int Test.<F>d__0.<>1__state"" ~IL_00bf: ldarg.0 IL_00c0: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__0.<>t__builder"" IL_00c5: ldloc.1 IL_00c6: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00cb: nop IL_00cc: ret }", sequencePoints: "Test+<F>d__0.MoveNext"); c.VerifyIL("Test.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine", @" { // Code size 1 (0x1) .maxstack 0 IL_0000: ret } "); } [Fact] public void IL_Task() { var source = @" using System; using System.Threading.Tasks; class Test { public static async Task F() { await Task.Factory.StartNew(() => 42); Console.WriteLine(42); } public static void Main() { var t = F(); t.Wait(); } }"; var expected = @" 42 "; var c = CompileAndVerify(source, expectedOutput: expected); c.VerifyIL("Test.F", @" { // Code size 47 (0x2f) .maxstack 2 .locals init (Test.<F>d__0 V_0) IL_0000: ldloca.s V_0 IL_0002: call ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Create()"" IL_0007: stfld ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<F>d__0.<>t__builder"" IL_000c: ldloca.s V_0 IL_000e: ldc.i4.m1 IL_000f: stfld ""int Test.<F>d__0.<>1__state"" IL_0014: ldloca.s V_0 IL_0016: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<F>d__0.<>t__builder"" IL_001b: ldloca.s V_0 IL_001d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start<Test.<F>d__0>(ref Test.<F>d__0)"" IL_0022: ldloca.s V_0 IL_0024: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<F>d__0.<>t__builder"" IL_0029: call ""System.Threading.Tasks.Task System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Task.get"" IL_002e: ret } "); c.VerifyIL("Test.<F>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 186 (0xba) .maxstack 3 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter<int> V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<F>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0062 IL_000a: call ""System.Threading.Tasks.TaskFactory System.Threading.Tasks.Task.Factory.get"" IL_000f: ldsfld ""System.Func<int> Test.<>c.<>9__0_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Test.<>c Test.<>c.<>9"" IL_001d: ldftn ""int Test.<>c.<F>b__0_0()"" IL_0023: newobj ""System.Func<int>..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Func<int> Test.<>c.<>9__0_0"" IL_002e: callvirt ""System.Threading.Tasks.Task<int> System.Threading.Tasks.TaskFactory.StartNew<int>(System.Func<int>)"" IL_0033: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0038: stloc.1 IL_0039: ldloca.s V_1 IL_003b: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0040: brtrue.s IL_007e IL_0042: ldarg.0 IL_0043: ldc.i4.0 IL_0044: dup IL_0045: stloc.0 IL_0046: stfld ""int Test.<F>d__0.<>1__state"" IL_004b: ldarg.0 IL_004c: ldloc.1 IL_004d: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0052: ldarg.0 IL_0053: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<F>d__0.<>t__builder"" IL_0058: ldloca.s V_1 IL_005a: ldarg.0 IL_005b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<F>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<F>d__0)"" IL_0060: leave.s IL_00b9 IL_0062: ldarg.0 IL_0063: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_0068: stloc.1 IL_0069: ldarg.0 IL_006a: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__0.<>u__1"" IL_006f: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0075: ldarg.0 IL_0076: ldc.i4.m1 IL_0077: dup IL_0078: stloc.0 IL_0079: stfld ""int Test.<F>d__0.<>1__state"" IL_007e: ldloca.s V_1 IL_0080: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0085: pop IL_0086: ldc.i4.s 42 IL_0088: call ""void System.Console.WriteLine(int)"" IL_008d: leave.s IL_00a6 } catch System.Exception { IL_008f: stloc.2 IL_0090: ldarg.0 IL_0091: ldc.i4.s -2 IL_0093: stfld ""int Test.<F>d__0.<>1__state"" IL_0098: ldarg.0 IL_0099: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<F>d__0.<>t__builder"" IL_009e: ldloc.2 IL_009f: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a4: leave.s IL_00b9 } IL_00a6: ldarg.0 IL_00a7: ldc.i4.s -2 IL_00a9: stfld ""int Test.<F>d__0.<>1__state"" IL_00ae: ldarg.0 IL_00af: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.<F>d__0.<>t__builder"" IL_00b4: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b9: ret } "); } [Fact] public void IL_Void() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class Test { static int i = 0; public static async void F(AutoResetEvent handle) { await Task.Factory.StartNew(() => { Test.i = 42; }); handle.Set(); } public static void Main() { var handle = new AutoResetEvent(false); F(handle); handle.WaitOne(1000 * 60); Console.WriteLine(i); } }"; var expected = @" 42 "; CompileAndVerify(source, expectedOutput: expected).VerifyIL("Test.F", @" { // Code size 43 (0x2b) .maxstack 2 .locals init (Test.<F>d__1 V_0) IL_0000: ldloca.s V_0 IL_0002: call ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Create()"" IL_0007: stfld ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<F>d__1.<>t__builder"" IL_000c: ldloca.s V_0 IL_000e: ldarg.0 IL_000f: stfld ""System.Threading.AutoResetEvent Test.<F>d__1.handle"" IL_0014: ldloca.s V_0 IL_0016: ldc.i4.m1 IL_0017: stfld ""int Test.<F>d__1.<>1__state"" IL_001c: ldloca.s V_0 IL_001e: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<F>d__1.<>t__builder"" IL_0023: ldloca.s V_0 IL_0025: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Start<Test.<F>d__1>(ref Test.<F>d__1)"" IL_002a: ret } ").VerifyIL("Test.<F>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 190 (0xbe) .maxstack 3 .locals init (int V_0, System.Runtime.CompilerServices.TaskAwaiter V_1, System.Exception V_2) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<F>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0062 IL_000a: call ""System.Threading.Tasks.TaskFactory System.Threading.Tasks.Task.Factory.get"" IL_000f: ldsfld ""System.Action Test.<>c.<>9__1_0"" IL_0014: dup IL_0015: brtrue.s IL_002e IL_0017: pop IL_0018: ldsfld ""Test.<>c Test.<>c.<>9"" IL_001d: ldftn ""void Test.<>c.<F>b__1_0()"" IL_0023: newobj ""System.Action..ctor(object, System.IntPtr)"" IL_0028: dup IL_0029: stsfld ""System.Action Test.<>c.<>9__1_0"" IL_002e: callvirt ""System.Threading.Tasks.Task System.Threading.Tasks.TaskFactory.StartNew(System.Action)"" IL_0033: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()"" IL_0038: stloc.1 IL_0039: ldloca.s V_1 IL_003b: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get"" IL_0040: brtrue.s IL_007e IL_0042: ldarg.0 IL_0043: ldc.i4.0 IL_0044: dup IL_0045: stloc.0 IL_0046: stfld ""int Test.<F>d__1.<>1__state"" IL_004b: ldarg.0 IL_004c: ldloc.1 IL_004d: stfld ""System.Runtime.CompilerServices.TaskAwaiter Test.<F>d__1.<>u__1"" IL_0052: ldarg.0 IL_0053: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<F>d__1.<>t__builder"" IL_0058: ldloca.s V_1 IL_005a: ldarg.0 IL_005b: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, Test.<F>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter, ref Test.<F>d__1)"" IL_0060: leave.s IL_00bd IL_0062: ldarg.0 IL_0063: ldfld ""System.Runtime.CompilerServices.TaskAwaiter Test.<F>d__1.<>u__1"" IL_0068: stloc.1 IL_0069: ldarg.0 IL_006a: ldflda ""System.Runtime.CompilerServices.TaskAwaiter Test.<F>d__1.<>u__1"" IL_006f: initobj ""System.Runtime.CompilerServices.TaskAwaiter"" IL_0075: ldarg.0 IL_0076: ldc.i4.m1 IL_0077: dup IL_0078: stloc.0 IL_0079: stfld ""int Test.<F>d__1.<>1__state"" IL_007e: ldloca.s V_1 IL_0080: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()"" IL_0085: ldarg.0 IL_0086: ldfld ""System.Threading.AutoResetEvent Test.<F>d__1.handle"" IL_008b: callvirt ""bool System.Threading.EventWaitHandle.Set()"" IL_0090: pop IL_0091: leave.s IL_00aa } catch System.Exception { IL_0093: stloc.2 IL_0094: ldarg.0 IL_0095: ldc.i4.s -2 IL_0097: stfld ""int Test.<F>d__1.<>1__state"" IL_009c: ldarg.0 IL_009d: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<F>d__1.<>t__builder"" IL_00a2: ldloc.2 IL_00a3: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetException(System.Exception)"" IL_00a8: leave.s IL_00bd } IL_00aa: ldarg.0 IL_00ab: ldc.i4.s -2 IL_00ad: stfld ""int Test.<F>d__1.<>1__state"" IL_00b2: ldarg.0 IL_00b3: ldflda ""System.Runtime.CompilerServices.AsyncVoidMethodBuilder Test.<F>d__1.<>t__builder"" IL_00b8: call ""void System.Runtime.CompilerServices.AsyncVoidMethodBuilder.SetResult()"" IL_00bd: ret } "); } [Fact] [WorkItem(564036, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/564036")] public void InferFromAsyncLambda() { var source = @"using System; using System.Threading.Tasks; class Program { public static T CallWithCatch<T>(Func<T> func) { Console.WriteLine(typeof(T).ToString()); return func(); } private static async Task LoadTestDataAsync() { await CallWithCatch(async () => await LoadTestData()); } private static async Task LoadTestData() { await Task.Run(() => { }); } public static void Main(string[] args) { Task t = LoadTestDataAsync(); t.Wait(1000); } }"; var expected = @"System.Threading.Tasks.Task"; CompileAndVerify(source, expectedOutput: expected); } [Fact] [WorkItem(620987, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/620987")] public void PrematureNull() { var source = @"using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; class Program { public static void Main(string[] args) { try { var ar = FindReferencesInDocumentAsync(""Document""); ar.Wait(1000 * 60); Console.WriteLine(ar.Result); } catch (Exception ex) { Console.WriteLine(ex); } } internal static async Task<string> GetTokensWithIdentifierAsync() { Console.WriteLine(""in GetTokensWithIdentifierAsync""); return ""GetTokensWithIdentifierAsync""; } protected static async Task<string> FindReferencesInTokensAsync( string document, string tokens) { Console.WriteLine(""in FindReferencesInTokensAsync""); if (tokens == null) throw new NullReferenceException(""tokens""); Console.WriteLine(""tokens were fine""); if (document == null) throw new NullReferenceException(""document""); Console.WriteLine(""document was fine""); return ""FindReferencesInTokensAsync""; } public static async Task<string> FindReferencesInDocumentAsync( string document) { Console.WriteLine(""in FindReferencesInDocumentAsync""); if (document == null) throw new NullReferenceException(""document""); var nonAliasReferences = await FindReferencesInTokensAsync( document, await GetTokensWithIdentifierAsync() ).ConfigureAwait(true); return ""done!""; } }"; var expected = @"in FindReferencesInDocumentAsync in GetTokensWithIdentifierAsync in FindReferencesInTokensAsync tokens were fine document was fine done!"; CompileAndVerify(source, expectedOutput: expected); } [Fact] [WorkItem(621705, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/621705")] public void GenericAsyncLambda() { var source = @"using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; class G<T> { T t; public G(T t, Func<T, Task<T>> action) { var tt = action(t); var completed = tt.Wait(1000 * 60); Debug.Assert(completed); this.t = tt.Result; } public override string ToString() { return t.ToString(); } } class Test { static G<U> M<U>(U t) { return new G<U>(t, async x => { return await IdentityAsync(x); } ); } static async Task<V> IdentityAsync<V>(V x) { await Task.Delay(1); return x; } public static void Main() { var g = M(12); Console.WriteLine(g); } }"; var expected = @"12"; CompileAndVerify(source, expectedOutput: expected); } [Fact] [WorkItem(602028, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602028")] public void BetterConversionFromAsyncLambda() { var source = @"using System.Threading; using System.Threading.Tasks; using System; class TestCase { public static int Goo(Func<Task<double>> f) { return 12; } public static int Goo(Func<Task<object>> f) { return 13; } public static void Main() { Console.WriteLine(Goo(async delegate() { return 14; })); } } "; var expected = @"12"; CompileAndVerify(source, expectedOutput: expected); } [Fact] [WorkItem(602206, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602206")] public void ExtensionAddMethod() { var source = @"using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; static public class Extension { static public void Add<T>(this Stack<T> stack, T item) { Console.WriteLine(""Add "" + item.ToString()); stack.Push(item); } } class TestCase { AutoResetEvent handle = new AutoResetEvent(false); private async Task<T> GetVal<T>(T x) { await Task.Delay(1); Console.WriteLine(""GetVal "" + x.ToString()); return x; } public async void Run() { try { Stack<int> stack = new Stack<int>() { await GetVal(1), 2, 3 }; // CS0117 } finally { handle.Set(); } } public static void Main(string[] args) { var tc = new TestCase(); tc.Run(); tc.handle.WaitOne(1000 * 60); } }"; var expected = @"GetVal 1 Add 1 Add 2 Add 3"; CompileAndVerify(source, expectedOutput: expected); } [Fact] [WorkItem(748527, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/748527")] public void Bug748527() { var source = @"using System.Threading.Tasks; using System; namespace A { public struct TestClass { async public System.Threading.Tasks.Task<int> IntRet(int IntI) { return await ((Func<Task<int>>)(async ()=> { await Task.Yield(); return IntI ; } ))() ; } } public class B { async public static System.Threading.Tasks.Task<int> MainMethod() { int MyRet = 0; TestClass TC = new TestClass(); if (( await ((Func<Task<int>>)(async ()=> { await Task.Yield(); return (await(new TestClass().IntRet( await ((Func<Task<int>>)(async ()=> { await Task.Yield(); return 3 ; } ))() ))) ; } ))() ) != await ((Func<Task<int>>)(async ()=> { await Task.Yield(); return 3 ; } ))() ) { MyRet = 1; } return await ((Func<Task<int>>)(async ()=> {await Task.Yield(); return MyRet;}))(); } static void Main () { MainMethod(); return; } } }"; var expectedOutput = ""; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] [WorkItem(602216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602216")] public void AsyncMethodOnlyWritesToEnclosingStruct() { var source = @"public struct GenC<T> where T : struct { public T? valueN; public async void Test(T t) { valueN = t; } } public class Test { public static void Main() { int test = 12; GenC<int> _int = new GenC<int>(); _int.Test(test); System.Console.WriteLine(_int.valueN ?? 1); } }"; var expected = @"1"; CompileAndVerify(source, expectedOutput: expected); } [Fact] [WorkItem(602246, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/602246")] public void Bug602246() { var source = @"using System; using System.Threading.Tasks; public class TestCase { public static async Task<T> Run<T>(T t) { await Task.Delay(1); Func<Func<Task<T>>, Task<T>> f = async (x) => { return await x(); }; var rez = await f(async () => { await Task.Delay(1); return t; }); return rez; } public static void Main() { var t = TestCase.Run<int>(12); if (!t.Wait(1000 * 60)) throw new Exception(); Console.Write(t.Result); } }"; var expected = @"12"; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(628654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/628654")] [Fact] public void AsyncWithDynamic01() { var source = @" using System; using System.Threading.Tasks; class Program { static void Main() { Goo<int>().Wait(); } static async Task Goo<T>() { Console.WriteLine(""{0}"" as dynamic, await Task.FromResult(new T[] { })); } }"; var expected = @" System.Int32[] "; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(640282, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/640282")] [Fact] public void CustomAsyncWithDynamic01() { var source = @" using System; using System.Threading; using System.Threading.Tasks; class MyTask { public dynamic GetAwaiter() { return new MyTaskAwaiter<Action>(); } public async void Run<T>() { int tests = 0; tests++; dynamic myTask = new MyTask(); var x = await myTask; if (x == 123) Driver.Count++; Driver.Result = Driver.Count - tests; //When test complete, set the flag. Driver.CompletedSignal.Set(); } } class MyTaskAwaiter<U> { public void OnCompleted(U continuationAction) { } public int GetResult() { return 123; } public dynamic IsCompleted { get { return true; } } } class Driver { public static int Result = -1; public static int Count = 0; public static AutoResetEvent CompletedSignal = new AutoResetEvent(false); public static void Main() { new MyTask().Run<int>(); CompletedSignal.WaitOne(); // 0 - success // 1 - failed (test completed) // -1 - failed (test incomplete - deadlock, etc) Console.WriteLine(Driver.Result); } }"; var expected = @"0"; CompileAndVerify(source, expectedOutput: expected); } [WorkItem(840843, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/840843")] [Fact] public void MissingAsyncVoidMethodBuilder() { var source = @" class C { async void M() {} } "; var comp = CSharpTestBase.CreateEmptyCompilation(source, new[] { Net40.mscorlib }, TestOptions.ReleaseDll); // NOTE: 4.0, not 4.5, so it's missing the async helpers. // CONSIDER: It would be nice if we didn't squiggle the whole method body, but this is a corner case. comp.VerifyEmitDiagnostics( // (4,16): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async void M() {} Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(4, 16), // (4,20): error CS0518: Predefined type 'System.Runtime.CompilerServices.AsyncVoidMethodBuilder' is not defined or imported // async void M() {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "{}").WithArguments("System.Runtime.CompilerServices.AsyncVoidMethodBuilder").WithLocation(4, 20), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.AsyncVoidMethodBuilder.Create' // async void M() {} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{}").WithArguments("System.Runtime.CompilerServices.AsyncVoidMethodBuilder", "Create").WithLocation(4, 20), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext' // async void M() {} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{}").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "MoveNext").WithLocation(4, 20), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine' // async void M() {} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{}").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "SetStateMachine").WithLocation(4, 20)); } [Fact] public void MissingAsyncTaskMethodBuilder() { var source = @"using System.Threading.Tasks; class C { async Task M() {} }"; var comp = CSharpTestBase.CreateEmptyCompilation(source, new[] { Net40.mscorlib }, TestOptions.ReleaseDll); // NOTE: 4.0, not 4.5, so it's missing the async helpers. comp.VerifyEmitDiagnostics( // (4,16): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async Task M() {} Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "M").WithLocation(4, 16), // (4,20): error CS0518: Predefined type 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder' is not defined or imported // async Task M() {} Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "{}").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder").WithLocation(4, 20), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Create' // async Task M() {} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{}").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder", "Create").WithLocation(4, 20), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Task' // async Task M() {} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{}").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder", "Task").WithLocation(4, 20), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext' // async Task M() {} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{}").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "MoveNext").WithLocation(4, 20), // (4,20): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine' // async Task M() {} Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{}").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "SetStateMachine").WithLocation(4, 20)); } [Fact] public void MissingAsyncTaskMethodBuilder_T() { var source = @"using System.Threading.Tasks; class C { async Task<int> F() => 3; }"; var comp = CSharpTestBase.CreateEmptyCompilation(source, new[] { Net40.mscorlib }, TestOptions.ReleaseDll); // NOTE: 4.0, not 4.5, so it's missing the async helpers. comp.VerifyEmitDiagnostics( // (4,21): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // async Task<int> F() => 3; Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "F").WithLocation(4, 21), // (4,25): error CS0518: Predefined type 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1' is not defined or imported // async Task<int> F() => 3; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "=> 3").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1").WithLocation(4, 25), // (4,25): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Create' // async Task<int> F() => 3; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> 3").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1", "Create").WithLocation(4, 25), // (4,25): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Task' // async Task<int> F() => 3; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> 3").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1", "Task").WithLocation(4, 25), // (4,25): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext' // async Task<int> F() => 3; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> 3").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "MoveNext").WithLocation(4, 25), // (4,25): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine' // async Task<int> F() => 3; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> 3").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "SetStateMachine").WithLocation(4, 25)); } private static string AsyncBuilderCode(string builderTypeName, string tasklikeTypeName, string genericTypeParameter = null, bool isStruct = false) { string ofT = genericTypeParameter == null ? "" : "<" + genericTypeParameter + ">"; return $@" public {(isStruct ? "struct" : "class")} {builderTypeName}{ofT} {{ public static {builderTypeName}{ofT} Create() => default({builderTypeName}{ofT}); public {tasklikeTypeName}{ofT} Task {{ get; }} public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine {{ }} public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine {{ }} public void SetException(System.Exception exception) {{ }} public void SetResult({(genericTypeParameter == null ? "" : genericTypeParameter + " result")}) {{ }} public void SetStateMachine(IAsyncStateMachine stateMachine) {{ }} public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine {{ }} }} "; } [Fact] public void PresentAsyncTasklikeBuilderMethod() { var source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { async ValueTask f() { await (Task)null; } async ValueTask<int> g() { await (Task)null; return 1; } } [AsyncMethodBuilder(typeof(ValueTaskMethodBuilder))] struct ValueTask { } [AsyncMethodBuilder(typeof(ValueTaskMethodBuilder<>))] struct ValueTask<T> { } class ValueTaskMethodBuilder { public static ValueTaskMethodBuilder Create() => null; public ValueTask Task { get; } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } public void SetException(System.Exception exception) { } public void SetResult() { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } } class ValueTaskMethodBuilder<T> { public static ValueTaskMethodBuilder<T> Create() => null; public ValueTask<T> Task { get; } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } public void SetException(System.Exception exception) { } public void SetResult(T result) { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var v = CompileAndVerify(source, null, options: TestOptions.ReleaseDll); v.VerifyIL("C.g", @"{ // Code size 45 (0x2d) .maxstack 2 .locals init (C.<g>d__1 V_0) IL_0000: ldloca.s V_0 IL_0002: call ""ValueTaskMethodBuilder<int> ValueTaskMethodBuilder<int>.Create()"" IL_0007: stfld ""ValueTaskMethodBuilder<int> C.<g>d__1.<>t__builder"" IL_000c: ldloca.s V_0 IL_000e: ldc.i4.m1 IL_000f: stfld ""int C.<g>d__1.<>1__state"" IL_0014: ldloc.0 IL_0015: ldfld ""ValueTaskMethodBuilder<int> C.<g>d__1.<>t__builder"" IL_001a: ldloca.s V_0 IL_001c: callvirt ""void ValueTaskMethodBuilder<int>.Start<C.<g>d__1>(ref C.<g>d__1)"" IL_0021: ldloc.0 IL_0022: ldfld ""ValueTaskMethodBuilder<int> C.<g>d__1.<>t__builder"" IL_0027: callvirt ""ValueTask<int> ValueTaskMethodBuilder<int>.Task.get"" IL_002c: ret }"); v.VerifyIL("C.f", @"{ // Code size 45 (0x2d) .maxstack 2 .locals init (C.<f>d__0 V_0) IL_0000: ldloca.s V_0 IL_0002: call ""ValueTaskMethodBuilder ValueTaskMethodBuilder.Create()"" IL_0007: stfld ""ValueTaskMethodBuilder C.<f>d__0.<>t__builder"" IL_000c: ldloca.s V_0 IL_000e: ldc.i4.m1 IL_000f: stfld ""int C.<f>d__0.<>1__state"" IL_0014: ldloc.0 IL_0015: ldfld ""ValueTaskMethodBuilder C.<f>d__0.<>t__builder"" IL_001a: ldloca.s V_0 IL_001c: callvirt ""void ValueTaskMethodBuilder.Start<C.<f>d__0>(ref C.<f>d__0)"" IL_0021: ldloc.0 IL_0022: ldfld ""ValueTaskMethodBuilder C.<f>d__0.<>t__builder"" IL_0027: callvirt ""ValueTask ValueTaskMethodBuilder.Task.get"" IL_002c: ret }"); } [Fact] public void AsyncTasklikeGenericBuilder() { var source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; class N { class BN { } class BG<U> { } [AsyncMethodBuilder(typeof(N.BG<int>))] class T_NIT<V> { } [AsyncMethodBuilder(typeof(N.BG<int>))] class T_NIN { } [AsyncMethodBuilder(typeof(N.BG<>))] class T_NOT<V> { } [AsyncMethodBuilder(typeof(N.BG<>))] class T_NON { } [AsyncMethodBuilder(typeof(N.BN))] class T_NNT<V> { } [AsyncMethodBuilder(typeof(N.BN))] class T_NNN { } async T_NIT<int> f1() => await Task.FromResult(1); async T_NIN f2() => await Task.FromResult(1); async T_NOT<int> f3() => await Task.FromResult(1); // ok builderType genericity (but missing members) async T_NON f4() => await Task.FromResult(1); async T_NNT<int> f5() => await Task.FromResult(1); async T_NNN f6() => await Task.FromResult(1); // ok builderType genericity (but missing members) } class G<T> { class BN { } class BG<U> { } [AsyncMethodBuilder(typeof(G<int>.BG<int>))] class T_IIT<V> { } [AsyncMethodBuilder(typeof(G<int>.BG<int>))] class T_IIN { } [AsyncMethodBuilder(typeof(G<int>.BN))] class T_INT<V> { } [AsyncMethodBuilder(typeof(G<int>.BN))] class T_INN { } [AsyncMethodBuilder(typeof(G<>.BG<>))] class T_OOT<V> { } [AsyncMethodBuilder(typeof(G<>.BG<>))] class T_OON { } [AsyncMethodBuilder(typeof(G<>.BN))] class T_ONT<V> { } [AsyncMethodBuilder(typeof(G<>.BN))] class T_ONN { } async T_IIT<int> g1() => await Task.FromResult(1); async T_IIN g2() => await Task.FromResult(1); async T_INT<int> g3() => await Task.FromResult(1); async T_INN g4() => await Task.FromResult(1); // might have been ok builder genericity but we decided not async T_OOT<int> g5() => await Task.FromResult(1); async T_OON g6() => await Task.FromResult(1); async T_ONT<int> g7() => await Task.FromResult(1); async T_ONN g8() => await Task.FromResult(1); } class Program { static void Main() { } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (17,27): error CS8940: A generic task-like return type was expected, but the type 'N.BG<int>' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. // async T_NIT<int> f1() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_WrongArityAsyncReturn, "=> await Task.FromResult(1)").WithArguments("N.BG<int>").WithLocation(17, 27), // (18,22): error CS1983: The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T> // async T_NIN f2() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.FromResult(1)").WithLocation(18, 22), // (19,27): error CS0656: Missing compiler required member 'N.BG<int>.Task' // async T_NOT<int> f3() => await Task.FromResult(1); // ok builderType genericity (but missing members) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.FromResult(1)").WithArguments("N.BG<int>", "Task").WithLocation(19, 27), // (19,27): error CS0656: Missing compiler required member 'N.BG<int>.Create' // async T_NOT<int> f3() => await Task.FromResult(1); // ok builderType genericity (but missing members) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.FromResult(1)").WithArguments("N.BG<int>", "Create").WithLocation(19, 27), // (20,22): error CS1983: The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T> // async T_NON f4() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.FromResult(1)").WithLocation(20, 22), // (21,27): error CS8940: A generic task-like return type was expected, but the type 'N.BN' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. // async T_NNT<int> f5() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_WrongArityAsyncReturn, "=> await Task.FromResult(1)").WithArguments("N.BN").WithLocation(21, 27), // (22,22): error CS0656: Missing compiler required member 'N.BN.Task' // async T_NNN f6() => await Task.FromResult(1); // ok builderType genericity (but missing members) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.FromResult(1)").WithArguments("N.BN", "Task").WithLocation(22, 22), // (22,22): error CS0656: Missing compiler required member 'N.BN.Create' // async T_NNN f6() => await Task.FromResult(1); // ok builderType genericity (but missing members) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.FromResult(1)").WithArguments("N.BN", "Create").WithLocation(22, 22), // (39,27): error CS8940: A generic task-like return type was expected, but the type 'G<int>.BG<int>' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. // async T_IIT<int> g1() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_WrongArityAsyncReturn, "=> await Task.FromResult(1)").WithArguments("G<int>.BG<int>").WithLocation(39, 27), // (40,22): error CS1983: The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T> // async T_IIN g2() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.FromResult(1)").WithLocation(40, 22), // (41,27): error CS8940: A generic task-like return type was expected, but the type 'G<int>.BN' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. // async T_INT<int> g3() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_WrongArityAsyncReturn, "=> await Task.FromResult(1)").WithArguments("G<int>.BN").WithLocation(41, 27), // (42,22): error CS1983: The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T> // async T_INN g4() => await Task.FromResult(1); // might have been ok builder genericity but we decided not Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.FromResult(1)").WithLocation(42, 22), // (43,27): error CS8940: A generic task-like return type was expected, but the type 'G<>.BG<>' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. // async T_OOT<int> g5() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_WrongArityAsyncReturn, "=> await Task.FromResult(1)").WithArguments("G<>.BG<>").WithLocation(43, 27), // (44,22): error CS1983: The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T> // async T_OON g6() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.FromResult(1)").WithLocation(44, 22), // (45,27): error CS8940: A generic task-like return type was expected, but the type 'G<>.BN' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. // async T_ONT<int> g7() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_WrongArityAsyncReturn, "=> await Task.FromResult(1)").WithArguments("G<>.BN").WithLocation(45, 27), // (46,22): error CS1983: The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T> // async T_ONN g8() => await Task.FromResult(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.FromResult(1)").WithLocation(46, 22) ); } [Fact] public void AsyncTasklikeBadAttributeArgument1() { var source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; [AsyncMethodBuilder(typeof(void))] class T { } class Program { static void Main() { } async T f() => await Task.Delay(1); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (9,17): error CS1983: The return type of an async method must be void, Task or Task<T> // async T f() => await Task.Delay(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.Delay(1)").WithLocation(9, 17) ); } [Fact] public void AsyncTasklikeBadAttributeArgument2() { var source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; [AsyncMethodBuilder(""hello"")] class T { } class Program { static void Main() { } async T f() => await Task.Delay(1); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (5,15): error CS1503: Argument 1: cannot convert from 'string' to 'System.Type' // [AsyncMethodBuilder("hello")] class T { } Diagnostic(ErrorCode.ERR_BadArgType, @"""hello""").WithArguments("1", "string", "System.Type").WithLocation(5, 21), // (9,13): error CS1983: The return type of an async method must be void, Task or Task<T> // async T f() => await Task.Delay(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "f").WithLocation(9, 13) ); } [Fact] public void AsyncTasklikeBadAttributeArgument3() { var source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; [AsyncMethodBuilder(typeof(Nonexistent))] class T { } class Program { static void Main() { } async T f() => await Task.Delay(1); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (5,22): error CS0246: The type or namespace name 'Nonexistent' could not be found (are you missing a using directive or an assembly reference?) // [AsyncMethodBuilder(typeof(Nonexistent))] class T { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nonexistent").WithArguments("Nonexistent").WithLocation(5, 28) ); } [Fact] public void AsyncTasklikeBadAttributeArgument4() { var source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; [AsyncMethodBuilder(null)] class T { } class Program { static void Main() { } async T f() => await Task.Delay(1); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (9,17): error CS1983: The return type of an async method must be void, Task or Task<T> // async T f() => await Task.Delay(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.Delay(1)").WithLocation(9, 17) ); } [Fact] public void AsyncTasklikeMissingBuilderType() { // Builder var libB = @"public class B { }"; var cB = CreateCompilationWithMscorlib45(libB); var rB = cB.EmitToImageReference(); // Tasklike var libT = @" using System.Runtime.CompilerServices; [AsyncMethodBuilder(typeof(B))] public class T { } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var cT = CreateCompilationWithMscorlib45(libT, references: new[] { rB }); var rT = cT.EmitToImageReference(); // Consumer, fails to reference builder var source = @" using System.Threading.Tasks; class Program { static void Main() { } async T f() => await Task.Delay(1); } "; var c = CreateCompilationWithMscorlib45(source, references: new[] { rT }); c.VerifyEmitDiagnostics( // (6,17): error CS1983: The return type of an async method must be void, Task or Task<T> // async T f() => await Task.Delay(1); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.Delay(1)").WithLocation(6, 17) ); } [Fact] public void AsyncTasklikeCreateMethod() { var source = $@" using System.Runtime.CompilerServices; using System.Threading.Tasks; class Program {{ static void Main() {{ }} async T0 f0() => await Task.Delay(0); async T1 f1() => await Task.Delay(1); async T2 f2() => await Task.Delay(2); async T3 f3() => await Task.Delay(3); async T4 f4() => await Task.Delay(4); async T5 f5() => await Task.Delay(5); async T6 f6() => await Task.Delay(6); async T7 f7() => await Task.Delay(7); async T8 f8() => await Task.Delay(8); }} [AsyncMethodBuilder(typeof(B0))] public class T0 {{ }} [AsyncMethodBuilder(typeof(B1))] public class T1 {{ }} [AsyncMethodBuilder(typeof(B2))] public class T2 {{ }} [AsyncMethodBuilder(typeof(B3))] public class T3 {{ }} [AsyncMethodBuilder(typeof(B4))] public class T4 {{ }} [AsyncMethodBuilder(typeof(B5))] public class T5 {{ }} [AsyncMethodBuilder(typeof(B6))] public class T6 {{ }} [AsyncMethodBuilder(typeof(B7))] public class T7 {{ }} [AsyncMethodBuilder(typeof(B8))] public class T8 {{ }} {AsyncBuilderCode("B0", "T0").Replace("public static B0 Create()", "public static B0 Create()")} {AsyncBuilderCode("B1", "T1").Replace("public static B1 Create()", "private static B1 Create()")} {AsyncBuilderCode("B2", "T2").Replace("public static B2 Create() => default(B2);", "public static void Create() { }")} {AsyncBuilderCode("B3", "T3").Replace("public static B3 Create() => default(B3);", "public static B1 Create() => default(B1);")} {AsyncBuilderCode("B4", "T4").Replace("public static B4 Create()", "public static B4 Create(int i)")} {AsyncBuilderCode("B5", "T5").Replace("public static B5 Create()", "public static B5 Create<T>()")} {AsyncBuilderCode("B6", "T6").Replace("public static B6 Create()", "public static B6 Create(object arg = null)")} {AsyncBuilderCode("B7", "T7").Replace("public static B7 Create()", "public static B7 Create(params object[] arg)")} {AsyncBuilderCode("B8", "T8").Replace("public static B8 Create()", "public B8 Create()")} namespace System.Runtime.CompilerServices {{ class AsyncMethodBuilderAttribute : System.Attribute {{ public AsyncMethodBuilderAttribute(System.Type t) {{ }} }} }} "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (8,19): error CS0656: Missing compiler required member 'B1.Create' // async T1 f1() => await Task.Delay(1); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.Delay(1)").WithArguments("B1", "Create").WithLocation(8, 19), // (9,19): error CS0656: Missing compiler required member 'B2.Create' // async T2 f2() => await Task.Delay(2); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.Delay(2)").WithArguments("B2", "Create").WithLocation(9, 19), // (10,19): error CS0656: Missing compiler required member 'B3.Create' // async T3 f3() => await Task.Delay(3); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.Delay(3)").WithArguments("B3", "Create").WithLocation(10, 19), // (11,19): error CS0656: Missing compiler required member 'B4.Create' // async T4 f4() => await Task.Delay(4); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.Delay(4)").WithArguments("B4", "Create").WithLocation(11, 19), // (12,19): error CS0656: Missing compiler required member 'B5.Create' // async T5 f5() => await Task.Delay(5); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.Delay(5)").WithArguments("B5", "Create").WithLocation(12, 19), // (13,19): error CS0656: Missing compiler required member 'B6.Create' // async T6 f6() => await Task.Delay(6); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.Delay(6)").WithArguments("B6", "Create").WithLocation(13, 19), // (14,19): error CS0656: Missing compiler required member 'B7.Create' // async T7 f7() => await Task.Delay(7); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.Delay(7)").WithArguments("B7", "Create").WithLocation(14, 19), // (15,19): error CS0656: Missing compiler required member 'B8.Create' // async T8 f8() => await Task.Delay(8); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "=> await Task.Delay(8)").WithArguments("B8", "Create").WithLocation(15, 19) ); } [Fact] public void AsyncInterfaceTasklike() { var source = $@" using System.Runtime.CompilerServices; using System.Threading.Tasks; class Program {{ static void Main() {{ }} async I0 f0() => await Task.Delay(0); async I1<int> f1() {{ await Task.Delay(1); return 1; }} }} [AsyncMethodBuilder(typeof(B0))] public interface I0 {{ }} [AsyncMethodBuilder(typeof(B1<>))] public interface I1<T> {{ }} {AsyncBuilderCode("B0", "I0", genericTypeParameter: null)} {AsyncBuilderCode("B1", "I1", genericTypeParameter: "T")} namespace System.Runtime.CompilerServices {{ class AsyncMethodBuilderAttribute : System.Attribute {{ public AsyncMethodBuilderAttribute(System.Type t) {{ }} }} }} "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( ); } [Fact] public void AsyncTasklikeBuilderAccessibility() { var source = $@" using System.Runtime.CompilerServices; using System.Threading.Tasks; [AsyncMethodBuilder(typeof(B1))] public class T1 {{ }} [AsyncMethodBuilder(typeof(B2))] public class T2 {{ }} [AsyncMethodBuilder(typeof(B3))] internal class T3 {{ }} [AsyncMethodBuilder(typeof(B4))] internal class T4 {{ }} {AsyncBuilderCode("B1", "T1").Replace("public class B1", "public class B1")} {AsyncBuilderCode("B2", "T2").Replace("public class B2", "internal class B2")} {AsyncBuilderCode("B3", "T3").Replace("public class B3", "public class B3").Replace("public T3 Task { get; }", "internal T3 Task {get; }")} {AsyncBuilderCode("B4", "T4").Replace("public class B4", "internal class B4")} class Program {{ static void Main() {{ }} async T1 f1() => await Task.Delay(1); async T2 f2() => await Task.Delay(2); async T3 f3() => await Task.Delay(3); async T4 f4() => await Task.Delay(4); }} namespace System.Runtime.CompilerServices {{ class AsyncMethodBuilderAttribute : System.Attribute {{ public AsyncMethodBuilderAttribute(System.Type t) {{ }} }} }} "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (66,19): error CS1983: The return type of an async method must be void, Task or Task<T> // async T2 f2() => await Task.Delay(2); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.Delay(2)").WithLocation(66, 19), // (67,19): error CS1983: The return type of an async method must be void, Task or Task<T> // async T3 f3() => await Task.Delay(3); Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=> await Task.Delay(3)").WithLocation(67, 19) ); } [Fact] public void AsyncTasklikeLambdaOverloads() { var source = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { static void Main() { f(async () => { await (Task)null; }); g(async () => { await (Task)null; }); k(async () => { await (Task)null; }); } static void f(Func<MyTask> lambda) { } static void g(Func<Task> lambda) { } static void k<T>(Func<T> lambda) { } } [AsyncMethodBuilder(typeof(MyTaskBuilder))] class MyTask { } class MyTaskBuilder { public static MyTaskBuilder Create() => null; public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void SetResult() { } public void SetException(Exception exception) { } public MyTask Task => default(MyTask); public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var v = CompileAndVerify(source, null, options: TestOptions.ReleaseDll); v.VerifyIL("C.Main", @" { // Code size 109 (0x6d) .maxstack 2 IL_0000: ldsfld ""System.Func<MyTask> C.<>c.<>9__0_0"" IL_0005: dup IL_0006: brtrue.s IL_001f IL_0008: pop IL_0009: ldsfld ""C.<>c C.<>c.<>9"" IL_000e: ldftn ""MyTask C.<>c.<Main>b__0_0()"" IL_0014: newobj ""System.Func<MyTask>..ctor(object, System.IntPtr)"" IL_0019: dup IL_001a: stsfld ""System.Func<MyTask> C.<>c.<>9__0_0"" IL_001f: call ""void C.f(System.Func<MyTask>)"" IL_0024: ldsfld ""System.Func<System.Threading.Tasks.Task> C.<>c.<>9__0_1"" IL_0029: dup IL_002a: brtrue.s IL_0043 IL_002c: pop IL_002d: ldsfld ""C.<>c C.<>c.<>9"" IL_0032: ldftn ""System.Threading.Tasks.Task C.<>c.<Main>b__0_1()"" IL_0038: newobj ""System.Func<System.Threading.Tasks.Task>..ctor(object, System.IntPtr)"" IL_003d: dup IL_003e: stsfld ""System.Func<System.Threading.Tasks.Task> C.<>c.<>9__0_1"" IL_0043: call ""void C.g(System.Func<System.Threading.Tasks.Task>)"" IL_0048: ldsfld ""System.Func<System.Threading.Tasks.Task> C.<>c.<>9__0_2"" IL_004d: dup IL_004e: brtrue.s IL_0067 IL_0050: pop IL_0051: ldsfld ""C.<>c C.<>c.<>9"" IL_0056: ldftn ""System.Threading.Tasks.Task C.<>c.<Main>b__0_2()"" IL_005c: newobj ""System.Func<System.Threading.Tasks.Task>..ctor(object, System.IntPtr)"" IL_0061: dup IL_0062: stsfld ""System.Func<System.Threading.Tasks.Task> C.<>c.<>9__0_2"" IL_0067: call ""void C.k<System.Threading.Tasks.Task>(System.Func<System.Threading.Tasks.Task>)"" IL_006c: ret }"); } [Fact] public void AsyncTasklikeIncompleteBuilder() { var source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { static void Main() { } async ValueTask0 f() { await Task.Delay(0); } async ValueTask1 g() { await Task.Delay(0); } async ValueTask2 h() { await Task.Delay(0); } } [AsyncMethodBuilder(typeof(ValueTaskMethodBuilder0))] struct ValueTask0 { } [AsyncMethodBuilder(typeof(ValueTaskMethodBuilder1))] struct ValueTask1 { } [AsyncMethodBuilder(typeof(ValueTaskMethodBuilder2))] struct ValueTask2 { } class ValueTaskMethodBuilder0 { public static ValueTaskMethodBuilder0 Create() => null; public ValueTask0 Task => default(ValueTask0); } class ValueTaskMethodBuilder1 { public static ValueTaskMethodBuilder1 Create() => null; public ValueTask1 Task => default(ValueTask1); public void SetException(System.Exception ex) { } } class ValueTaskMethodBuilder2 { public static ValueTaskMethodBuilder2 Create() => null; public ValueTask2 Task => default(ValueTask2); public void SetException(System.Exception ex) { } public void SetResult() { } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (7,26): error CS0656: Missing compiler required member 'ValueTaskMethodBuilder0.SetException' // async ValueTask0 f() { await Task.Delay(0); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); }").WithArguments("ValueTaskMethodBuilder0", "SetException").WithLocation(7, 26), // (8,26): error CS0656: Missing compiler required member 'ValueTaskMethodBuilder1.SetResult' // async ValueTask1 g() { await Task.Delay(0); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); }").WithArguments("ValueTaskMethodBuilder1", "SetResult").WithLocation(8, 26), // (9,26): error CS0656: Missing compiler required member 'ValueTaskMethodBuilder2.AwaitOnCompleted' // async ValueTask2 h() { await Task.Delay(0); } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await Task.Delay(0); }").WithArguments("ValueTaskMethodBuilder2", "AwaitOnCompleted").WithLocation(9, 26) ); } [Fact] public void AsyncTasklikeBuilderArityMismatch() { var source = @" using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { async Mismatch1<int> f() { await (Task)null; return 1; } async Mismatch2 g() { await (Task)null; return 1; } } [AsyncMethodBuilder(typeof(Mismatch1MethodBuilder))] struct Mismatch1<T> { } [AsyncMethodBuilder(typeof(Mismatch2MethodBuilder<>))] struct Mismatch2 { } class Mismatch1MethodBuilder { public static Mismatch1MethodBuilder Create() => null; } class Mismatch2MethodBuilder<T> { public static Mismatch2MethodBuilder<T> Create() => null; } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp = CreateCompilationWithMscorlib45(source); comp.VerifyEmitDiagnostics( // (5,30): error CS8940: A generic task-like return type was expected, but the type 'Mismatch1MethodBuilder' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. // async Mismatch1<int> f() { await (Task)null; return 1; } Diagnostic(ErrorCode.ERR_WrongArityAsyncReturn, "{ await (Task)null; return 1; }").WithArguments("Mismatch1MethodBuilder").WithLocation(5, 30), // (6,45): error CS1997: Since 'C.g()' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>'? // async Mismatch2 g() { await (Task)null; return 1; } Diagnostic(ErrorCode.ERR_TaskRetNoObjectRequired, "return").WithArguments("C.g()").WithLocation(6, 45) ); } [WorkItem(12616, "https://github.com/dotnet/roslyn/issues/12616")] [Fact] public void AsyncTasklikeBuilderConstraints() { var source1 = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { static void Main() { } async MyTask f() { await (Task)null; } } [AsyncMethodBuilder(typeof(MyTaskBuilder))] class MyTask { } interface I { } class MyTaskBuilder { public static MyTaskBuilder Create() => null; public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void Start<TSM>(ref TSM stateMachine) where TSM : I { } public void AwaitOnCompleted<TA, TSM>(ref TA awaiter, ref TSM stateMachine) { } public void AwaitUnsafeOnCompleted<TA, TSM>(ref TA awaiter, ref TSM stateMachine) { } public void SetResult() { } public void SetException(Exception ex) { } public MyTask Task => null; } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp1 = CreateCompilation(source1, options: TestOptions.DebugExe); comp1.VerifyEmitDiagnostics( // (8,22): error CS0311: The type 'C.<f>d__1' cannot be used as type parameter 'TSM' in the generic type or method 'MyTaskBuilder.Start<TSM>(ref TSM)'. There is no implicit reference conversion from 'C.<f>d__1' to 'I'. // async MyTask f() { await (Task)null; } Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "{ await (Task)null; }").WithArguments("MyTaskBuilder.Start<TSM>(ref TSM)", "I", "TSM", "C.<f>d__1").WithLocation(8, 22)); var source2 = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { static void Main() { } async MyTask f() { await (Task)null; } } [AsyncMethodBuilder(typeof(MyTaskBuilder))] class MyTask { } class MyTaskBuilder { public static MyTaskBuilder Create() => null; public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void Start<TSM>(ref TSM stateMachine) where TSM : IAsyncStateMachine { } public void AwaitOnCompleted<TA, TSM>(ref TA awaiter, ref TSM stateMachine) where TA : INotifyCompletion where TSM : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TA, TSM>(ref TA awaiter, ref TSM stateMachine) { } public void SetResult() { } public void SetException(Exception ex) { } public MyTask Task => null; } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var comp2 = CreateCompilation(source2, options: TestOptions.DebugExe); comp2.VerifyEmitDiagnostics(); } [Fact] [WorkItem(868822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/868822")] public void AsyncDelegates() { var source = @"using System; using System.Threading.Tasks; class Program { static void Main(string[] args) { test1(); test2(); } static void test1() { Invoke(async delegate { if (0.ToString().Length == 0) { await Task.Yield(); } else { System.Console.WriteLine(0.ToString()); } }); } static string test2() { return Invoke(async delegate { if (0.ToString().Length == 0) { await Task.Yield(); return 1.ToString(); } else { System.Console.WriteLine(2.ToString()); return null; } }); } static void Invoke(Action method) { method(); } static void Invoke(Func<Task> method) { method().Wait(); } static TResult Invoke<TResult>(Func<TResult> method) { return method(); } internal static TResult Invoke<TResult>(Func<Task<TResult>> method) { if (method != null) { return Invoke1(async delegate { await Task.Yield(); return await method(); }); } return default(TResult); } internal static TResult Invoke1<TResult>(Func<Task<TResult>> method) { return method().Result; } } "; var expected = @"0 2"; CompileAndVerify(source, expectedOutput: expected); } [Fact] public void MutatingArrayOfStructs() { var source = @" using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; struct S { public int A; public int Mutate(int b) { A += b; return 1; } } class Test { static int i = 0; public static Task<int> G() { return null; } public static async Task<int> F() { S[] array = new S[10]; return array[1].Mutate(await G()); } }"; var v = CompileAndVerify(source, null, options: TestOptions.DebugDll); v.VerifyIL("Test.<F>d__2.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 241 (0xf1) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, Test.<F>d__2 V_3, System.Exception V_4) ~IL_0000: ldarg.0 IL_0001: ldfld ""int Test.<F>d__2.<>1__state"" IL_0006: stloc.0 .try { ~IL_0007: ldloc.0 IL_0008: brfalse.s IL_000c IL_000a: br.s IL_000e IL_000c: br.s IL_0070 -IL_000e: nop -IL_000f: ldarg.0 IL_0010: ldc.i4.s 10 IL_0012: newarr ""S"" IL_0017: stfld ""S[] Test.<F>d__2.<array>5__1"" -IL_001c: ldarg.0 IL_001d: ldarg.0 IL_001e: ldfld ""S[] Test.<F>d__2.<array>5__1"" IL_0023: stfld ""S[] Test.<F>d__2.<>s__3"" IL_0028: ldarg.0 IL_0029: ldfld ""S[] Test.<F>d__2.<>s__3"" IL_002e: ldc.i4.1 IL_002f: ldelema ""S"" IL_0034: pop IL_0035: call ""System.Threading.Tasks.Task<int> Test.G()"" IL_003a: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_003f: stloc.2 ~IL_0040: ldloca.s V_2 IL_0042: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_0047: brtrue.s IL_008c IL_0049: ldarg.0 IL_004a: ldc.i4.0 IL_004b: dup IL_004c: stloc.0 IL_004d: stfld ""int Test.<F>d__2.<>1__state"" <IL_0052: ldarg.0 IL_0053: ldloc.2 IL_0054: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_0059: ldarg.0 IL_005a: stloc.3 IL_005b: ldarg.0 IL_005c: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_0061: ldloca.s V_2 IL_0063: ldloca.s V_3 IL_0065: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.<F>d__2>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.<F>d__2)"" IL_006a: nop IL_006b: leave IL_00f0 >IL_0070: ldarg.0 IL_0071: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_0076: stloc.2 IL_0077: ldarg.0 IL_0078: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.<F>d__2.<>u__1"" IL_007d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0083: ldarg.0 IL_0084: ldc.i4.m1 IL_0085: dup IL_0086: stloc.0 IL_0087: stfld ""int Test.<F>d__2.<>1__state"" IL_008c: ldarg.0 IL_008d: ldloca.s V_2 IL_008f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0094: stfld ""int Test.<F>d__2.<>s__2"" IL_0099: ldarg.0 IL_009a: ldfld ""S[] Test.<F>d__2.<>s__3"" IL_009f: ldc.i4.1 IL_00a0: ldelema ""S"" IL_00a5: ldarg.0 IL_00a6: ldfld ""int Test.<F>d__2.<>s__2"" IL_00ab: call ""int S.Mutate(int)"" IL_00b0: stloc.1 IL_00b1: leave.s IL_00d4 } catch System.Exception { ~IL_00b3: stloc.s V_4 IL_00b5: ldarg.0 IL_00b6: ldc.i4.s -2 IL_00b8: stfld ""int Test.<F>d__2.<>1__state"" IL_00bd: ldarg.0 IL_00be: ldnull IL_00bf: stfld ""S[] Test.<F>d__2.<array>5__1"" IL_00c4: ldarg.0 IL_00c5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_00ca: ldloc.s V_4 IL_00cc: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetException(System.Exception)"" IL_00d1: nop IL_00d2: leave.s IL_00f0 } -IL_00d4: ldarg.0 IL_00d5: ldc.i4.s -2 IL_00d7: stfld ""int Test.<F>d__2.<>1__state"" ~IL_00dc: ldarg.0 IL_00dd: ldnull IL_00de: stfld ""S[] Test.<F>d__2.<array>5__1"" IL_00e3: ldarg.0 IL_00e4: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int> Test.<F>d__2.<>t__builder"" IL_00e9: ldloc.1 IL_00ea: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder<int>.SetResult(int)"" IL_00ef: nop IL_00f0: ret }", sequencePoints: "Test+<F>d__2.MoveNext"); } [Fact] public void MutatingStructWithUsing() { var source = @"using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; class Program { public static void Main() { (new Program()).Test().Wait(); } public async Task Test() { var list = new List<int> {1, 2, 3}; using (var enumerator = list.GetEnumerator()) { Console.WriteLine(enumerator.MoveNext()); Console.WriteLine(enumerator.Current); await Task.Delay(1); } } }"; var expectedOutput = @"True 1"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: expectedOutput); } [Fact, WorkItem(1942, "https://github.com/dotnet/roslyn/issues/1942")] public void HoistStructure() { var source = @" using System; using System.Threading.Tasks; namespace ConsoleApp { struct TestStruct { public long i; public long j; } class Program { static async Task TestAsync() { TestStruct t; t.i = 12; Console.WriteLine(""Before {0}"", t.i); // emits ""Before 12"" await Task.Delay(100); Console.WriteLine(""After {0}"", t.i); // emits ""After 0"" expecting ""After 12"" } static void Main(string[] args) { TestAsync().Wait(); } } }"; var expectedOutput = @"Before 12 After 12"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: expectedOutput); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe), expectedOutput: expectedOutput); } [Fact, WorkItem(2567, "https://github.com/dotnet/roslyn/issues/2567")] public void AwaitInUsingAndForeach() { var source = @" using System.Threading.Tasks; using System; class Program { System.Collections.Generic.IEnumerable<int> ien = null; async Task<int> Test(IDisposable id, Task<int> task) { try { foreach (var i in ien) { return await task; } using (id) { return await task; } } catch (Exception) { return await task; } } public static void Main() {} }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe)); } [Fact, WorkItem(4697, "https://github.com/dotnet/roslyn/issues/4697")] public void AwaitInObjInitializer() { var source = @" using System; using System.Threading.Tasks; namespace CompilerCrashRepro2 { public class Item<T> { public T Value { get; set; } } public class Crasher { public static void Main() { var r = Build<int>()().Result.Value; System.Console.WriteLine(r); } public static Func<Task<Item<T>>> Build<T>() { return async () => new Item<T>() { Value = await GetValue<T>() }; } public static Task<T> GetValue<T>() { return Task.FromResult(default(T)); } } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "0"); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe), expectedOutput: "0"); } [Fact] public void AwaitInScriptExpression() { var source = @"System.Console.WriteLine(await System.Threading.Tasks.Task.FromResult(1));"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); } [Fact] public void AwaitInScriptGlobalStatement() { var source = @"await System.Threading.Tasks.Task.FromResult(4);"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); } [Fact] public void AwaitInScriptDeclaration() { var source = @"int x = await System.Threading.Tasks.Task.Run(() => 2); System.Console.WriteLine(x);"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); } [Fact] public void AwaitInInteractiveExpression() { var references = new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef }; var source0 = @"static async System.Threading.Tasks.Task<int> F() { return await System.Threading.Tasks.Task.FromResult(3); }"; var source1 = @"await F()"; var s0 = CSharpCompilation.CreateScriptCompilation("s0.dll", SyntaxFactory.ParseSyntaxTree(source0, options: TestOptions.Script), references); var s1 = CSharpCompilation.CreateScriptCompilation("s1.dll", SyntaxFactory.ParseSyntaxTree(source1, options: TestOptions.Script), references, previousScriptCompilation: s0); s1.VerifyDiagnostics(); } [Fact] public void AwaitInInteractiveGlobalStatement() { var references = new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef }; var source0 = @"await System.Threading.Tasks.Task.FromResult(5);"; var s0 = CSharpCompilation.CreateScriptCompilation("s0.dll", SyntaxFactory.ParseSyntaxTree(source0, options: TestOptions.Script), references); s0.VerifyDiagnostics(); } /// <summary> /// await should be disallowed in static field initializer /// since the static initialization of the class must be /// handled synchronously in the .cctor. /// </summary> [WorkItem(5787, "https://github.com/dotnet/roslyn/issues/5787")] [Fact] public void AwaitInScriptStaticInitializer() { var source = @"static int x = 1 + await System.Threading.Tasks.Task.FromResult(1); int y = x + await System.Threading.Tasks.Task.FromResult(2);"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (2,5): error CS8100: The 'await' operator cannot be used in a static script variable initializer. // await System.Threading.Tasks.Task.FromResult(1); Diagnostic(ErrorCode.ERR_BadAwaitInStaticVariableInitializer, "await System.Threading.Tasks.Task.FromResult(1)").WithLocation(2, 5)); } [Fact, WorkItem(4839, "https://github.com/dotnet/roslyn/issues/4839")] public void SwitchOnAwaitedValueAsync() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main() { M(0).Wait(); } static async Task M(int input) { var value = 1; switch (value) { case 0: return; case 1: return; } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe)); } [Fact, WorkItem(4839, "https://github.com/dotnet/roslyn/issues/4839")] public void SwitchOnAwaitedValue() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main() { M(0); } static void M(int input) { try { var value = 1; switch (value) { case 1: return; case 2: return; } } catch (Exception) { } } } "; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp). VerifyIL("Program.M(int)", @" { // Code size 16 (0x10) .maxstack 2 .locals init (int V_0) //value .try { IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: beq.s IL_000a IL_0006: ldloc.0 IL_0007: ldc.i4.2 IL_0008: pop IL_0009: pop IL_000a: leave.s IL_000f } catch System.Exception { IL_000c: pop IL_000d: leave.s IL_000f } IL_000f: ret }"); } [Fact, WorkItem(4839, "https://github.com/dotnet/roslyn/issues/4839")] public void SwitchOnAwaitedValueString() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main() { M(0).Wait(); } static async Task M(int input) { var value = ""q""; switch (value) { case ""a"": return; case ""b"": return; } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe)); } [Fact, WorkItem(4838, "https://github.com/dotnet/roslyn/issues/4838")] public void SwitchOnAwaitedValueInLoop() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main() { M(0).Wait(); } static async Task M(int input) { for (;;) { var value = await Task.FromResult(input); switch (value) { case 0: return; case 3: return; case 4: continue; case 100: return; default: throw new ArgumentOutOfRangeException(""Unknown value: "" + value); } } } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(comp); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe)); } [Fact, WorkItem(7669, "https://github.com/dotnet/roslyn/issues/7669")] public void HoistUsing001() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main() { System.Console.WriteLine(M(0).Result); } class D : IDisposable { public void Dispose() { Console.WriteLine(""disposed""); } } static async Task<string> M(int input) { Console.WriteLine(""Pre""); var window = new D(); try { Console.WriteLine(""show""); for (int i = 0; i < 2; i++) { await Task.Delay(100); } } finally { window.Dispose(); } Console.WriteLine(""Post""); return ""result""; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); var expectedOutput = @"Pre show disposed Post result"; CompileAndVerify(comp, expectedOutput: expectedOutput); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe), expectedOutput: expectedOutput); } [Fact, WorkItem(7669, "https://github.com/dotnet/roslyn/issues/7669")] public void HoistUsing002() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main() { System.Console.WriteLine(M(0).Result); } class D : IDisposable { public void Dispose() { Console.WriteLine(""disposed""); } } static async Task<string> M(int input) { Console.WriteLine(""Pre""); using (var window = new D()) { Console.WriteLine(""show""); for (int i = 0; i < 2; i++) { await Task.Delay(100); } } Console.WriteLine(""Post""); return ""result""; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); var expectedOutput = @"Pre show disposed Post result"; CompileAndVerify(comp, expectedOutput: expectedOutput); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe), expectedOutput: expectedOutput); } [Fact, WorkItem(7669, "https://github.com/dotnet/roslyn/issues/7669")] public void HoistUsing003() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main() { System.Console.WriteLine(M(0).Result); } class D : IDisposable { public void Dispose() { Console.WriteLine(""disposed""); } } static async Task<string> M(int input) { Console.WriteLine(""Pre""); using (var window1 = new D()) { Console.WriteLine(""show""); using (var window = new D()) { Console.WriteLine(""show""); for (int i = 0; i < 2; i++) { await Task.Delay(100); } } } Console.WriteLine(""Post""); return ""result""; } } "; var comp = CreateCompilation(source, options: TestOptions.DebugExe); var expectedOutput = @"Pre show show disposed disposed Post result"; CompileAndVerify(comp, expectedOutput: expectedOutput); CompileAndVerify(comp.WithOptions(TestOptions.ReleaseExe), expectedOutput: expectedOutput); } [Fact, WorkItem(9463, "https://github.com/dotnet/roslyn/issues/9463")] public void AsyncIteratorReportsDiagnosticsWhenCoreTypesAreMissing() { // Note that IAsyncStateMachine.MoveNext and IAsyncStateMachine.SetStateMachine are missing var source = @" using System.Threading.Tasks; namespace System { public class Object { } public struct Int32 { } public struct Boolean { } public class String { } public class Exception { } public class ValueType { } public class Enum { } public struct Void { } } namespace System.Threading.Tasks { public class Task { public TaskAwaiter GetAwaiter() { return null; } } public class TaskAwaiter : System.Runtime.CompilerServices.INotifyCompletion { public bool IsCompleted { get { return true; } } public void GetResult() { } } } namespace System.Runtime.CompilerServices { public interface INotifyCompletion { } public interface ICriticalNotifyCompletion { } public interface IAsyncStateMachine { } public class AsyncTaskMethodBuilder { public System.Threading.Tasks.Task Task { get { return null; } } public void SetException(System.Exception e) { } public void SetResult() { } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } } } class C { async Task GetNumber(Task task) { await task; } }"; var compilation = CreateEmptyCompilation(new[] { Parse(source) }); compilation.VerifyEmitDiagnostics( // warning CS8021: No value for RuntimeMetadataVersion found. No assembly containing System.Object was found nor was a value for RuntimeMetadataVersion specified through options. Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion).WithLocation(1, 1), // (62,37): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Create' // async Task GetNumber(Task task) { await task; } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await task; }").WithArguments("System.Runtime.CompilerServices.AsyncTaskMethodBuilder", "Create").WithLocation(62, 37), // (62,37): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext' // async Task GetNumber(Task task) { await task; } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await task; }").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "MoveNext").WithLocation(62, 37), // (62,37): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.IAsyncStateMachine.SetStateMachine' // async Task GetNumber(Task task) { await task; } Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "{ await task; }").WithArguments("System.Runtime.CompilerServices.IAsyncStateMachine", "SetStateMachine").WithLocation(62, 37)); } [Fact, WorkItem(16531, "https://github.com/dotnet/roslyn/issues/16531")] public void ArityMismatch() { var source = @" using System; using System.Threading.Tasks; using System.Runtime.CompilerServices; public class Program { public async MyAwesomeType<string> CustomTask() { await Task.Delay(1000); return string.Empty; } } [AsyncMethodBuilder(typeof(CustomAsyncTaskMethodBuilder<,>))] public struct MyAwesomeType<T> { public T Result { get; set; } } public class CustomAsyncTaskMethodBuilder<T, V> { public MyAwesomeType<T> Task => default(MyAwesomeType<T>); public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } public static CustomAsyncTaskMethodBuilder<T, V> Create() { return default(CustomAsyncTaskMethodBuilder<T, V>); } public void SetException(Exception exception) { } public void SetResult(T t) { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } } namespace System.Runtime.CompilerServices { public class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(Type type) { } } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugDll); compilation.VerifyEmitDiagnostics( // (8,53): error CS8940: A generic task-like return type was expected, but the type 'CustomAsyncTaskMethodBuilder<,>' found in 'AsyncMethodBuilder' attribute was not suitable. It must be an unbound generic type of arity one, and its containing type (if any) must be non-generic. // public async MyAwesomeType<string> CustomTask() { await Task.Delay(1000); return string.Empty; } Diagnostic(ErrorCode.ERR_WrongArityAsyncReturn, "{ await Task.Delay(1000); return string.Empty; }").WithArguments("CustomAsyncTaskMethodBuilder<,>").WithLocation(8, 53) ); } [Fact, WorkItem(16493, "https://github.com/dotnet/roslyn/issues/16493")] public void AsyncMethodBuilderReturnsDifferentTypeThanTasklikeType() { var source = @" using System; using System.Threading.Tasks; using System.Runtime.CompilerServices; public class G<T> { public async ValueTask Method() { await Task.Delay(5); return; } [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder))] public struct ValueTask { } } public class AsyncValueTaskMethodBuilder { public G<int>.ValueTask Task { get => default(G<int>.ValueTask); } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } public static AsyncValueTaskMethodBuilder Create() { return default(AsyncValueTaskMethodBuilder); } public void SetException(Exception exception) { } public void SetResult() { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } } namespace System.Runtime.CompilerServices { public class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(Type type) { } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugDll); compilation.VerifyEmitDiagnostics( // (8,37): error CS8204: For type 'AsyncValueTaskMethodBuilder' to be used as an AsyncMethodBuilder for type 'G<T>.ValueTask', its Task property should return type 'G<T>.ValueTask' instead of type 'G<int>.ValueTask'. // public async ValueTask Method() { await Task.Delay(5); return; } Diagnostic(ErrorCode.ERR_BadAsyncMethodBuilderTaskProperty, "{ await Task.Delay(5); return; }").WithArguments("AsyncValueTaskMethodBuilder", "G<T>.ValueTask", "G<int>.ValueTask").WithLocation(8, 37) ); } [Fact, WorkItem(16493, "https://github.com/dotnet/roslyn/issues/16493")] public void AsyncMethodBuilderReturnsDifferentTypeThanTasklikeType2() { var source = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { static async MyTask M() { await Task.Delay(5); throw null; } } [AsyncMethodBuilder(typeof(MyTaskBuilder))] class MyTask { } class MyTaskBuilder { public static MyTaskBuilder Create() => null; public int Task => 0; public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void SetResult() { } public void SetException(Exception exception) { } public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugDll); compilation.VerifyEmitDiagnostics( // (7,29): error CS8204: For type 'MyTaskBuilder' to be used as an AsyncMethodBuilder for type 'MyTask', its Task property should return type 'MyTask' instead of type 'int'. // static async MyTask M() { await Task.Delay(5); throw null; } Diagnostic(ErrorCode.ERR_BadAsyncMethodBuilderTaskProperty, "{ await Task.Delay(5); throw null; }").WithArguments("MyTaskBuilder", "MyTask", "int").WithLocation(7, 29) ); } [Fact, WorkItem(18257, "https://github.com/dotnet/roslyn/issues/18257")] public void PatternTempsAreLongLived() { var source = @"using System; public class Goo {} public class C { public static void Main(string[] args) { var c = new C(); c.M(new Goo()); c.M(new object()); } public async void M(object o) { switch (o) { case Goo _: Console.Write(0); break; default: Console.Write(1); break; } } }"; var expectedOutput = @"01"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); base.CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(18257, "https://github.com/dotnet/roslyn/issues/18257")] public void PatternTempsSpill() { // This test exercises the spilling machinery of async for pattern-matching temps var source = @"using System; using System.Threading.Tasks; public class C { public class Goo { public int Value; } public static void Main(string[] args) { var c = new C(); c.M(new Goo() { Value = 1 }); c.M(new Goo() { Value = 2 }); c.M(new Goo() { Value = 3 }); c.M(new object()); } public void M(object o) { MAsync(o).Wait(); } public async Task MAsync(object o) { switch (o) { case Goo goo when await Copy(goo.Value) == 1: Console.Write($""{goo.Value}=1 ""); break; case Goo goo when await Copy(goo.Value) == 2: Console.Write($""{goo.Value}=2 ""); break; case Goo goo: Console.Write($""{goo.Value} ""); break; default: Console.Write(""X ""); break; } } public async Task<int> Copy(int i) { await Task.Delay(1); return i; } }"; var expectedOutput = @"1=1 2=2 3 X"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); base.CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(19831, "https://github.com/dotnet/roslyn/issues/19831")] public void CaptureAssignedInOuterFinally() { var source = @" using System; using System.Threading.Tasks; public class Program { static void Main(string[] args) { Test().Wait(); System.Console.WriteLine(""success""); } public static async Task Test() { // declaring variable before try/finally and nulling it in finally cause NRE in try's body var obj = new Object(); try { for(int i = 0; i < 3; i++) { // NRE on second iteration obj.ToString(); await Task.Yield(); } } finally { obj = null; } } } "; var expectedOutput = @"success"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); base.CompileAndVerify(compilation, expectedOutput: expectedOutput); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); base.CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(24806, "https://github.com/dotnet/roslyn/issues/24806")] public void CaptureStructReceiver() { var source = @" using System; using System.Threading.Tasks; public class Program { static void Main(string[] args) { System.Console.WriteLine(Test1().Result); } static int x = 123; async static Task<string> Test1() { // cannot capture 'x' by value, since write in M1 is observable return x.ToString(await M1()); } async static Task<string> M1() { x = 42; await Task.Yield(); return """"; } } "; var expectedOutput = @"42"; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); base.CompileAndVerify(compilation, expectedOutput: expectedOutput); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); base.CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(13759, "https://github.com/dotnet/roslyn/issues/13759")] public void Unnecessary_Lifted_01() { var source = @" using System.IO; using System.Threading.Tasks; namespace Test { class Program { public static void Main() { } public static async Task M(Stream source, Stream destination) { byte[] buffer = new byte[0x1000]; int bytesRead; // this variable should not be lifted while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length)) != 0) { await destination.WriteAsync(buffer, 0, bytesRead); } } } } "; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp). VerifyIL("Test.Program.<M>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 315 (0x13b) .maxstack 4 .locals init (int V_0, int V_1, //bytesRead System.Runtime.CompilerServices.TaskAwaiter V_2, System.Runtime.CompilerServices.TaskAwaiter<int> V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.Program.<M>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0068 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: beq IL_00d4 IL_0011: ldarg.0 IL_0012: ldc.i4 0x1000 IL_0017: newarr ""byte"" IL_001c: stfld ""byte[] Test.Program.<M>d__1.<buffer>5__2"" IL_0021: br.s IL_008b IL_0023: ldarg.0 IL_0024: ldfld ""System.IO.Stream Test.Program.<M>d__1.destination"" IL_0029: ldarg.0 IL_002a: ldfld ""byte[] Test.Program.<M>d__1.<buffer>5__2"" IL_002f: ldc.i4.0 IL_0030: ldloc.1 IL_0031: callvirt ""System.Threading.Tasks.Task System.IO.Stream.WriteAsync(byte[], int, int)"" IL_0036: callvirt ""System.Runtime.CompilerServices.TaskAwaiter System.Threading.Tasks.Task.GetAwaiter()"" IL_003b: stloc.2 IL_003c: ldloca.s V_2 IL_003e: call ""bool System.Runtime.CompilerServices.TaskAwaiter.IsCompleted.get"" IL_0043: brtrue.s IL_0084 IL_0045: ldarg.0 IL_0046: ldc.i4.0 IL_0047: dup IL_0048: stloc.0 IL_0049: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_004e: ldarg.0 IL_004f: ldloc.2 IL_0050: stfld ""System.Runtime.CompilerServices.TaskAwaiter Test.Program.<M>d__1.<>u__1"" IL_0055: ldarg.0 IL_0056: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.Program.<M>d__1.<>t__builder"" IL_005b: ldloca.s V_2 IL_005d: ldarg.0 IL_005e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter, Test.Program.<M>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter, ref Test.Program.<M>d__1)"" IL_0063: leave IL_013a IL_0068: ldarg.0 IL_0069: ldfld ""System.Runtime.CompilerServices.TaskAwaiter Test.Program.<M>d__1.<>u__1"" IL_006e: stloc.2 IL_006f: ldarg.0 IL_0070: ldflda ""System.Runtime.CompilerServices.TaskAwaiter Test.Program.<M>d__1.<>u__1"" IL_0075: initobj ""System.Runtime.CompilerServices.TaskAwaiter"" IL_007b: ldarg.0 IL_007c: ldc.i4.m1 IL_007d: dup IL_007e: stloc.0 IL_007f: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_0084: ldloca.s V_2 IL_0086: call ""void System.Runtime.CompilerServices.TaskAwaiter.GetResult()"" IL_008b: ldarg.0 IL_008c: ldfld ""System.IO.Stream Test.Program.<M>d__1.source"" IL_0091: ldarg.0 IL_0092: ldfld ""byte[] Test.Program.<M>d__1.<buffer>5__2"" IL_0097: ldc.i4.0 IL_0098: ldarg.0 IL_0099: ldfld ""byte[] Test.Program.<M>d__1.<buffer>5__2"" IL_009e: ldlen IL_009f: conv.i4 IL_00a0: callvirt ""System.Threading.Tasks.Task<int> System.IO.Stream.ReadAsync(byte[], int, int)"" IL_00a5: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_00aa: stloc.3 IL_00ab: ldloca.s V_3 IL_00ad: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_00b2: brtrue.s IL_00f0 IL_00b4: ldarg.0 IL_00b5: ldc.i4.1 IL_00b6: dup IL_00b7: stloc.0 IL_00b8: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_00bd: ldarg.0 IL_00be: ldloc.3 IL_00bf: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.Program.<M>d__1.<>u__2"" IL_00c4: ldarg.0 IL_00c5: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.Program.<M>d__1.<>t__builder"" IL_00ca: ldloca.s V_3 IL_00cc: ldarg.0 IL_00cd: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, Test.Program.<M>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref Test.Program.<M>d__1)"" IL_00d2: leave.s IL_013a IL_00d4: ldarg.0 IL_00d5: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.Program.<M>d__1.<>u__2"" IL_00da: stloc.3 IL_00db: ldarg.0 IL_00dc: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> Test.Program.<M>d__1.<>u__2"" IL_00e1: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00e7: ldarg.0 IL_00e8: ldc.i4.m1 IL_00e9: dup IL_00ea: stloc.0 IL_00eb: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_00f0: ldloca.s V_3 IL_00f2: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00f7: dup IL_00f8: stloc.1 IL_00f9: brtrue IL_0023 IL_00fe: leave.s IL_0120 } catch System.Exception { IL_0100: stloc.s V_4 IL_0102: ldarg.0 IL_0103: ldc.i4.s -2 IL_0105: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_010a: ldarg.0 IL_010b: ldnull IL_010c: stfld ""byte[] Test.Program.<M>d__1.<buffer>5__2"" IL_0111: ldarg.0 IL_0112: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.Program.<M>d__1.<>t__builder"" IL_0117: ldloc.s V_4 IL_0119: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_011e: leave.s IL_013a } IL_0120: ldarg.0 IL_0121: ldc.i4.s -2 IL_0123: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_0128: ldarg.0 IL_0129: ldnull IL_012a: stfld ""byte[] Test.Program.<M>d__1.<buffer>5__2"" IL_012f: ldarg.0 IL_0130: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.Program.<M>d__1.<>t__builder"" IL_0135: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_013a: ret }"); } [Fact, WorkItem(13759, "https://github.com/dotnet/roslyn/issues/13759")] public void Unnecessary_Lifted_02() { var source = @" using System.IO; using System.Threading.Tasks; namespace Test { class Program { public static void Main() { } public static async Task M(Stream source, Stream destination) { bool someCondition = true; bool notLiftedVariable; while (someCondition && (notLiftedVariable = await M1())) { M2(notLiftedVariable); } } private static async Task<bool> M1() { await System.Threading.Tasks.Task.Delay(1); return true; } private static void M2(bool b) { } } } "; var comp = CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp). VerifyIL("Test.Program.<M>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 175 (0xaf) .maxstack 3 .locals init (int V_0, bool V_1, //notLiftedVariable bool V_2, System.Runtime.CompilerServices.TaskAwaiter<bool> V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int Test.Program.<M>d__1.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0057 IL_000a: ldarg.0 IL_000b: ldc.i4.1 IL_000c: stfld ""bool Test.Program.<M>d__1.<someCondition>5__2"" IL_0011: br.s IL_0019 IL_0013: ldloc.1 IL_0014: call ""void Test.Program.M2(bool)"" IL_0019: ldarg.0 IL_001a: ldfld ""bool Test.Program.<M>d__1.<someCondition>5__2"" IL_001f: stloc.2 IL_0020: ldloc.2 IL_0021: brfalse.s IL_007d IL_0023: call ""System.Threading.Tasks.Task<bool> Test.Program.M1()"" IL_0028: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<bool> System.Threading.Tasks.Task<bool>.GetAwaiter()"" IL_002d: stloc.3 IL_002e: ldloca.s V_3 IL_0030: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.IsCompleted.get"" IL_0035: brtrue.s IL_0073 IL_0037: ldarg.0 IL_0038: ldc.i4.0 IL_0039: dup IL_003a: stloc.0 IL_003b: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_0040: ldarg.0 IL_0041: ldloc.3 IL_0042: stfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> Test.Program.<M>d__1.<>u__1"" IL_0047: ldarg.0 IL_0048: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.Program.<M>d__1.<>t__builder"" IL_004d: ldloca.s V_3 IL_004f: ldarg.0 IL_0050: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<bool>, Test.Program.<M>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<bool>, ref Test.Program.<M>d__1)"" IL_0055: leave.s IL_00ae IL_0057: ldarg.0 IL_0058: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<bool> Test.Program.<M>d__1.<>u__1"" IL_005d: stloc.3 IL_005e: ldarg.0 IL_005f: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<bool> Test.Program.<M>d__1.<>u__1"" IL_0064: initobj ""System.Runtime.CompilerServices.TaskAwaiter<bool>"" IL_006a: ldarg.0 IL_006b: ldc.i4.m1 IL_006c: dup IL_006d: stloc.0 IL_006e: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_0073: ldloca.s V_3 IL_0075: call ""bool System.Runtime.CompilerServices.TaskAwaiter<bool>.GetResult()"" IL_007a: dup IL_007b: stloc.1 IL_007c: stloc.2 IL_007d: ldloc.2 IL_007e: brtrue.s IL_0013 IL_0080: leave.s IL_009b } catch System.Exception { IL_0082: stloc.s V_4 IL_0084: ldarg.0 IL_0085: ldc.i4.s -2 IL_0087: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_008c: ldarg.0 IL_008d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.Program.<M>d__1.<>t__builder"" IL_0092: ldloc.s V_4 IL_0094: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0099: leave.s IL_00ae } IL_009b: ldarg.0 IL_009c: ldc.i4.s -2 IL_009e: stfld ""int Test.Program.<M>d__1.<>1__state"" IL_00a3: ldarg.0 IL_00a4: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder Test.Program.<M>d__1.<>t__builder"" IL_00a9: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00ae: ret }"); } [Fact, WorkItem(25991, "https://github.com/dotnet/roslyn/issues/25991")] public void CompilerCrash01() { var source = @"namespace Issue25991 { using System; using System.Threading.Tasks; public class CrashClass { public static void Main() { Console.WriteLine(""Passed""); } public async Task CompletedTask() { } public async Task OnCrash() { var switchObject = new object(); switch (switchObject) { case InvalidCastException _: switch (switchObject) { case NullReferenceException exception: await CompletedTask(); var myexception = exception; break; } break; case InvalidOperationException _: switch (switchObject) { case NullReferenceException exception: await CompletedTask(); var myexception = exception; break; } break; } } } } "; var expected = @"Passed"; CompileAndVerify(source, expectedOutput: expected); } [Fact, WorkItem(25991, "https://github.com/dotnet/roslyn/issues/25991")] public void CompilerCrash02() { var source = @"namespace Issue25991 { using System; using System.Threading.Tasks; public class CrashClass { public static void Main() { Console.WriteLine(""Passed""); } public async Task CompletedTask() { } public async Task OnCrash() { var switchObject = new object(); switch (switchObject) { case InvalidCastException x1: switch (switchObject) { case NullReferenceException exception: await CompletedTask(); var myexception1 = x1; var myexception = exception; break; } break; case InvalidOperationException x1: switch (switchObject) { case NullReferenceException exception: await CompletedTask(); var myexception1 = x1; var myexception = exception; var x2 = switchObject; break; } break; } } } } "; var expected = @"Passed"; CompileAndVerify(source, expectedOutput: expected); } [Fact, WorkItem(19905, "https://github.com/dotnet/roslyn/issues/19905")] public void FinallyEnteredFromExceptionalControlFlow() { var source = @" using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; class TestCase { public async Task Run() { try { var tmp = await (new { task = Task.Run<string>(async () => { await Task.Delay(1); return """"; }) }).task; throw new Exception(tmp); } finally { Console.Write(0); } } } class Driver { static void Main() { var t = new TestCase(); try { t.Run().Wait(); } catch (Exception) { Console.Write(1); } } }"; var expectedOutput = @"01"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); base.CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(38543, "https://github.com/dotnet/roslyn/issues/38543")] public void AsyncLambdaWithAwaitedTasksInTernary() { var source = @" using System; using System.Threading.Tasks; class Program { static Task M(bool b) => M2(async () => b ? await Task.Delay(1) : await Task.Delay(2)); static T M2<T>(Func<T> f) => f(); }"; // The diagnostic message isn't great, but it is correct that we report an error var c = CreateCompilation(source, options: TestOptions.DebugDll); c.VerifyDiagnostics( // (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // b ? await Task.Delay(1) : await Task.Delay(2)); Diagnostic(ErrorCode.ERR_IllegalStatement, "b ? await Task.Delay(1) : await Task.Delay(2)").WithLocation(8, 9) ); } [Fact] [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] public void GetAwaiterBoxingConversion_01() { var source = @"using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; interface IAwaitable { } struct StructAwaitable : IAwaitable { } static class Extensions { public static TaskAwaiter GetAwaiter(this IAwaitable x) { if (x == null) throw new ArgumentNullException(nameof(x)); Console.Write(x); return Task.CompletedTask.GetAwaiter(); } } class Program { static async Task Main() { await new StructAwaitable(); } }"; var comp = CSharpTestBase.CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "StructAwaitable"); } [Fact] [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] public void GetAwaiterBoxingConversion_02() { var source = @"using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; struct StructAwaitable { } static class Extensions { public static TaskAwaiter GetAwaiter(this object x) { if (x == null) throw new ArgumentNullException(nameof(x)); Console.Write(x); return Task.CompletedTask.GetAwaiter(); } } class Program { static async Task Main() { StructAwaitable? s = new StructAwaitable(); await s; } }"; var comp = CSharpTestBase.CreateCompilation(source, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "StructAwaitable"); } [Fact, WorkItem(40251, "https://github.com/dotnet/roslyn/issues/40251")] public void AssignRefAfterAwait() { const string source = @" using System.Threading.Tasks; using System; class IntCode { public static async Task Main() { await Step(0); } public static async Task CompletedTask() { } public static async Task Step(int i) { Console.Write(field); await CompletedTask(); ReadMemory() = i switch { _ => GetValue() }; Console.Write(field); } public static long GetValue() { Console.Write(2); return 3L; } private static long field; private static ref long ReadMemory() { Console.Write(1); return ref field; } } "; var diags = new[] { // (12,30): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread. // public static async Task CompletedTask() Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "CompletedTask").WithLocation(12, 30) }; CompileAndVerify(source, options: TestOptions.DebugExe, verify: Verification.Skipped, expectedOutput: "0123").VerifyDiagnostics(diags); CompileAndVerify(source, options: TestOptions.ReleaseExe, verify: Verification.Skipped, expectedOutput: "0123").VerifyDiagnostics(diags); } [Fact, WorkItem(40251, "https://github.com/dotnet/roslyn/issues/40251")] public void AssignRefWithAwait() { const string source = @" using System.Threading.Tasks; class IntCode { public async Task Step(Task<int> t) { ReadMemory() = await t; ReadMemory() += await t; } private ref long ReadMemory() => throw null; } "; var expected = new[] { // (8,9): error CS8178: 'await' cannot be used in an expression containing a call to 'IntCode.ReadMemory()' because it returns by reference // ReadMemory() = await t; Diagnostic(ErrorCode.ERR_RefReturningCallAndAwait, "ReadMemory()").WithArguments("IntCode.ReadMemory()").WithLocation(8, 9), // (9,9): error CS8178: 'await' cannot be used in an expression containing a call to 'IntCode.ReadMemory()' because it returns by reference // ReadMemory() += await t; Diagnostic(ErrorCode.ERR_RefReturningCallAndAwait, "ReadMemory()").WithArguments("IntCode.ReadMemory()").WithLocation(9, 9) }; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyEmitDiagnostics(expected); comp = CreateCompilation(source, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics(expected); } [Fact] [WorkItem(30521, "https://github.com/dotnet/roslyn/issues/30521")] public void ComplexSwitchExpressionInvolvingNullCoalescingAndAwait() { var source = @"using System; using System.Threading.Tasks; public class C { public Task<int> Get() => Task.FromResult(1); public async Task M(int? val) { switch (val ?? await Get()) { case 1: default: throw new NotImplementedException(string.Empty); } } } "; var comp = CSharpTestBase.CreateCompilation(source, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("C.<M>d__1.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", source: source, expectedIL: @" { // Code size 176 (0xb0) .maxstack 3 .locals init (int V_0, C V_1, int? V_2, int V_3, System.Runtime.CompilerServices.TaskAwaiter<int> V_4, System.Exception V_5) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<M>d__1.<>1__state"" IL_0006: stloc.0 IL_0007: ldarg.0 IL_0008: ldfld ""C C.<M>d__1.<>4__this"" IL_000d: stloc.1 .try { IL_000e: ldloc.0 IL_000f: brfalse.s IL_0062 IL_0011: ldarg.0 IL_0012: ldfld ""int? C.<M>d__1.val"" IL_0017: stloc.2 IL_0018: ldloca.s V_2 IL_001a: call ""bool int?.HasValue.get"" IL_001f: brfalse.s IL_002b IL_0021: ldloca.s V_2 IL_0023: call ""int int?.GetValueOrDefault()"" IL_0028: stloc.3 IL_0029: br.s IL_0087 IL_002b: ldloc.1 IL_002c: call ""System.Threading.Tasks.Task<int> C.Get()"" IL_0031: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0036: stloc.s V_4 IL_0038: ldloca.s V_4 IL_003a: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_003f: brtrue.s IL_007f IL_0041: ldarg.0 IL_0042: ldc.i4.0 IL_0043: dup IL_0044: stloc.0 IL_0045: stfld ""int C.<M>d__1.<>1__state"" IL_004a: ldarg.0 IL_004b: ldloc.s V_4 IL_004d: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<M>d__1.<>u__1"" IL_0052: ldarg.0 IL_0053: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<M>d__1.<>t__builder"" IL_0058: ldloca.s V_4 IL_005a: ldarg.0 IL_005b: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, C.<M>d__1>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref C.<M>d__1)"" IL_0060: leave.s IL_00af IL_0062: ldarg.0 IL_0063: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<M>d__1.<>u__1"" IL_0068: stloc.s V_4 IL_006a: ldarg.0 IL_006b: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> C.<M>d__1.<>u__1"" IL_0070: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0076: ldarg.0 IL_0077: ldc.i4.m1 IL_0078: dup IL_0079: stloc.0 IL_007a: stfld ""int C.<M>d__1.<>1__state"" IL_007f: ldloca.s V_4 IL_0081: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0086: stloc.3 IL_0087: ldloc.3 IL_0088: ldc.i4.1 IL_0089: pop IL_008a: pop IL_008b: ldsfld ""string string.Empty"" IL_0090: newobj ""System.NotImplementedException..ctor(string)"" IL_0095: throw } catch System.Exception { IL_0096: stloc.s V_5 IL_0098: ldarg.0 IL_0099: ldc.i4.s -2 IL_009b: stfld ""int C.<M>d__1.<>1__state"" IL_00a0: ldarg.0 IL_00a1: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder C.<M>d__1.<>t__builder"" IL_00a6: ldloc.s V_5 IL_00a8: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00ad: leave.s IL_00af } IL_00af: ret } "); } [Fact, WorkItem(46843, "https://github.com/dotnet/roslyn/issues/46843")] public void LockInAsyncMethodWithAwaitInFinally() { var source = @" using System.Threading.Tasks; public class C { public async Task M(object o) { lock(o) { } try { } finally { await Task.Yield(); } } } "; var comp = CSharpTestBase.CreateCompilation(source); comp.VerifyEmitDiagnostics(); } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/OverrideCompletionProviderTests.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.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public class OverrideCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(OverrideCompletionProvider); protected override OptionSet WithChangedOptions(OptionSet options) { return options .WithChangedOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement) .WithChangedOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement); } #region "CompletionItem tests" [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedVirtualPublicMethod() { await VerifyItemExistsAsync(@" public class a { public virtual void goo() { } } public class b : a { override $$ }", "goo()"); } [WorkItem(543799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543799")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedParameterDefaultValue1() { await VerifyItemExistsAsync(@"public class a { public virtual void goo(int x = 42) { } } public class b : a { override $$ }", "goo(int x = 42)", "void a.goo([int x = 42])"); } [WorkItem(543799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543799")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedParameterDefaultValue2() { await VerifyItemExistsAsync(@"public class a { public virtual void goo(int x, int y = 42) { } } public class b : a { override $$ }", "goo(int x, int y = 42)", "void a.goo(int x, [int y = 42])"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedAbstractPublicMethod() { await VerifyItemExistsAsync(@" public class a { public abstract void goo(); } public class b : a { override $$ }", "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotPrivateInheritedMethod() { await VerifyItemIsAbsentAsync(@" public class a { private virtual void goo() { } } public class b : a { override $$ }", "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MatchReturnType() { var markup = @" public class a { public virtual void goo() { } public virtual string bar() {return null;} } public class b : a { override void $$ }"; await VerifyItemIsAbsentAsync(markup, "bar()"); await VerifyItemExistsAsync(markup, "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InvalidReturnType() { var markup = @" public class a { public virtual void goo() { } public virtual string bar() {return null;} } public class b : a { override badtype $$ }"; await VerifyItemExistsAsync(markup, "goo()"); await VerifyItemExistsAsync(markup, "bar()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAlreadyImplementedMethods() { await VerifyItemIsAbsentAsync(@" public class a { protected virtual void goo() { } protected virtual string bar() {return null;} } public class b : a { protected override void goo() { } override $$ }", "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotSealed() { await VerifyItemIsAbsentAsync(@" public class a { protected sealed void goo() { } } public class b : a { public override $$ }", "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowEvent() { await VerifyItemExistsAsync(@" using System; public class a { public virtual event EventHandler goo; } public class b : a { public override $$ }", "goo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotIfTokensAfterPosition() { await VerifyNoItemsExistAsync(@" public class a { public virtual void goo() { } } public class b : a { public override $$ void }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotIfNameAfterPosition() { await VerifyNoItemsExistAsync(@" public class a { public virtual void goo() { } } public class b : a { public override void $$ bar }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotIfStatic() { await VerifyNoItemsExistAsync(@" public class a { public virtual void goo() { } } public class b : a { public static override $$ }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterSingleLineMethodDeclaration() { await VerifyNoItemsExistAsync(@" public class a { public virtual void goo() { } } public class b : a { void bar() { } override $$ }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SuggestProperty() { await VerifyItemExistsAsync(@" public class a { public virtual int goo { } } public class b : a { override $$ }", "goo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotSuggestSealed() { await VerifyItemIsAbsentAsync(@" public class a { public sealed int goo { } } public class b : a { override $$ }", "goo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GatherModifiers() { await VerifyItemExistsAsync(@" public class a { public abstract extern unsafe int goo { } } public class b : a { override $$ }", "goo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IgnorePartial() { await VerifyNoItemsExistAsync(@" public class a { public virtual partial goo() { } } public class b : a { override partial $$ }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IgnoreSealed() { await VerifyItemIsAbsentAsync(@" public class a { public virtual sealed int goo() { } } public class b : a { override $$ }", "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IgnoreIfTokenAfter() { await VerifyNoItemsExistAsync(@" public class a { public virtual int goo() { } } public class b : a { override $$ int }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SuggestAfterUnsafeAbstractExtern() { await VerifyItemExistsAsync(@" public class a { public virtual int goo() { } } public class b : a { unsafe abstract extern override $$ }", "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SuggestAfterSealed() { await VerifyItemExistsAsync(@" public class a { public virtual int goo() { } } public class b : a { sealed override $$ }", "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoAccessibility() { var markup = @" public class a { public virtual int goo() { } protected virtual int bar() { } } public class b : a { override $$ }"; await VerifyItemExistsAsync(markup, "goo()"); await VerifyItemExistsAsync(markup, "bar()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FilterAccessibility() { var markup = @" public class a { public virtual int goo() { } protected virtual int bar() { } internal virtual int far() { } private virtual int bor() { } } public class b : a { override internal $$ }"; await VerifyItemIsAbsentAsync(markup, "goo()"); await VerifyItemIsAbsentAsync(markup, "bar()"); await VerifyItemIsAbsentAsync(markup, "bor()"); await VerifyItemExistsAsync(markup, "far()"); await VerifyItemExistsAsync(@" public class a { public virtual int goo() { } protected virtual int bar() { } internal virtual int far() { } private virtual int bor() { } } public class b : a { override protected $$ }", "bar()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FilterPublicInternal() { var protectedinternal = @" public class a { protected internal virtual void goo() { } public virtual void bar() { } } public class b : a { protected internal override $$ }"; await VerifyItemIsAbsentAsync(protectedinternal, "bar()"); await VerifyItemExistsAsync(protectedinternal, "goo()"); var internalprotected = @" public class a { protected internal virtual void goo() { } public virtual void bar() { } } public class b : a { internal protected override $$ }"; await VerifyItemIsAbsentAsync(internalprotected, "bar()"); await VerifyItemExistsAsync(internalprotected, "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VerifySignatureFormat() { var markup = @" public class a { override $$ }"; await VerifyItemExistsAsync(markup, "Equals(object obj)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PrivateNoFilter() { var markup = @" public class c { public virtual void goo() { } } public class a : c { private override $$ }"; await VerifyNoItemsExistAsync(markup); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotOfferedOnFirstLine() { var markup = @"class c { override $$"; await VerifyNoItemsExistAsync(markup); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotOfferedOverrideAlone() { var markup = @"override $$"; await VerifyNoItemsExistAsync(markup); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IntermediateClassOverriddenMember() { var markup = @"abstract class Base { public abstract void Goo(); } class Derived : Base { public override void Goo() { } } class SomeClass : Derived { override $$ }"; await VerifyItemExistsAsync(markup, "Goo()", "void Derived.Goo()"); } [WorkItem(543748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543748")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotOfferedBaseClassMember() { var markup = @"abstract class Base { public abstract void Goo(); } class Derived : Base { public override void Goo() { } } class SomeClass : Derived { override $$ }"; await VerifyItemIsAbsentAsync(markup, "Goo()", "void Base.Goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotOfferedOnNonVirtual() { var markup = @"class Base { public void Goo(); } class SomeClass : Base { override $$ }"; await VerifyItemIsAbsentAsync(markup, "Goo()", "void Base.Goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GenericTypeNameSubstitutedForGenericInDerivedClass1() { var markup = @"public abstract class Base<T> { public abstract void Goo(T t); } public class SomeClass<X> : Base<X> { override $$ }"; await VerifyItemExistsAsync(markup, "Goo(X t)"); await VerifyItemIsAbsentAsync(markup, "Goo(T t)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GenericTypeNameSubstitutedForGenericInDerivedClass2() { var markup = @"public abstract class Base<T> { public abstract void Goo(T t); } public class SomeClass<X, Y, Z> : Base<Y> { override $$ }"; await VerifyItemExistsAsync(markup, "Goo(Y t)"); await VerifyItemIsAbsentAsync(markup, "Goo(T t)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GenericTypeNameSubstitutedForGenericInDerivedClass3() { var markup = @"public abstract class Base<T, S> { public abstract void Goo(T t, S s); } public class SomeClass<X, Y, Z> : Base<Y, Z> { override $$ }"; await VerifyItemExistsAsync(markup, "Goo(Y t, Z s)"); await VerifyItemIsAbsentAsync(markup, "Goo(T t, S s)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GenericTypeNameSubstitutedForNonGenericInDerivedClass1() { var markup = @"public abstract class Base<T> { public abstract void Goo(T t); } public class SomeClass : Base<int> { override $$ }"; await VerifyItemExistsAsync(markup, "Goo(int t)"); await VerifyItemIsAbsentAsync(markup, "Goo(T t)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GenericTypeNameSubstitutedForNonGenericInDerivedClass2() { var markup = @"public abstract class Base<T> { public abstract void Goo(T t); } public class SomeClass<X, Y, Z> : Base<int> { override $$ }"; await VerifyItemExistsAsync(markup, "Goo(int t)"); await VerifyItemIsAbsentAsync(markup, "Goo(T t)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GenericTypeNameSubstitutedForNonGenericInDerivedClass3() { var markup = @"using System; public abstract class Base<T, S> { public abstract void Goo(T t, S s); } public class SomeClass : Base<int, Exception> { override $$ }"; await VerifyItemExistsAsync(markup, "Goo(int t, Exception s)"); await VerifyItemIsAbsentAsync(markup, "Goo(T t, S s)"); } [WorkItem(543756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543756")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ParameterTypeSimplified() { var markup = @"using System; public abstract class Base { public abstract void Goo(System.Exception e); } public class SomeClass : Base { override $$ }"; await VerifyItemExistsAsync(markup, "Goo(Exception e)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NullableAnnotationsIncluded() { var markup = @"#nullable enable public abstract class Base { public abstract void Goo(string? s); } public class SomeClass : Base { override $$ }"; await VerifyItemExistsAsync(markup, "Goo(string? s)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EscapedMethodNameInIntelliSenseList() { var markup = @"public abstract class Base { public abstract void @class(); } public class SomeClass : Base { override $$ }"; MarkupTestFile.GetPosition(markup, out var code, out int position); await BaseVerifyWorkerAsync(code, position, "@class()", "void Base.@class()", SourceCodeKind.Regular, false, false, null, null, null, null, null, null); await BaseVerifyWorkerAsync(code, position, "@class()", "void Base.@class()", SourceCodeKind.Script, false, false, null, null, null, null, null, null); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EscapedPropertyNameInIntelliSenseList() { var markup = @"public abstract class Base { public virtual int @class { get; set; } } public class SomeClass : Base { override $$ }"; MarkupTestFile.GetPosition(markup, out var code, out int position); await BaseVerifyWorkerAsync(code, position, "@class", "int Base.@class { get; set; }", SourceCodeKind.Regular, false, false, null, null, null, null, null, null); await BaseVerifyWorkerAsync(code, position, "@class", "int Base.@class { get; set; }", SourceCodeKind.Script, false, false, null, null, null, null, null, null); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EscapedParameterNameInIntelliSenseList() { var markup = @"public abstract class Base { public abstract void goo(int @class); } public class SomeClass : Base { override $$ }"; await VerifyItemExistsAsync(markup, "goo(int @class)", "void Base.goo(int @class)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task RefParameter() { var markup = @"public abstract class Base { public abstract void goo(int x, ref string y); } public class SomeClass : Base { override $$ }"; await VerifyItemExistsAsync(markup, "goo(int x, ref string y)", "void Base.goo(int x, ref string y)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutParameter() { var markup = @"public abstract class Base { public abstract void goo(int x, out string y); } public class SomeClass : Base { override $$ }"; await VerifyItemExistsAsync(markup, "goo(int x, out string y)", "void Base.goo(int x, out string y)"); } [WorkItem(529714, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529714")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GenericMethodTypeParametersNotRenamed() { var markup = @"abstract class CGoo { public virtual X Something<X>(X arg) { return default(X); } } class Derived<X> : CGoo { override $$ }"; await VerifyItemExistsAsync(markup, "Something<X>(X arg)"); } #endregion #region "Commit tests" [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInEmptyClass() { var markupBeforeCommit = @"class c { override $$ }"; var expectedCodeAfterCommit = @"class c { public override bool Equals(object obj) { return base.Equals(obj);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Equals(object obj)", expectedCodeAfterCommit); } [WorkItem(529714, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529714")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitGenericMethodTypeParametersNotRenamed() { var markupBeforeCommit = @"abstract class CGoo { public virtual X Something<X>(X arg) { return default(X); } } class Derived<X> : CGoo { override $$ }"; var expectedCodeAfterCommit = @"abstract class CGoo { public virtual X Something<X>(X arg) { return default(X); } } class Derived<X> : CGoo { public override X Something<X>(X arg) { return base.Something(arg);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Something<X>(X arg)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitMethodBeforeMethod() { var markupBeforeCommit = @"class c { override $$ public void goo() { } }"; var expectedCodeAfterCommit = @"class c { public override bool Equals(object obj) { return base.Equals(obj);$$ } public void goo() { } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Equals(object obj)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitMethodAfterMethod() { var markupBeforeCommit = @"class c { public void goo() { } override $$ }"; var expectedCodeAfterCommit = @"class c { public void goo() { } public override bool Equals(object obj) { return base.Equals(obj);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Equals(object obj)", expectedCodeAfterCommit); } [WorkItem(543798, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543798")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitOptionalParameterValuesAreGenerated() { var markupBeforeCommit = @"using System; abstract public class Base { public abstract void goo(int x = 42); } public class Derived : Base { override $$ }"; var expectedCodeAfterCommit = @"using System; abstract public class Base { public abstract void goo(int x = 42); } public class Derived : Base { public override void goo(int x = 42) { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int x = 42)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAttributesAreNotGenerated() { var markupBeforeCommit = @"using System; public class Base { [Obsolete] public virtual void goo() { } } public class Derived : Base { override $$ }"; var expectedCodeAfterCommit = @"using System; public class Base { [Obsolete] public virtual void goo() { } } public class Derived : Base { public override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInaccessibleParameterAttributesAreNotGenerated() { var markupBeforeCommit = @"using System; public class Class1 { private class MyPrivate : Attribute { } public class MyPublic : Attribute { } public virtual void M([MyPrivate, MyPublic] int i) { } } public class Class2 : Class1 { public override void $$ }"; var expectedCodeAfterCommit = @"using System; public class Class1 { private class MyPrivate : Attribute { } public class MyPublic : Attribute { } public virtual void M([MyPrivate, MyPublic] int i) { } } public class Class2 : Class1 { public override void M([MyPublic] int i) { base.M(i);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "M(int i)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitVoidMethod() { var markupBeforeCommit = @"class c { public virtual void goo() { } } class d : c { override $$ }"; var expectedCodeAfterCommit = @"class c { public virtual void goo() { } } class d : c { public override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitVoidMethodWithParams() { var markupBeforeCommit = @"class c { public virtual void goo(int bar, int quux) { } } class d : c { override $$ }"; var expectedCodeAfterCommit = @"class c { public virtual void goo(int bar, int quux) { } } class d : c { public override void goo(int bar, int quux) { base.goo(bar, quux);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int bar, int quux)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitNonVoidMethod() { var markupBeforeCommit = @"class c { public virtual int goo() { } } class d : c { override $$ }"; var expectedCodeAfterCommit = @"class c { public virtual int goo() { } } class d : c { public override int goo() { return base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitNonVoidMethodWithParams() { var markupBeforeCommit = @"class c { public virtual int goo(int bar, int quux) { } } class d : c { override $$ }"; var expectedCodeAfterCommit = @"class c { public virtual int goo(int bar, int quux) { } } class d : c { public override int goo(int bar, int quux) { return base.goo(bar, quux);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int bar, int quux)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitProtectedMethod() { var markupBeforeCommit = @"class c { protected virtual void goo() { } } class d : c { override $$ }"; var expectedCodeAfterCommit = @"class c { protected virtual void goo() { } } class d : c { protected override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInternalMethod() { var markupBeforeCommit = @"class c { internal virtual void goo() { } } class d : c { override $$ }"; var expectedCodeAfterCommit = @"class c { internal virtual void goo() { } } class d : c { internal override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitProtectedInternalMethod() { var markupBeforeCommit = @"public class c { protected internal virtual void goo() { } } class d : c { override $$ }"; var expectedCodeAfterCommit = @"public class c { protected internal virtual void goo() { } } class d : c { protected internal override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAbstractMethodThrows() { var markupBeforeCommit = @"using System; abstract class c { public abstract void goo(); } class d : c { override $$ }"; var expectedCodeAfterCommit = @"using System; abstract class c { public abstract void goo(); } class d : c { public override void goo() { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitOverrideAsAbstract() { var markupBeforeCommit = @"class c { public virtual void goo() { }; } class d : c { abstract override $$ }"; var expectedCodeAfterCommit = @"class c { public virtual void goo() { }; } class d : c { public abstract override void goo();$$ }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitOverrideAsUnsafeSealed() { var markupBeforeCommit = @"class c { public virtual void goo() { }; } class d : c { unsafe sealed override $$ }"; var expectedCodeAfterCommit = @"class c { public virtual void goo() { }; } class d : c { public sealed override unsafe void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInsertProperty() { var markupBeforeCommit = @"public class c { public virtual int goo { get; set; } } public class d : c { override $$ }"; var expectedCodeAfterCommit = @"public class c { public virtual int goo { get; set; } } public class d : c { public override int goo { get { return base.goo;$$ } set { base.goo = value; } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInsertPropertyAfterMethod() { var markupBeforeCommit = @"public class c { public virtual int goo { get; set; } } public class d : c { public void a() { } override $$ }"; var expectedCodeAfterCommit = @"public class c { public virtual int goo { get; set; } } public class d : c { public void a() { } public override int goo { get { return base.goo;$$ } set { base.goo = value; } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInsertPropertyBeforeMethod() { var markupBeforeCommit = @"public class c { public virtual int goo { get; set; } } public class d : c { override $$ public void a() { } }"; var expectedCodeAfterCommit = @"public class c { public virtual int goo { get; set; } } public class d : c { public override int goo { get { return base.goo;$$ } set { base.goo = value; } } public void a() { } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitPropertyInaccessibleGet() { var markupBeforeCommit = @"public class c { public virtual int goo { private get; set; } } public class d : c { override $$ }"; var expectedCodeAfterCommit = @"public class c { public virtual int goo { private get; set; } } public class d : c { public override int goo { set { base.goo = value;$$ } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitPropertyInaccessibleSet() { var markupBeforeCommit = @"public class c { public virtual int goo { private set; get; } } public class d : c { override $$ }"; var expectedCodeAfterCommit = @"public class c { public virtual int goo { private set; get; } } public class d : c { public override int goo { get { return base.goo;$$ } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInsertPropertyInaccessibleParameterAttributesAreNotGenerated() { var markupBeforeCommit = @"using System; namespace ClassLibrary1 { public class Class1 { private class MyPrivate : Attribute { } public class MyPublic : Attribute { } public virtual int this[[MyPrivate, MyPublic]int i] { get { return 0; } set { } } } public class Class2 : Class1 { public override int $$ } }"; var expectedCodeAfterCommit = @"using System; namespace ClassLibrary1 { public class Class1 { private class MyPrivate : Attribute { } public class MyPublic : Attribute { } public virtual int this[[MyPrivate, MyPublic]int i] { get { return 0; } set { } } } public class Class2 : Class1 { public override int this[[MyPublic] int i] { get { return base[i];$$ } set { base[i] = value; } } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "this[int i]", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAccessibleEvent() { var markupBeforeCommit = @"using System; public class a { public virtual event EventHandler goo; } public class b : a { override $$ }"; var expectedCodeAfterCommit = @"using System; public class a { public virtual event EventHandler goo; } public class b : a { public override event EventHandler goo;$$ }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitEventAfterMethod() { var markupBeforeCommit = @"using System; public class a { public virtual event EventHandler goo; } public class b : a { void bar() { } override $$ }"; var expectedCodeAfterCommit = @"using System; public class a { public virtual event EventHandler goo; } public class b : a { void bar() { } public override event EventHandler goo;$$ }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitGenericMethod() { var markupBeforeCommit = @"using System; public class a { public virtual void goo<T>() { } } public class b : a { override $$ }"; var expectedCodeAfterCommit = @"using System; public class a { public virtual void goo<T>() { } } public class b : a { public override void goo<T>() { base.goo<T>();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo<T>()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitMethodWithNullableAttributes() { var markupBeforeCommit = @" #nullable enable class C { public virtual string? Goo(string? s) { } } class D : C { override $$ }"; var expectedCodeAfterCommit = @" #nullable enable class C { public virtual string? Goo(string? s) { } } class D : C { public override string? Goo(string? s) { return base.Goo(s);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo(string? s)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitMethodInNullableDisableContext() { var markupBeforeCommit = @" #nullable enable class C { public virtual string? Goo(string? s) { } } #nullable disable class D : C { override $$ }"; var expectedCodeAfterCommit = @" #nullable enable class C { public virtual string? Goo(string? s) { } } #nullable disable class D : C { public override string Goo(string s) { return base.Goo(s);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo(string? s)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitToStringIsExplicitlyNonNullReturning() { var markupBeforeCommit = @" #nullable enable namespace System { public class Object { public virtual string? ToString() { } } } class D : System.Object { override $$ }"; var expectedCodeAfterCommit = @" #nullable enable namespace System { public class Object { public virtual string? ToString() { } } } class D : System.Object { public override string ToString() { return base.ToString();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "ToString()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInsertIndexer() { var markupBeforeCommit = @"public class MyIndexer<T> { private T[] arr = new T[100]; public virtual T this[int i] { get { return arr[i]; } set { arr[i] = value; } } } class d : MyIndexer<T> { override $$ }"; var expectedCodeAfterCommit = @"public class MyIndexer<T> { private T[] arr = new T[100]; public virtual T this[int i] { get { return arr[i]; } set { arr[i] = value; } } } class d : MyIndexer<T> { public override T this[int i] { get { return base[i];$$ } set { base[i] = value; } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "this[int i]", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAbstractIndexer() { var markupBeforeCommit = @"public class MyIndexer<T> { private T[] arr = new T[100]; public abstract T this[int i] { get; set; } } class d : MyIndexer<T> { override $$ }"; var expectedCodeAfterCommit = @"public class MyIndexer<T> { private T[] arr = new T[100]; public abstract T this[int i] { get; set; } } class d : MyIndexer<T> { public override T this[int i] { get { throw new System.NotImplementedException();$$ } set { throw new System.NotImplementedException(); } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "this[int i]", expectedCodeAfterCommit); } // The following two scenarios are already verified through 'VerifyCommit', // which also tests everything at the end of the file (truncating input markup at $$) // public void CommitInsertAtEndOfFile() // public void CommitInsertAtEndOfFileAfterMethod() [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitFormats() { var markupBeforeCommit = @"class Base { public virtual void goo() { } } class Derived : Base { override $$ }"; var expectedCodeAfterCommit = @"class Base { public virtual void goo() { } } class Derived : Base { public override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitSimplifiesParameterTypes() { var markupBeforeCommit = @"using System; public abstract class Base { public abstract void goo(System.Exception e); } public class SomeClass : Base { override $$ }"; var expectedCodeAfterCommit = @"using System; public abstract class Base { public abstract void goo(System.Exception e); } public class SomeClass : Base { public override void goo(Exception e) { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(Exception e)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitSimplifiesReturnType() { var markupBeforeCommit = @"using System; public abstract class Base { public abstract System.ArgumentException goo(System.Exception e); } public class SomeClass : Base { override $$ }"; var expectedCodeAfterCommit = @"using System; public abstract class Base { public abstract System.ArgumentException goo(System.Exception e); } public class SomeClass : Base { public override ArgumentException goo(Exception e) { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(Exception e)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitEscapedMethodName() { var markupBeforeCommit = @"using System; public abstract class Base { public abstract void @class(); } public class SomeClass : Base { override $$ }"; var expectedCodeAfterCommit = @"using System; public abstract class Base { public abstract void @class(); } public class SomeClass : Base { public override void @class() { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "@class()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitEscapedPropertyName() { var markupBeforeCommit = @"public abstract class Base { public virtual int @class { get; set; } } public class SomeClass : Base { override $$ }"; var expectedCodeAfterCommit = @"public abstract class Base { public virtual int @class { get; set; } } public class SomeClass : Base { public override int @class { get { return base.@class;$$ } set { base.@class = value; } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "@class", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitEscapedParameterName() { var markupBeforeCommit = @"using System; public abstract class Base { public abstract void goo(int @class); } public class SomeClass : Base { override $$ }"; var expectedCodeAfterCommit = @"using System; public abstract class Base { public abstract void goo(int @class); } public class SomeClass : Base { public override void goo(int @class) { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int @class)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitRefParameter() { var markupBeforeCommit = @"using System; public abstract class Base { public abstract void goo(int x, ref string y); } public class SomeClass : Base { override $$ }"; var expectedCodeAfterCommit = @"using System; public abstract class Base { public abstract void goo(int x, ref string y); } public class SomeClass : Base { public override void goo(int x, ref string y) { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int x, ref string y)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitOutParameter() { var markupBeforeCommit = @"using System; public abstract class Base { public abstract void goo(int x, out string y); } public class SomeClass : Base { override $$ }"; var expectedCodeAfterCommit = @"using System; public abstract class Base { public abstract void goo(int x, out string y); } public class SomeClass : Base { public override void goo(int x, out string y) { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int x, out string y)", expectedCodeAfterCommit); } [WorkItem(544560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544560")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestUnsafe1() { var markupBeforeCommit = @"public class A { public unsafe virtual void F() { } } public class B : A { override $$ }"; var expectedCodeAfterCommit = @"public class A { public unsafe virtual void F() { } } public class B : A { public override void F() { base.F();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "F()", expectedCodeAfterCommit); } [WorkItem(544560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544560")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestUnsafe2() { var markupBeforeCommit = @"public class A { public unsafe virtual void F() { } } public class B : A { override unsafe $$ }"; var expectedCodeAfterCommit = @"public class A { public unsafe virtual void F() { } } public class B : A { public override unsafe void F() { base.F();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "F()", expectedCodeAfterCommit); } [WorkItem(544560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544560")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestUnsafe3() { var markupBeforeCommit = @"public class A { public unsafe virtual void F() { } } public class B : A { unsafe override $$ }"; var expectedCodeAfterCommit = @"public class A { public unsafe virtual void F() { } } public class B : A { public override unsafe void F() { base.F();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "F()", expectedCodeAfterCommit); } [WorkItem(544560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544560")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestUnsafe4() { var markupBeforeCommit = @"public class A { public virtual void F(int* i) { } } public class B : A { override $$ }"; var expectedCodeAfterCommit = @"public class A { public virtual void F(int* i) { } } public class B : A { public override unsafe void F(int* i) { base.F(i);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "F(int* i)", expectedCodeAfterCommit); } [WorkItem(545534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545534")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestPrivateVirtualProperty() { var markupBeforeCommit = @"public class B { public virtual int Goo { get; private set; } class C : B { override $$ } }"; var expectedCodeAfterCommit = @"public class B { public virtual int Goo { get; private set; } class C : B { public override int Goo { get { return base.Goo;$$ } } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo", expectedCodeAfterCommit); } [WorkItem(636706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636706")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CrossLanguageParameterizedPropertyOverride() { var vbFile = @"Public Class Goo Public Overridable Property Bar(bay As Integer) As Integer Get Return 23 End Get Set(value As Integer) End Set End Property End Class "; var csharpFile = @"class Program : Goo { override $$ } "; var csharpFileAfterCommit = @"class Program : Goo { public override int get_Bar(int bay) { return base.get_Bar(bay);$$ } public override void set_Bar(int bay, int value) { base.set_Bar(bay, value); } } "; var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <ProjectReference>VBProject</ProjectReference> <Document FilePath=""CSharpDocument"">{1}</Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""VBProject""> <Document FilePath=""VBDocument""> {3} </Document> </Project> </Workspace>", LanguageNames.CSharp, csharpFile, LanguageNames.VisualBasic, vbFile); using var testWorkspace = TestWorkspace.Create(xmlString, exportProvider: ExportProvider); var testDocument = testWorkspace.Documents.Single(d => d.Name == "CSharpDocument"); Contract.ThrowIfNull(testDocument.CursorPosition); var position = testDocument.CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var documentId = testWorkspace.Documents.Single(d => d.Name == "CSharpDocument").Id; var document = solution.GetRequiredDocument(documentId); var triggerInfo = CompletionTrigger.Invoke; var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, position, triggerInfo); var completionItem = completionList.Items.First(i => CompareItems(i.DisplayText, "Bar[int bay]")); if (service.GetProvider(completionItem) is ICustomCommitCompletionProvider customCommitCompletionProvider) { var textView = testWorkspace.GetTestDocument(documentId).GetTextView(); customCommitCompletionProvider.Commit(completionItem, textView, textView.TextBuffer, textView.TextSnapshot, '\t'); var actualCodeAfterCommit = textView.TextBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = textView.Caret.Position.BufferPosition.Position; MarkupTestFile.GetPosition(csharpFileAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); } } #endregion #region "Commit: With Trivia" [WorkItem(529199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529199")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitSurroundingTriviaDirective() { var markupBeforeCommit = @"class Base { public virtual void goo() { } } class Derived : Base { #if true override $$ #endif }"; var expectedCodeAfterCommit = @"class Base { public virtual void goo() { } } class Derived : Base { #if true public override void goo() { base.goo();$$ } #endif }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WorkItem(529199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529199")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitBeforeTriviaDirective() { var markupBeforeCommit = @"class Base { public virtual void goo() { } } class Derived : Base { override $$ #if true #endif }"; var expectedCodeAfterCommit = @"class Base { public virtual void goo() { } } class Derived : Base { public override void goo() { base.goo();$$ } #if true #endif }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAfterTriviaDirective() { var markupBeforeCommit = @"class Base { public virtual void goo() { } } class Derived : Base { #if true #endif override $$ }"; var expectedCodeAfterCommit = @"class Base { public virtual void goo() { } } class Derived : Base { #if true #endif public override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WorkItem(529199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529199")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitBeforeComment() { var markupBeforeCommit = @"class Base { public virtual void goo() { } } class Derived : Base { override $$ /* comment */ }"; var expectedCodeAfterCommit = @"class Base { public virtual void goo() { } } class Derived : Base { public override void goo() { base.goo();$$ } /* comment */ }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAfterComment() { var markupBeforeCommit = @"class Base { public virtual void goo() { } } class Derived : Base { /* comment */ override $$ }"; var expectedCodeAfterCommit = @"class Base { public virtual void goo() { } } class Derived : Base { /* comment */ public override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotFormatFile() { var markupBeforeCommit = @"class Program { int zip; public virtual void goo() { } } class C : Program { int bar; override $$ }"; var expectedCodeAfterCommit = @"class Program { int zip; public virtual void goo() { } } class C : Program { int bar; public override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WorkItem(736742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/736742")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AcrossPartialTypes1() { var file1 = @"partial class c { } "; var file2 = @"partial class c { override $$ } "; var csharpFileAfterCommit = @"partial class c { public override bool Equals(object obj) { return base.Equals(obj);$$ } } "; var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""CSharpDocument"">{1}</Document> <Document FilePath=""CSharpDocument2"">{2}</Document> </Project> </Workspace>", LanguageNames.CSharp, file1, file2); using var testWorkspace = TestWorkspace.Create(xmlString, exportProvider: ExportProvider); var testDocument = testWorkspace.Documents.Single(d => d.Name == "CSharpDocument2"); Contract.ThrowIfNull(testDocument.CursorPosition); var position = testDocument.CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var documentId = testWorkspace.Documents.Single(d => d.Name == "CSharpDocument2").Id; var document = solution.GetRequiredDocument(documentId); var triggerInfo = CompletionTrigger.Invoke; var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, position, triggerInfo); var completionItem = completionList.Items.First(i => CompareItems(i.DisplayText, "Equals(object obj)")); if (service.GetProvider(completionItem) is ICustomCommitCompletionProvider customCommitCompletionProvider) { var textView = testWorkspace.GetTestDocument(documentId).GetTextView(); customCommitCompletionProvider.Commit(completionItem, textView, textView.TextBuffer, textView.TextSnapshot, '\t'); var actualCodeAfterCommit = textView.TextBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = textView.Caret.Position.BufferPosition.Position; MarkupTestFile.GetPosition(csharpFileAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); } } [WorkItem(736742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/736742")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AcrossPartialTypes2() { var file1 = @"partial class c { } "; var file2 = @"partial class c { override $$ } "; var csharpFileAfterCommit = @"partial class c { public override bool Equals(object obj) { return base.Equals(obj);$$ } } "; var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""CSharpDocument"">{1}</Document> <Document FilePath=""CSharpDocument2"">{2}</Document> </Project> </Workspace>", LanguageNames.CSharp, file2, file1); using var testWorkspace = TestWorkspace.Create(xmlString, exportProvider: ExportProvider); var testDocument = testWorkspace.Documents.Single(d => d.Name == "CSharpDocument"); Contract.ThrowIfNull(testDocument.CursorPosition); var cursorPosition = testDocument.CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var documentId = testWorkspace.Documents.Single(d => d.Name == "CSharpDocument").Id; var document = solution.GetRequiredDocument(documentId); var triggerInfo = CompletionTrigger.Invoke; var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, cursorPosition, triggerInfo); var completionItem = completionList.Items.First(i => CompareItems(i.DisplayText, "Equals(object obj)")); if (service.GetProvider(completionItem) is ICustomCommitCompletionProvider customCommitCompletionProvider) { var textView = testWorkspace.GetTestDocument(documentId).GetTextView(); customCommitCompletionProvider.Commit(completionItem, textView, textView.TextBuffer, textView.TextSnapshot, '\t'); var actualCodeAfterCommit = textView.TextBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = textView.Caret.Position.BufferPosition.Position; MarkupTestFile.GetPosition(csharpFileAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); } } #endregion #region "EditorBrowsable should be ignored" [WpfFact] [WorkItem(545678, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545678")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_IgnoredWhenOverridingMethods() { var markup = @" class D : B { override $$ }"; var referencedCode = @" public class B { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public virtual void Goo() {} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo()", expectedSymbolsMetadataReference: 1, expectedSymbolsSameSolution: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DuplicateMember() { var markupBeforeCommit = @"class Program { public virtual void goo() {} public virtual void goo() {} } class C : Program { override $$ }"; var expectedCodeAfterCommit = @"class Program { public virtual void goo() {} public virtual void goo() {} } class C : Program { public override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LeaveTrailingTriviaAlone() { var text = @" namespace ConsoleApplication46 { class Program { static void Main(string[] args) { } override $$ } }"; using var workspace = TestWorkspace.Create(LanguageNames.CSharp, new CSharpCompilationOptions(OutputKind.ConsoleApplication), new CSharpParseOptions(), new[] { text }, ExportProvider); var provider = new OverrideCompletionProvider(); var testDocument = workspace.Documents.Single(); var document = workspace.CurrentSolution.GetRequiredDocument(testDocument.Id); var service = GetCompletionService(document.Project); Contract.ThrowIfNull(testDocument.CursorPosition); var completionList = await GetCompletionListAsync(service, document, testDocument.CursorPosition.Value, CompletionTrigger.Invoke); var oldTree = await document.GetSyntaxTreeAsync(); var commit = await provider.GetChangeAsync(document, completionList.Items.First(i => i.DisplayText == "ToString()"), ' '); var change = commit.TextChange; // If we left the trailing trivia of the close curly of Main alone, // there should only be one change: the replacement of "override " with a method. Assert.Equal(change.Span, TextSpan.FromBounds(136, 145)); } [WorkItem(8257, "https://github.com/dotnet/roslyn/issues/8257")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotImplementedQualifiedWhenSystemUsingNotPresent_Property() { var markupBeforeCommit = @"abstract class C { public abstract int goo { get; set; }; } class Program : C { override $$ }"; var expectedCodeAfterCommit = @"abstract class C { public abstract int goo { get; set; }; } class Program : C { public override int goo { get { throw new System.NotImplementedException();$$ } set { throw new System.NotImplementedException(); } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); } [WorkItem(8257, "https://github.com/dotnet/roslyn/issues/8257")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotImplementedQualifiedWhenSystemUsingNotPresent_Method() { var markupBeforeCommit = @"abstract class C { public abstract void goo(); } class Program : C { override $$ }"; var expectedCodeAfterCommit = @"abstract class C { public abstract void goo(); } class Program : C { public override void goo() { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FilterOutMethodsWithNonRoundTrippableSymbolKeys() { var text = XElement.Parse(@"<Workspace> <Project Name=""P1"" Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C : ClassLibrary7.Class1 { override $$ } ]]> </Document> </Project> <Project Name=""P2"" Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document> namespace ClassLibrary2 { public class Missing {} } </Document> </Project> <Project Name=""P3"" Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3.dll""> <ProjectReference>P2</ProjectReference> <Document> namespace ClassLibrary7 { public class Class1 { public virtual void Goo(ClassLibrary2.Missing m) {} public virtual void Bar() {} } } </Document> </Project> </Workspace>"); // P3 has a project ref to Project P2 and uses the type "Missing" from P2 // as the return type of a virtual method. // P1 has a metadata reference to P3 and therefore doesn't get the transitive // reference to P2. If we try to override Goo, the missing "Missing" type will // prevent round tripping the symbolkey. using var workspace = TestWorkspace.Create(text, exportProvider: ExportProvider); var compilation = await workspace.CurrentSolution.Projects.First(p => p.Name == "P3").GetCompilationAsync(); // CompilationExtensions is in the Microsoft.CodeAnalysis.Test.Utilities namespace // which has a "Traits" type that conflicts with the one in Roslyn.Test.Utilities var reference = MetadataReference.CreateFromImage(compilation.EmitToArray()); var p1 = workspace.CurrentSolution.Projects.First(p => p.Name == "P1"); var updatedP1 = p1.AddMetadataReference(reference); workspace.ChangeSolution(updatedP1.Solution); var provider = new OverrideCompletionProvider(); var testDocument = workspace.Documents.First(d => d.Name == "CurrentDocument.cs"); var document = workspace.CurrentSolution.GetRequiredDocument(testDocument.Id); var service = GetCompletionService(document.Project); Contract.ThrowIfNull(testDocument.CursorPosition); var completionList = await GetCompletionListAsync(service, document, testDocument.CursorPosition.Value, CompletionTrigger.Invoke); Assert.True(completionList.Items.Any(c => c.DisplayText == "Bar()")); Assert.False(completionList.Items.Any(c => c.DisplayText == "Goo()")); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInParameter() { var source = XElement.Parse(@"<Workspace> <Project Name=""P1"" Language=""C#"" LanguageVersion=""Latest"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ public class SomeClass : Base { override $$ } ]]> </Document> </Project> </Workspace>"); using var workspace = TestWorkspace.Create(source, exportProvider: ExportProvider); var before = @" public abstract class Base { public abstract void M(in int x); }"; var after = @" public class SomeClass : Base { public override void M(in int x) { throw new System.NotImplementedException(); } } "; var origComp = await workspace.CurrentSolution.Projects.Single().GetRequiredCompilationAsync(CancellationToken.None); var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest); var libComp = origComp.RemoveAllSyntaxTrees().AddSyntaxTrees(CSharpSyntaxTree.ParseText(before, options: options)); var libRef = MetadataReference.CreateFromImage(libComp.EmitToArray()); var project = workspace.CurrentSolution.Projects.Single(); var updatedProject = project.AddMetadataReference(libRef); workspace.ChangeSolution(updatedProject.Solution); var provider = new OverrideCompletionProvider(); var testDocument = workspace.Documents.First(d => d.Name == "CurrentDocument.cs"); var document = workspace.CurrentSolution.GetRequiredDocument(testDocument.Id); var service = GetCompletionService(document.Project); Contract.ThrowIfNull(testDocument.CursorPosition); var completionList = await GetCompletionListAsync(service, document, testDocument.CursorPosition.Value, CompletionTrigger.Invoke); var completionItem = completionList.Items.Where(c => c.DisplayText == "M(in int x)").Single(); var commit = await service.GetChangeAsync(document, completionItem, commitKey: null, CancellationToken.None); var text = await document.GetTextAsync(); var newText = text.WithChanges(commit.TextChange); var newDoc = document.WithText(newText); document.Project.Solution.Workspace.TryApplyChanges(newDoc.Project.Solution); var textBuffer = workspace.Documents.Single().GetTextBuffer(); var actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString(); Assert.Equal(after, actualCodeAfterCommit); } [WorkItem(39909, "https://github.com/dotnet/roslyn/issues/39909")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAddsMissingImports() { var markupBeforeCommit = @" namespace NS1 { using NS2; public class Goo { public virtual bool Bar(Baz baz) => true; } } namespace NS2 { public class Baz {} } namespace NS3 { using NS1; class D : Goo { override $$ } }"; var expectedCodeAfterCommit = @" namespace NS1 { using NS2; public class Goo { public virtual bool Bar(Baz baz) => true; } } namespace NS2 { public class Baz {} } namespace NS3 { using NS1; using NS2; class D : Goo { public override bool Bar(Baz baz) { return base.Bar(baz);$$ } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Bar(NS2.Baz baz)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47941, "https://github.com/dotnet/roslyn/issues/47941")] public async Task OverrideInRecordWithoutExplicitOverriddenMember() { await VerifyItemExistsAsync(@"record Program { override $$ }", "ToString()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47941, "https://github.com/dotnet/roslyn/issues/47941")] public async Task OverrideInRecordWithExplicitOverriddenMember() { await VerifyItemIsAbsentAsync(@"record Program { public override string ToString() => ""; override $$ }", "ToString()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47973, "https://github.com/dotnet/roslyn/issues/47973")] public async Task NoCloneInOverriddenRecord() { // Currently WellKnownMemberNames.CloneMethodName is not public, so we can't reference it directly. We // could hardcode in the value "<Clone>$", however if the compiler ever changed the name and we somehow // started showing it in completion, this test would continue to pass. So this allows us to at least go // back and explicitly validate this scenario even in that event. var cloneMemberName = (string)typeof(WellKnownMemberNames).GetField("CloneMethodName", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null); Assert.Equal("<Clone>$", cloneMemberName); await VerifyItemIsAbsentAsync(@" record Base(); record Program : Base { override $$ }", cloneMemberName); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(48640, "https://github.com/dotnet/roslyn/issues/48640")] public async Task ObjectEqualsInClass() { await VerifyItemExistsAsync(@" class Program { override $$ }", "Equals(object obj)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(48640, "https://github.com/dotnet/roslyn/issues/48640")] public async Task NoObjectEqualsInOverriddenRecord1() { await VerifyItemIsAbsentAsync(@" record Program { override $$ }", "Equals(object obj)"); await VerifyItemExistsAsync(@" record Program { override $$ }", "ToString()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(48640, "https://github.com/dotnet/roslyn/issues/48640")] public async Task NoObjectEqualsInOverriddenRecord() { await VerifyItemIsAbsentAsync(@" record Base(); record Program : Base { override $$ }", "Equals(object obj)"); await VerifyItemExistsAsync(@" record Base(); record Program : Base { override $$ }", "ToString()"); } private Task VerifyItemExistsAsync(string markup, string expectedItem) { return VerifyItemExistsAsync(markup, expectedItem, isComplexTextEdit: 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.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public class OverrideCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(OverrideCompletionProvider); protected override OptionSet WithChangedOptions(OptionSet options) { return options .WithChangedOption(CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, CSharpCodeStyleOptions.NeverWithSilentEnforcement) .WithChangedOption(CSharpCodeStyleOptions.PreferExpressionBodiedProperties, CSharpCodeStyleOptions.NeverWithSilentEnforcement); } #region "CompletionItem tests" [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedVirtualPublicMethod() { await VerifyItemExistsAsync(@" public class a { public virtual void goo() { } } public class b : a { override $$ }", "goo()"); } [WorkItem(543799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543799")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedParameterDefaultValue1() { await VerifyItemExistsAsync(@"public class a { public virtual void goo(int x = 42) { } } public class b : a { override $$ }", "goo(int x = 42)", "void a.goo([int x = 42])"); } [WorkItem(543799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543799")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedParameterDefaultValue2() { await VerifyItemExistsAsync(@"public class a { public virtual void goo(int x, int y = 42) { } } public class b : a { override $$ }", "goo(int x, int y = 42)", "void a.goo(int x, [int y = 42])"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InheritedAbstractPublicMethod() { await VerifyItemExistsAsync(@" public class a { public abstract void goo(); } public class b : a { override $$ }", "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotPrivateInheritedMethod() { await VerifyItemIsAbsentAsync(@" public class a { private virtual void goo() { } } public class b : a { override $$ }", "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task MatchReturnType() { var markup = @" public class a { public virtual void goo() { } public virtual string bar() {return null;} } public class b : a { override void $$ }"; await VerifyItemIsAbsentAsync(markup, "bar()"); await VerifyItemExistsAsync(markup, "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InvalidReturnType() { var markup = @" public class a { public virtual void goo() { } public virtual string bar() {return null;} } public class b : a { override badtype $$ }"; await VerifyItemExistsAsync(markup, "goo()"); await VerifyItemExistsAsync(markup, "bar()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAlreadyImplementedMethods() { await VerifyItemIsAbsentAsync(@" public class a { protected virtual void goo() { } protected virtual string bar() {return null;} } public class b : a { protected override void goo() { } override $$ }", "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotSealed() { await VerifyItemIsAbsentAsync(@" public class a { protected sealed void goo() { } } public class b : a { public override $$ }", "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ShowEvent() { await VerifyItemExistsAsync(@" using System; public class a { public virtual event EventHandler goo; } public class b : a { public override $$ }", "goo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotIfTokensAfterPosition() { await VerifyNoItemsExistAsync(@" public class a { public virtual void goo() { } } public class b : a { public override $$ void }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotIfNameAfterPosition() { await VerifyNoItemsExistAsync(@" public class a { public virtual void goo() { } } public class b : a { public override void $$ bar }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotIfStatic() { await VerifyNoItemsExistAsync(@" public class a { public virtual void goo() { } } public class b : a { public static override $$ }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterSingleLineMethodDeclaration() { await VerifyNoItemsExistAsync(@" public class a { public virtual void goo() { } } public class b : a { void bar() { } override $$ }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SuggestProperty() { await VerifyItemExistsAsync(@" public class a { public virtual int goo { } } public class b : a { override $$ }", "goo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotSuggestSealed() { await VerifyItemIsAbsentAsync(@" public class a { public sealed int goo { } } public class b : a { override $$ }", "goo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GatherModifiers() { await VerifyItemExistsAsync(@" public class a { public abstract extern unsafe int goo { } } public class b : a { override $$ }", "goo"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IgnorePartial() { await VerifyNoItemsExistAsync(@" public class a { public virtual partial goo() { } } public class b : a { override partial $$ }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IgnoreSealed() { await VerifyItemIsAbsentAsync(@" public class a { public virtual sealed int goo() { } } public class b : a { override $$ }", "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IgnoreIfTokenAfter() { await VerifyNoItemsExistAsync(@" public class a { public virtual int goo() { } } public class b : a { override $$ int }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SuggestAfterUnsafeAbstractExtern() { await VerifyItemExistsAsync(@" public class a { public virtual int goo() { } } public class b : a { unsafe abstract extern override $$ }", "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SuggestAfterSealed() { await VerifyItemExistsAsync(@" public class a { public virtual int goo() { } } public class b : a { sealed override $$ }", "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NoAccessibility() { var markup = @" public class a { public virtual int goo() { } protected virtual int bar() { } } public class b : a { override $$ }"; await VerifyItemExistsAsync(markup, "goo()"); await VerifyItemExistsAsync(markup, "bar()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FilterAccessibility() { var markup = @" public class a { public virtual int goo() { } protected virtual int bar() { } internal virtual int far() { } private virtual int bor() { } } public class b : a { override internal $$ }"; await VerifyItemIsAbsentAsync(markup, "goo()"); await VerifyItemIsAbsentAsync(markup, "bar()"); await VerifyItemIsAbsentAsync(markup, "bor()"); await VerifyItemExistsAsync(markup, "far()"); await VerifyItemExistsAsync(@" public class a { public virtual int goo() { } protected virtual int bar() { } internal virtual int far() { } private virtual int bor() { } } public class b : a { override protected $$ }", "bar()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FilterPublicInternal() { var protectedinternal = @" public class a { protected internal virtual void goo() { } public virtual void bar() { } } public class b : a { protected internal override $$ }"; await VerifyItemIsAbsentAsync(protectedinternal, "bar()"); await VerifyItemExistsAsync(protectedinternal, "goo()"); var internalprotected = @" public class a { protected internal virtual void goo() { } public virtual void bar() { } } public class b : a { internal protected override $$ }"; await VerifyItemIsAbsentAsync(internalprotected, "bar()"); await VerifyItemExistsAsync(internalprotected, "goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task VerifySignatureFormat() { var markup = @" public class a { override $$ }"; await VerifyItemExistsAsync(markup, "Equals(object obj)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task PrivateNoFilter() { var markup = @" public class c { public virtual void goo() { } } public class a : c { private override $$ }"; await VerifyNoItemsExistAsync(markup); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotOfferedOnFirstLine() { var markup = @"class c { override $$"; await VerifyNoItemsExistAsync(markup); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotOfferedOverrideAlone() { var markup = @"override $$"; await VerifyNoItemsExistAsync(markup); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IntermediateClassOverriddenMember() { var markup = @"abstract class Base { public abstract void Goo(); } class Derived : Base { public override void Goo() { } } class SomeClass : Derived { override $$ }"; await VerifyItemExistsAsync(markup, "Goo()", "void Derived.Goo()"); } [WorkItem(543748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543748")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotOfferedBaseClassMember() { var markup = @"abstract class Base { public abstract void Goo(); } class Derived : Base { public override void Goo() { } } class SomeClass : Derived { override $$ }"; await VerifyItemIsAbsentAsync(markup, "Goo()", "void Base.Goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotOfferedOnNonVirtual() { var markup = @"class Base { public void Goo(); } class SomeClass : Base { override $$ }"; await VerifyItemIsAbsentAsync(markup, "Goo()", "void Base.Goo()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GenericTypeNameSubstitutedForGenericInDerivedClass1() { var markup = @"public abstract class Base<T> { public abstract void Goo(T t); } public class SomeClass<X> : Base<X> { override $$ }"; await VerifyItemExistsAsync(markup, "Goo(X t)"); await VerifyItemIsAbsentAsync(markup, "Goo(T t)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GenericTypeNameSubstitutedForGenericInDerivedClass2() { var markup = @"public abstract class Base<T> { public abstract void Goo(T t); } public class SomeClass<X, Y, Z> : Base<Y> { override $$ }"; await VerifyItemExistsAsync(markup, "Goo(Y t)"); await VerifyItemIsAbsentAsync(markup, "Goo(T t)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GenericTypeNameSubstitutedForGenericInDerivedClass3() { var markup = @"public abstract class Base<T, S> { public abstract void Goo(T t, S s); } public class SomeClass<X, Y, Z> : Base<Y, Z> { override $$ }"; await VerifyItemExistsAsync(markup, "Goo(Y t, Z s)"); await VerifyItemIsAbsentAsync(markup, "Goo(T t, S s)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GenericTypeNameSubstitutedForNonGenericInDerivedClass1() { var markup = @"public abstract class Base<T> { public abstract void Goo(T t); } public class SomeClass : Base<int> { override $$ }"; await VerifyItemExistsAsync(markup, "Goo(int t)"); await VerifyItemIsAbsentAsync(markup, "Goo(T t)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GenericTypeNameSubstitutedForNonGenericInDerivedClass2() { var markup = @"public abstract class Base<T> { public abstract void Goo(T t); } public class SomeClass<X, Y, Z> : Base<int> { override $$ }"; await VerifyItemExistsAsync(markup, "Goo(int t)"); await VerifyItemIsAbsentAsync(markup, "Goo(T t)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GenericTypeNameSubstitutedForNonGenericInDerivedClass3() { var markup = @"using System; public abstract class Base<T, S> { public abstract void Goo(T t, S s); } public class SomeClass : Base<int, Exception> { override $$ }"; await VerifyItemExistsAsync(markup, "Goo(int t, Exception s)"); await VerifyItemIsAbsentAsync(markup, "Goo(T t, S s)"); } [WorkItem(543756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543756")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task ParameterTypeSimplified() { var markup = @"using System; public abstract class Base { public abstract void Goo(System.Exception e); } public class SomeClass : Base { override $$ }"; await VerifyItemExistsAsync(markup, "Goo(Exception e)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NullableAnnotationsIncluded() { var markup = @"#nullable enable public abstract class Base { public abstract void Goo(string? s); } public class SomeClass : Base { override $$ }"; await VerifyItemExistsAsync(markup, "Goo(string? s)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EscapedMethodNameInIntelliSenseList() { var markup = @"public abstract class Base { public abstract void @class(); } public class SomeClass : Base { override $$ }"; MarkupTestFile.GetPosition(markup, out var code, out int position); await BaseVerifyWorkerAsync(code, position, "@class()", "void Base.@class()", SourceCodeKind.Regular, false, false, null, null, null, null, null, null); await BaseVerifyWorkerAsync(code, position, "@class()", "void Base.@class()", SourceCodeKind.Script, false, false, null, null, null, null, null, null); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EscapedPropertyNameInIntelliSenseList() { var markup = @"public abstract class Base { public virtual int @class { get; set; } } public class SomeClass : Base { override $$ }"; MarkupTestFile.GetPosition(markup, out var code, out int position); await BaseVerifyWorkerAsync(code, position, "@class", "int Base.@class { get; set; }", SourceCodeKind.Regular, false, false, null, null, null, null, null, null); await BaseVerifyWorkerAsync(code, position, "@class", "int Base.@class { get; set; }", SourceCodeKind.Script, false, false, null, null, null, null, null, null); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task EscapedParameterNameInIntelliSenseList() { var markup = @"public abstract class Base { public abstract void goo(int @class); } public class SomeClass : Base { override $$ }"; await VerifyItemExistsAsync(markup, "goo(int @class)", "void Base.goo(int @class)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task RefParameter() { var markup = @"public abstract class Base { public abstract void goo(int x, ref string y); } public class SomeClass : Base { override $$ }"; await VerifyItemExistsAsync(markup, "goo(int x, ref string y)", "void Base.goo(int x, ref string y)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OutParameter() { var markup = @"public abstract class Base { public abstract void goo(int x, out string y); } public class SomeClass : Base { override $$ }"; await VerifyItemExistsAsync(markup, "goo(int x, out string y)", "void Base.goo(int x, out string y)"); } [WorkItem(529714, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529714")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task GenericMethodTypeParametersNotRenamed() { var markup = @"abstract class CGoo { public virtual X Something<X>(X arg) { return default(X); } } class Derived<X> : CGoo { override $$ }"; await VerifyItemExistsAsync(markup, "Something<X>(X arg)"); } #endregion #region "Commit tests" [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInEmptyClass() { var markupBeforeCommit = @"class c { override $$ }"; var expectedCodeAfterCommit = @"class c { public override bool Equals(object obj) { return base.Equals(obj);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Equals(object obj)", expectedCodeAfterCommit); } [WorkItem(529714, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529714")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitGenericMethodTypeParametersNotRenamed() { var markupBeforeCommit = @"abstract class CGoo { public virtual X Something<X>(X arg) { return default(X); } } class Derived<X> : CGoo { override $$ }"; var expectedCodeAfterCommit = @"abstract class CGoo { public virtual X Something<X>(X arg) { return default(X); } } class Derived<X> : CGoo { public override X Something<X>(X arg) { return base.Something(arg);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Something<X>(X arg)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitMethodBeforeMethod() { var markupBeforeCommit = @"class c { override $$ public void goo() { } }"; var expectedCodeAfterCommit = @"class c { public override bool Equals(object obj) { return base.Equals(obj);$$ } public void goo() { } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Equals(object obj)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitMethodAfterMethod() { var markupBeforeCommit = @"class c { public void goo() { } override $$ }"; var expectedCodeAfterCommit = @"class c { public void goo() { } public override bool Equals(object obj) { return base.Equals(obj);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Equals(object obj)", expectedCodeAfterCommit); } [WorkItem(543798, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543798")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitOptionalParameterValuesAreGenerated() { var markupBeforeCommit = @"using System; abstract public class Base { public abstract void goo(int x = 42); } public class Derived : Base { override $$ }"; var expectedCodeAfterCommit = @"using System; abstract public class Base { public abstract void goo(int x = 42); } public class Derived : Base { public override void goo(int x = 42) { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int x = 42)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAttributesAreNotGenerated() { var markupBeforeCommit = @"using System; public class Base { [Obsolete] public virtual void goo() { } } public class Derived : Base { override $$ }"; var expectedCodeAfterCommit = @"using System; public class Base { [Obsolete] public virtual void goo() { } } public class Derived : Base { public override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInaccessibleParameterAttributesAreNotGenerated() { var markupBeforeCommit = @"using System; public class Class1 { private class MyPrivate : Attribute { } public class MyPublic : Attribute { } public virtual void M([MyPrivate, MyPublic] int i) { } } public class Class2 : Class1 { public override void $$ }"; var expectedCodeAfterCommit = @"using System; public class Class1 { private class MyPrivate : Attribute { } public class MyPublic : Attribute { } public virtual void M([MyPrivate, MyPublic] int i) { } } public class Class2 : Class1 { public override void M([MyPublic] int i) { base.M(i);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "M(int i)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitVoidMethod() { var markupBeforeCommit = @"class c { public virtual void goo() { } } class d : c { override $$ }"; var expectedCodeAfterCommit = @"class c { public virtual void goo() { } } class d : c { public override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitVoidMethodWithParams() { var markupBeforeCommit = @"class c { public virtual void goo(int bar, int quux) { } } class d : c { override $$ }"; var expectedCodeAfterCommit = @"class c { public virtual void goo(int bar, int quux) { } } class d : c { public override void goo(int bar, int quux) { base.goo(bar, quux);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int bar, int quux)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitNonVoidMethod() { var markupBeforeCommit = @"class c { public virtual int goo() { } } class d : c { override $$ }"; var expectedCodeAfterCommit = @"class c { public virtual int goo() { } } class d : c { public override int goo() { return base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitNonVoidMethodWithParams() { var markupBeforeCommit = @"class c { public virtual int goo(int bar, int quux) { } } class d : c { override $$ }"; var expectedCodeAfterCommit = @"class c { public virtual int goo(int bar, int quux) { } } class d : c { public override int goo(int bar, int quux) { return base.goo(bar, quux);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int bar, int quux)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitProtectedMethod() { var markupBeforeCommit = @"class c { protected virtual void goo() { } } class d : c { override $$ }"; var expectedCodeAfterCommit = @"class c { protected virtual void goo() { } } class d : c { protected override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInternalMethod() { var markupBeforeCommit = @"class c { internal virtual void goo() { } } class d : c { override $$ }"; var expectedCodeAfterCommit = @"class c { internal virtual void goo() { } } class d : c { internal override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitProtectedInternalMethod() { var markupBeforeCommit = @"public class c { protected internal virtual void goo() { } } class d : c { override $$ }"; var expectedCodeAfterCommit = @"public class c { protected internal virtual void goo() { } } class d : c { protected internal override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAbstractMethodThrows() { var markupBeforeCommit = @"using System; abstract class c { public abstract void goo(); } class d : c { override $$ }"; var expectedCodeAfterCommit = @"using System; abstract class c { public abstract void goo(); } class d : c { public override void goo() { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitOverrideAsAbstract() { var markupBeforeCommit = @"class c { public virtual void goo() { }; } class d : c { abstract override $$ }"; var expectedCodeAfterCommit = @"class c { public virtual void goo() { }; } class d : c { public abstract override void goo();$$ }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitOverrideAsUnsafeSealed() { var markupBeforeCommit = @"class c { public virtual void goo() { }; } class d : c { unsafe sealed override $$ }"; var expectedCodeAfterCommit = @"class c { public virtual void goo() { }; } class d : c { public sealed override unsafe void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInsertProperty() { var markupBeforeCommit = @"public class c { public virtual int goo { get; set; } } public class d : c { override $$ }"; var expectedCodeAfterCommit = @"public class c { public virtual int goo { get; set; } } public class d : c { public override int goo { get { return base.goo;$$ } set { base.goo = value; } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInsertPropertyAfterMethod() { var markupBeforeCommit = @"public class c { public virtual int goo { get; set; } } public class d : c { public void a() { } override $$ }"; var expectedCodeAfterCommit = @"public class c { public virtual int goo { get; set; } } public class d : c { public void a() { } public override int goo { get { return base.goo;$$ } set { base.goo = value; } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInsertPropertyBeforeMethod() { var markupBeforeCommit = @"public class c { public virtual int goo { get; set; } } public class d : c { override $$ public void a() { } }"; var expectedCodeAfterCommit = @"public class c { public virtual int goo { get; set; } } public class d : c { public override int goo { get { return base.goo;$$ } set { base.goo = value; } } public void a() { } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitPropertyInaccessibleGet() { var markupBeforeCommit = @"public class c { public virtual int goo { private get; set; } } public class d : c { override $$ }"; var expectedCodeAfterCommit = @"public class c { public virtual int goo { private get; set; } } public class d : c { public override int goo { set { base.goo = value;$$ } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitPropertyInaccessibleSet() { var markupBeforeCommit = @"public class c { public virtual int goo { private set; get; } } public class d : c { override $$ }"; var expectedCodeAfterCommit = @"public class c { public virtual int goo { private set; get; } } public class d : c { public override int goo { get { return base.goo;$$ } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInsertPropertyInaccessibleParameterAttributesAreNotGenerated() { var markupBeforeCommit = @"using System; namespace ClassLibrary1 { public class Class1 { private class MyPrivate : Attribute { } public class MyPublic : Attribute { } public virtual int this[[MyPrivate, MyPublic]int i] { get { return 0; } set { } } } public class Class2 : Class1 { public override int $$ } }"; var expectedCodeAfterCommit = @"using System; namespace ClassLibrary1 { public class Class1 { private class MyPrivate : Attribute { } public class MyPublic : Attribute { } public virtual int this[[MyPrivate, MyPublic]int i] { get { return 0; } set { } } } public class Class2 : Class1 { public override int this[[MyPublic] int i] { get { return base[i];$$ } set { base[i] = value; } } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "this[int i]", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAccessibleEvent() { var markupBeforeCommit = @"using System; public class a { public virtual event EventHandler goo; } public class b : a { override $$ }"; var expectedCodeAfterCommit = @"using System; public class a { public virtual event EventHandler goo; } public class b : a { public override event EventHandler goo;$$ }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitEventAfterMethod() { var markupBeforeCommit = @"using System; public class a { public virtual event EventHandler goo; } public class b : a { void bar() { } override $$ }"; var expectedCodeAfterCommit = @"using System; public class a { public virtual event EventHandler goo; } public class b : a { void bar() { } public override event EventHandler goo;$$ }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitGenericMethod() { var markupBeforeCommit = @"using System; public class a { public virtual void goo<T>() { } } public class b : a { override $$ }"; var expectedCodeAfterCommit = @"using System; public class a { public virtual void goo<T>() { } } public class b : a { public override void goo<T>() { base.goo<T>();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo<T>()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitMethodWithNullableAttributes() { var markupBeforeCommit = @" #nullable enable class C { public virtual string? Goo(string? s) { } } class D : C { override $$ }"; var expectedCodeAfterCommit = @" #nullable enable class C { public virtual string? Goo(string? s) { } } class D : C { public override string? Goo(string? s) { return base.Goo(s);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo(string? s)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitMethodInNullableDisableContext() { var markupBeforeCommit = @" #nullable enable class C { public virtual string? Goo(string? s) { } } #nullable disable class D : C { override $$ }"; var expectedCodeAfterCommit = @" #nullable enable class C { public virtual string? Goo(string? s) { } } #nullable disable class D : C { public override string Goo(string s) { return base.Goo(s);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo(string? s)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitToStringIsExplicitlyNonNullReturning() { var markupBeforeCommit = @" #nullable enable namespace System { public class Object { public virtual string? ToString() { } } } class D : System.Object { override $$ }"; var expectedCodeAfterCommit = @" #nullable enable namespace System { public class Object { public virtual string? ToString() { } } } class D : System.Object { public override string ToString() { return base.ToString();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "ToString()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitInsertIndexer() { var markupBeforeCommit = @"public class MyIndexer<T> { private T[] arr = new T[100]; public virtual T this[int i] { get { return arr[i]; } set { arr[i] = value; } } } class d : MyIndexer<T> { override $$ }"; var expectedCodeAfterCommit = @"public class MyIndexer<T> { private T[] arr = new T[100]; public virtual T this[int i] { get { return arr[i]; } set { arr[i] = value; } } } class d : MyIndexer<T> { public override T this[int i] { get { return base[i];$$ } set { base[i] = value; } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "this[int i]", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAbstractIndexer() { var markupBeforeCommit = @"public class MyIndexer<T> { private T[] arr = new T[100]; public abstract T this[int i] { get; set; } } class d : MyIndexer<T> { override $$ }"; var expectedCodeAfterCommit = @"public class MyIndexer<T> { private T[] arr = new T[100]; public abstract T this[int i] { get; set; } } class d : MyIndexer<T> { public override T this[int i] { get { throw new System.NotImplementedException();$$ } set { throw new System.NotImplementedException(); } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "this[int i]", expectedCodeAfterCommit); } // The following two scenarios are already verified through 'VerifyCommit', // which also tests everything at the end of the file (truncating input markup at $$) // public void CommitInsertAtEndOfFile() // public void CommitInsertAtEndOfFileAfterMethod() [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitFormats() { var markupBeforeCommit = @"class Base { public virtual void goo() { } } class Derived : Base { override $$ }"; var expectedCodeAfterCommit = @"class Base { public virtual void goo() { } } class Derived : Base { public override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitSimplifiesParameterTypes() { var markupBeforeCommit = @"using System; public abstract class Base { public abstract void goo(System.Exception e); } public class SomeClass : Base { override $$ }"; var expectedCodeAfterCommit = @"using System; public abstract class Base { public abstract void goo(System.Exception e); } public class SomeClass : Base { public override void goo(Exception e) { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(Exception e)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitSimplifiesReturnType() { var markupBeforeCommit = @"using System; public abstract class Base { public abstract System.ArgumentException goo(System.Exception e); } public class SomeClass : Base { override $$ }"; var expectedCodeAfterCommit = @"using System; public abstract class Base { public abstract System.ArgumentException goo(System.Exception e); } public class SomeClass : Base { public override ArgumentException goo(Exception e) { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(Exception e)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitEscapedMethodName() { var markupBeforeCommit = @"using System; public abstract class Base { public abstract void @class(); } public class SomeClass : Base { override $$ }"; var expectedCodeAfterCommit = @"using System; public abstract class Base { public abstract void @class(); } public class SomeClass : Base { public override void @class() { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "@class()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitEscapedPropertyName() { var markupBeforeCommit = @"public abstract class Base { public virtual int @class { get; set; } } public class SomeClass : Base { override $$ }"; var expectedCodeAfterCommit = @"public abstract class Base { public virtual int @class { get; set; } } public class SomeClass : Base { public override int @class { get { return base.@class;$$ } set { base.@class = value; } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "@class", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitEscapedParameterName() { var markupBeforeCommit = @"using System; public abstract class Base { public abstract void goo(int @class); } public class SomeClass : Base { override $$ }"; var expectedCodeAfterCommit = @"using System; public abstract class Base { public abstract void goo(int @class); } public class SomeClass : Base { public override void goo(int @class) { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int @class)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitRefParameter() { var markupBeforeCommit = @"using System; public abstract class Base { public abstract void goo(int x, ref string y); } public class SomeClass : Base { override $$ }"; var expectedCodeAfterCommit = @"using System; public abstract class Base { public abstract void goo(int x, ref string y); } public class SomeClass : Base { public override void goo(int x, ref string y) { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int x, ref string y)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitOutParameter() { var markupBeforeCommit = @"using System; public abstract class Base { public abstract void goo(int x, out string y); } public class SomeClass : Base { override $$ }"; var expectedCodeAfterCommit = @"using System; public abstract class Base { public abstract void goo(int x, out string y); } public class SomeClass : Base { public override void goo(int x, out string y) { throw new NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo(int x, out string y)", expectedCodeAfterCommit); } [WorkItem(544560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544560")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestUnsafe1() { var markupBeforeCommit = @"public class A { public unsafe virtual void F() { } } public class B : A { override $$ }"; var expectedCodeAfterCommit = @"public class A { public unsafe virtual void F() { } } public class B : A { public override void F() { base.F();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "F()", expectedCodeAfterCommit); } [WorkItem(544560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544560")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestUnsafe2() { var markupBeforeCommit = @"public class A { public unsafe virtual void F() { } } public class B : A { override unsafe $$ }"; var expectedCodeAfterCommit = @"public class A { public unsafe virtual void F() { } } public class B : A { public override unsafe void F() { base.F();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "F()", expectedCodeAfterCommit); } [WorkItem(544560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544560")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestUnsafe3() { var markupBeforeCommit = @"public class A { public unsafe virtual void F() { } } public class B : A { unsafe override $$ }"; var expectedCodeAfterCommit = @"public class A { public unsafe virtual void F() { } } public class B : A { public override unsafe void F() { base.F();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "F()", expectedCodeAfterCommit); } [WorkItem(544560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544560")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestUnsafe4() { var markupBeforeCommit = @"public class A { public virtual void F(int* i) { } } public class B : A { override $$ }"; var expectedCodeAfterCommit = @"public class A { public virtual void F(int* i) { } } public class B : A { public override unsafe void F(int* i) { base.F(i);$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "F(int* i)", expectedCodeAfterCommit); } [WorkItem(545534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545534")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestPrivateVirtualProperty() { var markupBeforeCommit = @"public class B { public virtual int Goo { get; private set; } class C : B { override $$ } }"; var expectedCodeAfterCommit = @"public class B { public virtual int Goo { get; private set; } class C : B { public override int Goo { get { return base.Goo;$$ } } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Goo", expectedCodeAfterCommit); } [WorkItem(636706, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636706")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CrossLanguageParameterizedPropertyOverride() { var vbFile = @"Public Class Goo Public Overridable Property Bar(bay As Integer) As Integer Get Return 23 End Get Set(value As Integer) End Set End Property End Class "; var csharpFile = @"class Program : Goo { override $$ } "; var csharpFileAfterCommit = @"class Program : Goo { public override int get_Bar(int bay) { return base.get_Bar(bay);$$ } public override void set_Bar(int bay, int value) { base.set_Bar(bay, value); } } "; var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <ProjectReference>VBProject</ProjectReference> <Document FilePath=""CSharpDocument"">{1}</Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""VBProject""> <Document FilePath=""VBDocument""> {3} </Document> </Project> </Workspace>", LanguageNames.CSharp, csharpFile, LanguageNames.VisualBasic, vbFile); using var testWorkspace = TestWorkspace.Create(xmlString, exportProvider: ExportProvider); var testDocument = testWorkspace.Documents.Single(d => d.Name == "CSharpDocument"); Contract.ThrowIfNull(testDocument.CursorPosition); var position = testDocument.CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var documentId = testWorkspace.Documents.Single(d => d.Name == "CSharpDocument").Id; var document = solution.GetRequiredDocument(documentId); var triggerInfo = CompletionTrigger.Invoke; var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, position, triggerInfo); var completionItem = completionList.Items.First(i => CompareItems(i.DisplayText, "Bar[int bay]")); if (service.GetProvider(completionItem) is ICustomCommitCompletionProvider customCommitCompletionProvider) { var textView = testWorkspace.GetTestDocument(documentId).GetTextView(); customCommitCompletionProvider.Commit(completionItem, textView, textView.TextBuffer, textView.TextSnapshot, '\t'); var actualCodeAfterCommit = textView.TextBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = textView.Caret.Position.BufferPosition.Position; MarkupTestFile.GetPosition(csharpFileAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); } } #endregion #region "Commit: With Trivia" [WorkItem(529199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529199")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitSurroundingTriviaDirective() { var markupBeforeCommit = @"class Base { public virtual void goo() { } } class Derived : Base { #if true override $$ #endif }"; var expectedCodeAfterCommit = @"class Base { public virtual void goo() { } } class Derived : Base { #if true public override void goo() { base.goo();$$ } #endif }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WorkItem(529199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529199")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitBeforeTriviaDirective() { var markupBeforeCommit = @"class Base { public virtual void goo() { } } class Derived : Base { override $$ #if true #endif }"; var expectedCodeAfterCommit = @"class Base { public virtual void goo() { } } class Derived : Base { public override void goo() { base.goo();$$ } #if true #endif }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAfterTriviaDirective() { var markupBeforeCommit = @"class Base { public virtual void goo() { } } class Derived : Base { #if true #endif override $$ }"; var expectedCodeAfterCommit = @"class Base { public virtual void goo() { } } class Derived : Base { #if true #endif public override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WorkItem(529199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529199")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitBeforeComment() { var markupBeforeCommit = @"class Base { public virtual void goo() { } } class Derived : Base { override $$ /* comment */ }"; var expectedCodeAfterCommit = @"class Base { public virtual void goo() { } } class Derived : Base { public override void goo() { base.goo();$$ } /* comment */ }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAfterComment() { var markupBeforeCommit = @"class Base { public virtual void goo() { } } class Derived : Base { /* comment */ override $$ }"; var expectedCodeAfterCommit = @"class Base { public virtual void goo() { } } class Derived : Base { /* comment */ public override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DoNotFormatFile() { var markupBeforeCommit = @"class Program { int zip; public virtual void goo() { } } class C : Program { int bar; override $$ }"; var expectedCodeAfterCommit = @"class Program { int zip; public virtual void goo() { } } class C : Program { int bar; public override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WorkItem(736742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/736742")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AcrossPartialTypes1() { var file1 = @"partial class c { } "; var file2 = @"partial class c { override $$ } "; var csharpFileAfterCommit = @"partial class c { public override bool Equals(object obj) { return base.Equals(obj);$$ } } "; var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""CSharpDocument"">{1}</Document> <Document FilePath=""CSharpDocument2"">{2}</Document> </Project> </Workspace>", LanguageNames.CSharp, file1, file2); using var testWorkspace = TestWorkspace.Create(xmlString, exportProvider: ExportProvider); var testDocument = testWorkspace.Documents.Single(d => d.Name == "CSharpDocument2"); Contract.ThrowIfNull(testDocument.CursorPosition); var position = testDocument.CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var documentId = testWorkspace.Documents.Single(d => d.Name == "CSharpDocument2").Id; var document = solution.GetRequiredDocument(documentId); var triggerInfo = CompletionTrigger.Invoke; var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, position, triggerInfo); var completionItem = completionList.Items.First(i => CompareItems(i.DisplayText, "Equals(object obj)")); if (service.GetProvider(completionItem) is ICustomCommitCompletionProvider customCommitCompletionProvider) { var textView = testWorkspace.GetTestDocument(documentId).GetTextView(); customCommitCompletionProvider.Commit(completionItem, textView, textView.TextBuffer, textView.TextSnapshot, '\t'); var actualCodeAfterCommit = textView.TextBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = textView.Caret.Position.BufferPosition.Position; MarkupTestFile.GetPosition(csharpFileAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); } } [WorkItem(736742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/736742")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AcrossPartialTypes2() { var file1 = @"partial class c { } "; var file2 = @"partial class c { override $$ } "; var csharpFileAfterCommit = @"partial class c { public override bool Equals(object obj) { return base.Equals(obj);$$ } } "; var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""CSharpDocument"">{1}</Document> <Document FilePath=""CSharpDocument2"">{2}</Document> </Project> </Workspace>", LanguageNames.CSharp, file2, file1); using var testWorkspace = TestWorkspace.Create(xmlString, exportProvider: ExportProvider); var testDocument = testWorkspace.Documents.Single(d => d.Name == "CSharpDocument"); Contract.ThrowIfNull(testDocument.CursorPosition); var cursorPosition = testDocument.CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var documentId = testWorkspace.Documents.Single(d => d.Name == "CSharpDocument").Id; var document = solution.GetRequiredDocument(documentId); var triggerInfo = CompletionTrigger.Invoke; var service = GetCompletionService(document.Project); var completionList = await GetCompletionListAsync(service, document, cursorPosition, triggerInfo); var completionItem = completionList.Items.First(i => CompareItems(i.DisplayText, "Equals(object obj)")); if (service.GetProvider(completionItem) is ICustomCommitCompletionProvider customCommitCompletionProvider) { var textView = testWorkspace.GetTestDocument(documentId).GetTextView(); customCommitCompletionProvider.Commit(completionItem, textView, textView.TextBuffer, textView.TextSnapshot, '\t'); var actualCodeAfterCommit = textView.TextBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = textView.Caret.Position.BufferPosition.Position; MarkupTestFile.GetPosition(csharpFileAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); } } #endregion #region "EditorBrowsable should be ignored" [WpfFact] [WorkItem(545678, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545678")] [Trait(Traits.Feature, Traits.Features.Completion)] public async Task EditorBrowsable_IgnoredWhenOverridingMethods() { var markup = @" class D : B { override $$ }"; var referencedCode = @" public class B { [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public virtual void Goo() {} }"; await VerifyItemInEditorBrowsableContextsAsync( markup: markup, referencedCode: referencedCode, item: "Goo()", expectedSymbolsMetadataReference: 1, expectedSymbolsSameSolution: 1, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } #endregion [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task DuplicateMember() { var markupBeforeCommit = @"class Program { public virtual void goo() {} public virtual void goo() {} } class C : Program { override $$ }"; var expectedCodeAfterCommit = @"class Program { public virtual void goo() {} public virtual void goo() {} } class C : Program { public override void goo() { base.goo();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task LeaveTrailingTriviaAlone() { var text = @" namespace ConsoleApplication46 { class Program { static void Main(string[] args) { } override $$ } }"; using var workspace = TestWorkspace.Create(LanguageNames.CSharp, new CSharpCompilationOptions(OutputKind.ConsoleApplication), new CSharpParseOptions(), new[] { text }, ExportProvider); var provider = new OverrideCompletionProvider(); var testDocument = workspace.Documents.Single(); var document = workspace.CurrentSolution.GetRequiredDocument(testDocument.Id); var service = GetCompletionService(document.Project); Contract.ThrowIfNull(testDocument.CursorPosition); var completionList = await GetCompletionListAsync(service, document, testDocument.CursorPosition.Value, CompletionTrigger.Invoke); var oldTree = await document.GetSyntaxTreeAsync(); var commit = await provider.GetChangeAsync(document, completionList.Items.First(i => i.DisplayText == "ToString()"), ' '); var change = commit.TextChange; // If we left the trailing trivia of the close curly of Main alone, // there should only be one change: the replacement of "override " with a method. Assert.Equal(change.Span, TextSpan.FromBounds(136, 145)); } [WorkItem(8257, "https://github.com/dotnet/roslyn/issues/8257")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotImplementedQualifiedWhenSystemUsingNotPresent_Property() { var markupBeforeCommit = @"abstract class C { public abstract int goo { get; set; }; } class Program : C { override $$ }"; var expectedCodeAfterCommit = @"abstract class C { public abstract int goo { get; set; }; } class Program : C { public override int goo { get { throw new System.NotImplementedException();$$ } set { throw new System.NotImplementedException(); } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo", expectedCodeAfterCommit); } [WorkItem(8257, "https://github.com/dotnet/roslyn/issues/8257")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotImplementedQualifiedWhenSystemUsingNotPresent_Method() { var markupBeforeCommit = @"abstract class C { public abstract void goo(); } class Program : C { override $$ }"; var expectedCodeAfterCommit = @"abstract class C { public abstract void goo(); } class Program : C { public override void goo() { throw new System.NotImplementedException();$$ } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "goo()", expectedCodeAfterCommit); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task FilterOutMethodsWithNonRoundTrippableSymbolKeys() { var text = XElement.Parse(@"<Workspace> <Project Name=""P1"" Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C : ClassLibrary7.Class1 { override $$ } ]]> </Document> </Project> <Project Name=""P2"" Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document> namespace ClassLibrary2 { public class Missing {} } </Document> </Project> <Project Name=""P3"" Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3.dll""> <ProjectReference>P2</ProjectReference> <Document> namespace ClassLibrary7 { public class Class1 { public virtual void Goo(ClassLibrary2.Missing m) {} public virtual void Bar() {} } } </Document> </Project> </Workspace>"); // P3 has a project ref to Project P2 and uses the type "Missing" from P2 // as the return type of a virtual method. // P1 has a metadata reference to P3 and therefore doesn't get the transitive // reference to P2. If we try to override Goo, the missing "Missing" type will // prevent round tripping the symbolkey. using var workspace = TestWorkspace.Create(text, exportProvider: ExportProvider); var compilation = await workspace.CurrentSolution.Projects.First(p => p.Name == "P3").GetCompilationAsync(); // CompilationExtensions is in the Microsoft.CodeAnalysis.Test.Utilities namespace // which has a "Traits" type that conflicts with the one in Roslyn.Test.Utilities var reference = MetadataReference.CreateFromImage(compilation.EmitToArray()); var p1 = workspace.CurrentSolution.Projects.First(p => p.Name == "P1"); var updatedP1 = p1.AddMetadataReference(reference); workspace.ChangeSolution(updatedP1.Solution); var provider = new OverrideCompletionProvider(); var testDocument = workspace.Documents.First(d => d.Name == "CurrentDocument.cs"); var document = workspace.CurrentSolution.GetRequiredDocument(testDocument.Id); var service = GetCompletionService(document.Project); Contract.ThrowIfNull(testDocument.CursorPosition); var completionList = await GetCompletionListAsync(service, document, testDocument.CursorPosition.Value, CompletionTrigger.Invoke); Assert.True(completionList.Items.Any(c => c.DisplayText == "Bar()")); Assert.False(completionList.Items.Any(c => c.DisplayText == "Goo()")); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task TestInParameter() { var source = XElement.Parse(@"<Workspace> <Project Name=""P1"" Language=""C#"" LanguageVersion=""Latest"" CommonReferences=""true"" AssemblyName=""Proj1""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ public class SomeClass : Base { override $$ } ]]> </Document> </Project> </Workspace>"); using var workspace = TestWorkspace.Create(source, exportProvider: ExportProvider); var before = @" public abstract class Base { public abstract void M(in int x); }"; var after = @" public class SomeClass : Base { public override void M(in int x) { throw new System.NotImplementedException(); } } "; var origComp = await workspace.CurrentSolution.Projects.Single().GetRequiredCompilationAsync(CancellationToken.None); var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest); var libComp = origComp.RemoveAllSyntaxTrees().AddSyntaxTrees(CSharpSyntaxTree.ParseText(before, options: options)); var libRef = MetadataReference.CreateFromImage(libComp.EmitToArray()); var project = workspace.CurrentSolution.Projects.Single(); var updatedProject = project.AddMetadataReference(libRef); workspace.ChangeSolution(updatedProject.Solution); var provider = new OverrideCompletionProvider(); var testDocument = workspace.Documents.First(d => d.Name == "CurrentDocument.cs"); var document = workspace.CurrentSolution.GetRequiredDocument(testDocument.Id); var service = GetCompletionService(document.Project); Contract.ThrowIfNull(testDocument.CursorPosition); var completionList = await GetCompletionListAsync(service, document, testDocument.CursorPosition.Value, CompletionTrigger.Invoke); var completionItem = completionList.Items.Where(c => c.DisplayText == "M(in int x)").Single(); var commit = await service.GetChangeAsync(document, completionItem, commitKey: null, CancellationToken.None); var text = await document.GetTextAsync(); var newText = text.WithChanges(commit.TextChange); var newDoc = document.WithText(newText); document.Project.Solution.Workspace.TryApplyChanges(newDoc.Project.Solution); var textBuffer = workspace.Documents.Single().GetTextBuffer(); var actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString(); Assert.Equal(after, actualCodeAfterCommit); } [WorkItem(39909, "https://github.com/dotnet/roslyn/issues/39909")] [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task CommitAddsMissingImports() { var markupBeforeCommit = @" namespace NS1 { using NS2; public class Goo { public virtual bool Bar(Baz baz) => true; } } namespace NS2 { public class Baz {} } namespace NS3 { using NS1; class D : Goo { override $$ } }"; var expectedCodeAfterCommit = @" namespace NS1 { using NS2; public class Goo { public virtual bool Bar(Baz baz) => true; } } namespace NS2 { public class Baz {} } namespace NS3 { using NS1; using NS2; class D : Goo { public override bool Bar(Baz baz) { return base.Bar(baz);$$ } } }"; await VerifyCustomCommitProviderAsync(markupBeforeCommit, "Bar(NS2.Baz baz)", expectedCodeAfterCommit); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47941, "https://github.com/dotnet/roslyn/issues/47941")] public async Task OverrideInRecordWithoutExplicitOverriddenMember() { await VerifyItemExistsAsync(@"record Program { override $$ }", "ToString()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47941, "https://github.com/dotnet/roslyn/issues/47941")] public async Task OverrideInRecordWithExplicitOverriddenMember() { await VerifyItemIsAbsentAsync(@"record Program { public override string ToString() => ""; override $$ }", "ToString()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(47973, "https://github.com/dotnet/roslyn/issues/47973")] public async Task NoCloneInOverriddenRecord() { // Currently WellKnownMemberNames.CloneMethodName is not public, so we can't reference it directly. We // could hardcode in the value "<Clone>$", however if the compiler ever changed the name and we somehow // started showing it in completion, this test would continue to pass. So this allows us to at least go // back and explicitly validate this scenario even in that event. var cloneMemberName = (string)typeof(WellKnownMemberNames).GetField("CloneMethodName", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null); Assert.Equal("<Clone>$", cloneMemberName); await VerifyItemIsAbsentAsync(@" record Base(); record Program : Base { override $$ }", cloneMemberName); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(48640, "https://github.com/dotnet/roslyn/issues/48640")] public async Task ObjectEqualsInClass() { await VerifyItemExistsAsync(@" class Program { override $$ }", "Equals(object obj)"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(48640, "https://github.com/dotnet/roslyn/issues/48640")] public async Task NoObjectEqualsInOverriddenRecord1() { await VerifyItemIsAbsentAsync(@" record Program { override $$ }", "Equals(object obj)"); await VerifyItemExistsAsync(@" record Program { override $$ }", "ToString()"); } [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(48640, "https://github.com/dotnet/roslyn/issues/48640")] public async Task NoObjectEqualsInOverriddenRecord() { await VerifyItemIsAbsentAsync(@" record Base(); record Program : Base { override $$ }", "Equals(object obj)"); await VerifyItemExistsAsync(@" record Base(); record Program : Base { override $$ }", "ToString()"); } private Task VerifyItemExistsAsync(string markup, string expectedItem) { return VerifyItemExistsAsync(markup, expectedItem, isComplexTextEdit: true); } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/LanguageService/AbstractLanguageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService { internal abstract partial class AbstractLanguageService { public abstract Guid LanguageServiceId { get; } public abstract IServiceProvider SystemServiceProvider { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService { internal abstract partial class AbstractLanguageService { public abstract Guid LanguageServiceId { get; } public abstract IServiceProvider SystemServiceProvider { get; } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Scripting/CoreTestUtilities/ObjectFormatterFixtures/MockDesktopTask.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.Threading.Tasks; namespace ObjectFormatterFixtures { /// <summary> /// Follows the shape of the Desktop version of <see cref="Task"/> relevant for debugger display. /// </summary> [DebuggerTypeProxy(typeof(MockTaskProxy))] [DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}")] internal class MockDesktopTask { private readonly Action m_action; public MockDesktopTask(Action action) { m_action = action; } public int Id => 1234; public object AsyncState => null; public TaskCreationOptions CreationOptions => TaskCreationOptions.None; public Exception Exception => null; public TaskStatus Status => TaskStatus.Created; private string DebuggerDisplayMethodDescription => m_action.Method.ToString(); } internal class MockTaskProxy { private readonly MockDesktopTask m_task; public object AsyncState => m_task.AsyncState; public TaskCreationOptions CreationOptions => m_task.CreationOptions; public Exception Exception => m_task.Exception; public int Id => m_task.Id; public bool CancellationPending => false; public TaskStatus Status => m_task.Status; public MockTaskProxy(MockDesktopTask task) { m_task = task; } } }
// Licensed to the .NET Foundation under one or more 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.Threading.Tasks; namespace ObjectFormatterFixtures { /// <summary> /// Follows the shape of the Desktop version of <see cref="Task"/> relevant for debugger display. /// </summary> [DebuggerTypeProxy(typeof(MockTaskProxy))] [DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}")] internal class MockDesktopTask { private readonly Action m_action; public MockDesktopTask(Action action) { m_action = action; } public int Id => 1234; public object AsyncState => null; public TaskCreationOptions CreationOptions => TaskCreationOptions.None; public Exception Exception => null; public TaskStatus Status => TaskStatus.Created; private string DebuggerDisplayMethodDescription => m_action.Method.ToString(); } internal class MockTaskProxy { private readonly MockDesktopTask m_task; public object AsyncState => m_task.AsyncState; public TaskCreationOptions CreationOptions => m_task.CreationOptions; public Exception Exception => m_task.Exception; public int Id => m_task.Id; public bool CancellationPending => false; public TaskStatus Status => m_task.Status; public MockTaskProxy(MockDesktopTask task) { m_task = task; } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/CodeAnalysisTest/GivesAccessTo.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class GivesAccessTo { [Fact, WorkItem(26459, "https://github.com/dotnet/roslyn/issues/26459")] public void TestGivesAccessTo_CrossLanguageAndCompilation() { var csharpTree = CSharpSyntaxTree.ParseText(@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""VB"")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""CS2"")] internal class CS { } "); var csharpTree2 = CSharpSyntaxTree.ParseText(@" internal class CS2 { } "); var vbTree = VisualBasicSyntaxTree.ParseText(@" <assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""CS"")> <assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""VB2"")> Friend Class VB End Class "); var vbTree2 = VisualBasicSyntaxTree.ParseText(@" Friend Class VB2 End Class "); var csc = (Compilation)CSharpCompilation.Create("CS", new[] { csharpTree }, new MetadataReference[] { TestBase.MscorlibRef }); var CS = csc.GlobalNamespace.GetMembers("CS").First() as INamedTypeSymbol; var csc2 = (Compilation)CSharpCompilation.Create("CS2", new[] { csharpTree2 }, new MetadataReference[] { TestBase.MscorlibRef }); var CS2 = csc2.GlobalNamespace.GetMembers("CS2").First() as INamedTypeSymbol; var vbc = VisualBasicCompilation.Create("VB", new[] { vbTree }, new MetadataReference[] { TestBase.MscorlibRef }); var VB = vbc.GlobalNamespace.GetMembers("VB")[0] as INamedTypeSymbol; var vbc2 = VisualBasicCompilation.Create("VB2", new[] { vbTree2 }, new MetadataReference[] { TestBase.MscorlibRef }); var VB2 = vbc2.GlobalNamespace.GetMembers("VB2")[0] as INamedTypeSymbol; Assert.True(CS.ContainingAssembly.GivesAccessTo(CS2.ContainingAssembly)); Assert.True(CS.ContainingAssembly.GivesAccessTo(VB.ContainingAssembly)); Assert.False(CS.ContainingAssembly.GivesAccessTo(VB2.ContainingAssembly)); Assert.True(VB.ContainingAssembly.GivesAccessTo(VB2.ContainingAssembly)); Assert.True(VB.ContainingAssembly.GivesAccessTo(CS.ContainingAssembly)); Assert.False(VB.ContainingAssembly.GivesAccessTo(CS2.ContainingAssembly)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public class GivesAccessTo { [Fact, WorkItem(26459, "https://github.com/dotnet/roslyn/issues/26459")] public void TestGivesAccessTo_CrossLanguageAndCompilation() { var csharpTree = CSharpSyntaxTree.ParseText(@" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""VB"")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""CS2"")] internal class CS { } "); var csharpTree2 = CSharpSyntaxTree.ParseText(@" internal class CS2 { } "); var vbTree = VisualBasicSyntaxTree.ParseText(@" <assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""CS"")> <assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""VB2"")> Friend Class VB End Class "); var vbTree2 = VisualBasicSyntaxTree.ParseText(@" Friend Class VB2 End Class "); var csc = (Compilation)CSharpCompilation.Create("CS", new[] { csharpTree }, new MetadataReference[] { TestBase.MscorlibRef }); var CS = csc.GlobalNamespace.GetMembers("CS").First() as INamedTypeSymbol; var csc2 = (Compilation)CSharpCompilation.Create("CS2", new[] { csharpTree2 }, new MetadataReference[] { TestBase.MscorlibRef }); var CS2 = csc2.GlobalNamespace.GetMembers("CS2").First() as INamedTypeSymbol; var vbc = VisualBasicCompilation.Create("VB", new[] { vbTree }, new MetadataReference[] { TestBase.MscorlibRef }); var VB = vbc.GlobalNamespace.GetMembers("VB")[0] as INamedTypeSymbol; var vbc2 = VisualBasicCompilation.Create("VB2", new[] { vbTree2 }, new MetadataReference[] { TestBase.MscorlibRef }); var VB2 = vbc2.GlobalNamespace.GetMembers("VB2")[0] as INamedTypeSymbol; Assert.True(CS.ContainingAssembly.GivesAccessTo(CS2.ContainingAssembly)); Assert.True(CS.ContainingAssembly.GivesAccessTo(VB.ContainingAssembly)); Assert.False(CS.ContainingAssembly.GivesAccessTo(VB2.ContainingAssembly)); Assert.True(VB.ContainingAssembly.GivesAccessTo(VB2.ContainingAssembly)); Assert.True(VB.ContainingAssembly.GivesAccessTo(CS.ContainingAssembly)); Assert.False(VB.ContainingAssembly.GivesAccessTo(CS2.ContainingAssembly)); } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/CSharpTest/Structure/AbstractCSharpSyntaxNodeStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.UnitTests.Structure; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public abstract class AbstractCSharpSyntaxNodeStructureTests<TSyntaxNode> : AbstractSyntaxNodeStructureProviderTests<TSyntaxNode> where TSyntaxNode : SyntaxNode { protected sealed override string LanguageName => LanguageNames.CSharp; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Editor.UnitTests.Structure; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure { public abstract class AbstractCSharpSyntaxNodeStructureTests<TSyntaxNode> : AbstractSyntaxNodeStructureProviderTests<TSyntaxNode> where TSyntaxNode : SyntaxNode { protected sealed override string LanguageName => LanguageNames.CSharp; } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/TestUtilities/Utilities/TestEditorOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities { /// <summary> /// Mock object for editor options. /// not sure why, but Moq throw Null exception when DefaultOptions.StaticXXXField is used in Moq /// </summary> public class TestEditorOptions : IEditorOptions { public static IEditorOptions Instance = new TestEditorOptions(); private readonly bool _convertTabsToSpaces; private readonly int _tabSize; private readonly int _indentSize; public TestEditorOptions() { _convertTabsToSpaces = true; _tabSize = 4; _indentSize = 4; } public TestEditorOptions(bool convertTabsToSpaces, int tabSize, int indentSize) { _convertTabsToSpaces = convertTabsToSpaces; _tabSize = tabSize; _indentSize = indentSize; } public T GetOptionValue<T>(EditorOptionKey<T> key) { if (key.Equals(DefaultOptions.ConvertTabsToSpacesOptionId)) { return (T)(object)_convertTabsToSpaces; } else if (key.Equals(DefaultOptions.TabSizeOptionId)) { return (T)(object)_tabSize; } else if (key.Equals(DefaultOptions.IndentSizeOptionId)) { return (T)(object)_indentSize; } throw new ArgumentException("key", "unexpected key"); } #region not implemented public bool ClearOptionValue<T>(EditorOptionKey<T> key) => throw new NotImplementedException(); public bool ClearOptionValue(string optionId) => throw new NotImplementedException(); public object GetOptionValue(string optionId) => throw new NotImplementedException(); public T GetOptionValue<T>(string optionId) => throw new NotImplementedException(); public IEditorOptions GlobalOptions { get { throw new NotImplementedException(); } } public bool IsOptionDefined<T>(EditorOptionKey<T> key, bool localScopeOnly) => throw new NotImplementedException(); public bool IsOptionDefined(string optionId, bool localScopeOnly) => throw new NotImplementedException(); #pragma warning disable 67 public event EventHandler<EditorOptionChangedEventArgs> OptionChanged; public IEditorOptions Parent { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public void SetOptionValue<T>(EditorOptionKey<T> key, T value) => throw new NotImplementedException(); public void SetOptionValue(string optionId, object value) => throw new NotImplementedException(); public System.Collections.Generic.IEnumerable<EditorOptionDefinition> SupportedOptions { get { throw new NotImplementedException(); } } #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.Text; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Utilities { /// <summary> /// Mock object for editor options. /// not sure why, but Moq throw Null exception when DefaultOptions.StaticXXXField is used in Moq /// </summary> public class TestEditorOptions : IEditorOptions { public static IEditorOptions Instance = new TestEditorOptions(); private readonly bool _convertTabsToSpaces; private readonly int _tabSize; private readonly int _indentSize; public TestEditorOptions() { _convertTabsToSpaces = true; _tabSize = 4; _indentSize = 4; } public TestEditorOptions(bool convertTabsToSpaces, int tabSize, int indentSize) { _convertTabsToSpaces = convertTabsToSpaces; _tabSize = tabSize; _indentSize = indentSize; } public T GetOptionValue<T>(EditorOptionKey<T> key) { if (key.Equals(DefaultOptions.ConvertTabsToSpacesOptionId)) { return (T)(object)_convertTabsToSpaces; } else if (key.Equals(DefaultOptions.TabSizeOptionId)) { return (T)(object)_tabSize; } else if (key.Equals(DefaultOptions.IndentSizeOptionId)) { return (T)(object)_indentSize; } throw new ArgumentException("key", "unexpected key"); } #region not implemented public bool ClearOptionValue<T>(EditorOptionKey<T> key) => throw new NotImplementedException(); public bool ClearOptionValue(string optionId) => throw new NotImplementedException(); public object GetOptionValue(string optionId) => throw new NotImplementedException(); public T GetOptionValue<T>(string optionId) => throw new NotImplementedException(); public IEditorOptions GlobalOptions { get { throw new NotImplementedException(); } } public bool IsOptionDefined<T>(EditorOptionKey<T> key, bool localScopeOnly) => throw new NotImplementedException(); public bool IsOptionDefined(string optionId, bool localScopeOnly) => throw new NotImplementedException(); #pragma warning disable 67 public event EventHandler<EditorOptionChangedEventArgs> OptionChanged; public IEditorOptions Parent { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public void SetOptionValue<T>(EditorOptionKey<T> key, T value) => throw new NotImplementedException(); public void SetOptionValue(string optionId, object value) => throw new NotImplementedException(); public System.Collections.Generic.IEnumerable<EditorOptionDefinition> SupportedOptions { get { throw new NotImplementedException(); } } #endregion } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/ProjectFileLoaderRegistry.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.IO; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MSBuild { internal class ProjectFileLoaderRegistry { private readonly HostWorkspaceServices _workspaceServices; private readonly DiagnosticReporter _diagnosticReporter; private readonly Dictionary<string, string> _extensionToLanguageMap; private readonly NonReentrantLock _dataGuard; public ProjectFileLoaderRegistry(HostWorkspaceServices workspaceServices, DiagnosticReporter diagnosticReporter) { _workspaceServices = workspaceServices; _diagnosticReporter = diagnosticReporter; _extensionToLanguageMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); _dataGuard = new NonReentrantLock(); } /// <summary> /// Associates a project file extension with a language name. /// </summary> public void AssociateFileExtensionWithLanguage(string fileExtension, string language) { using (_dataGuard.DisposableWait()) { _extensionToLanguageMap[fileExtension] = language; } } public bool TryGetLoaderFromProjectPath(string? projectFilePath, [NotNullWhen(true)] out IProjectFileLoader? loader) { return TryGetLoaderFromProjectPath(projectFilePath, DiagnosticReportingMode.Ignore, out loader); } public bool TryGetLoaderFromProjectPath(string? projectFilePath, DiagnosticReportingMode mode, [NotNullWhen(true)] out IProjectFileLoader? loader) { using (_dataGuard.DisposableWait()) { var extension = Path.GetExtension(projectFilePath); if (extension is null) { loader = null; _diagnosticReporter.Report(mode, $"Project file path was 'null'"); return false; } if (extension.Length > 0 && extension[0] == '.') { extension = extension[1..]; } if (_extensionToLanguageMap.TryGetValue(extension, out var language)) { if (_workspaceServices.SupportedLanguages.Contains(language)) { loader = _workspaceServices.GetLanguageServices(language).GetService<IProjectFileLoader>(); } else { loader = null; _diagnosticReporter.Report(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projectFilePath, language)); return false; } } else { loader = ProjectFileLoader.GetLoaderForProjectFileExtension(_workspaceServices, extension); if (loader == null) { _diagnosticReporter.Report(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projectFilePath, Path.GetExtension(projectFilePath))); return false; } } // since we have both C# and VB loaders in this same library, it no longer indicates whether we have full language support available. if (loader != null) { language = loader.Language; // check for command line parser existing... if not then error. var commandLineParser = _workspaceServices .GetLanguageServices(language) .GetService<ICommandLineParserService>(); if (commandLineParser == null) { loader = null; _diagnosticReporter.Report(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projectFilePath, language)); return false; } } return loader != 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.Diagnostics.CodeAnalysis; using System.IO; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MSBuild { internal class ProjectFileLoaderRegistry { private readonly HostWorkspaceServices _workspaceServices; private readonly DiagnosticReporter _diagnosticReporter; private readonly Dictionary<string, string> _extensionToLanguageMap; private readonly NonReentrantLock _dataGuard; public ProjectFileLoaderRegistry(HostWorkspaceServices workspaceServices, DiagnosticReporter diagnosticReporter) { _workspaceServices = workspaceServices; _diagnosticReporter = diagnosticReporter; _extensionToLanguageMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); _dataGuard = new NonReentrantLock(); } /// <summary> /// Associates a project file extension with a language name. /// </summary> public void AssociateFileExtensionWithLanguage(string fileExtension, string language) { using (_dataGuard.DisposableWait()) { _extensionToLanguageMap[fileExtension] = language; } } public bool TryGetLoaderFromProjectPath(string? projectFilePath, [NotNullWhen(true)] out IProjectFileLoader? loader) { return TryGetLoaderFromProjectPath(projectFilePath, DiagnosticReportingMode.Ignore, out loader); } public bool TryGetLoaderFromProjectPath(string? projectFilePath, DiagnosticReportingMode mode, [NotNullWhen(true)] out IProjectFileLoader? loader) { using (_dataGuard.DisposableWait()) { var extension = Path.GetExtension(projectFilePath); if (extension is null) { loader = null; _diagnosticReporter.Report(mode, $"Project file path was 'null'"); return false; } if (extension.Length > 0 && extension[0] == '.') { extension = extension[1..]; } if (_extensionToLanguageMap.TryGetValue(extension, out var language)) { if (_workspaceServices.SupportedLanguages.Contains(language)) { loader = _workspaceServices.GetLanguageServices(language).GetService<IProjectFileLoader>(); } else { loader = null; _diagnosticReporter.Report(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projectFilePath, language)); return false; } } else { loader = ProjectFileLoader.GetLoaderForProjectFileExtension(_workspaceServices, extension); if (loader == null) { _diagnosticReporter.Report(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projectFilePath, Path.GetExtension(projectFilePath))); return false; } } // since we have both C# and VB loaders in this same library, it no longer indicates whether we have full language support available. if (loader != null) { language = loader.Language; // check for command line parser existing... if not then error. var commandLineParser = _workspaceServices .GetLanguageServices(language) .GetService<ICommandLineParserService>(); if (commandLineParser == null) { loader = null; _diagnosticReporter.Report(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projectFilePath, language)); return false; } } return loader != null; } } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core.Wpf/NavigableSymbols/NavigableSymbolService.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.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.NavigableSymbols { [Export(typeof(INavigableSymbolSourceProvider))] [Name(nameof(NavigableSymbolService))] [ContentType(ContentTypeNames.RoslynContentType)] internal partial class NavigableSymbolService : INavigableSymbolSourceProvider { private static readonly object s_key = new(); private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly IThreadingContext _threadingContext; private readonly IStreamingFindUsagesPresenter _streamingPresenter; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public NavigableSymbolService( IUIThreadOperationExecutor uiThreadOperationExecutor, IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter) { _uiThreadOperationExecutor = uiThreadOperationExecutor; _threadingContext = threadingContext; _streamingPresenter = streamingPresenter; } public INavigableSymbolSource TryCreateNavigableSymbolSource(ITextView textView, ITextBuffer buffer) { return textView.GetOrCreatePerSubjectBufferProperty(buffer, s_key, (v, b) => new NavigableSymbolSource(_threadingContext, _streamingPresenter, _uiThreadOperationExecutor)); } } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.NavigableSymbols { [Export(typeof(INavigableSymbolSourceProvider))] [Name(nameof(NavigableSymbolService))] [ContentType(ContentTypeNames.RoslynContentType)] internal partial class NavigableSymbolService : INavigableSymbolSourceProvider { private static readonly object s_key = new(); private readonly IUIThreadOperationExecutor _uiThreadOperationExecutor; private readonly IThreadingContext _threadingContext; private readonly IStreamingFindUsagesPresenter _streamingPresenter; [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public NavigableSymbolService( IUIThreadOperationExecutor uiThreadOperationExecutor, IThreadingContext threadingContext, IStreamingFindUsagesPresenter streamingPresenter) { _uiThreadOperationExecutor = uiThreadOperationExecutor; _threadingContext = threadingContext; _streamingPresenter = streamingPresenter; } public INavigableSymbolSource TryCreateNavigableSymbolSource(ITextView textView, ITextBuffer buffer) { return textView.GetOrCreatePerSubjectBufferProperty(buffer, s_key, (v, b) => new NavigableSymbolSource(_threadingContext, _streamingPresenter, _uiThreadOperationExecutor)); } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Impl/CodeModel/MethodXml/BinaryOperatorKind.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.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal enum BinaryOperatorKind { None, AddDelegate, BitwiseAnd, BitwiseOr, Concatenate, Plus } }
// Licensed to the .NET Foundation under one or more 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.VisualStudio.LanguageServices.Implementation.CodeModel.MethodXml { internal enum BinaryOperatorKind { None, AddDelegate, BitwiseAnd, BitwiseOr, Concatenate, Plus } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/RegexDocumentHighlightsService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.EmbeddedLanguages.Common; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions { using RegexToken = EmbeddedSyntaxToken<RegexKind>; internal sealed class RegexDocumentHighlightsService : IDocumentHighlightsService { private readonly RegexEmbeddedLanguage _language; public RegexDocumentHighlightsService(RegexEmbeddedLanguage language) => _language = language; public async Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { var option = document.Project.Solution.Workspace.Options.GetOption(RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, document.Project.Language); if (!option) { return default; } var tree = await _language.TryGetTreeAtPositionAsync(document, position, cancellationToken).ConfigureAwait(false); return tree == null ? default : ImmutableArray.Create(new DocumentHighlights(document, GetHighlights(tree, position))); } private ImmutableArray<HighlightSpan> GetHighlights(RegexTree tree, int positionInDocument) { var referencesOnTheRight = GetReferences(tree, positionInDocument); if (!referencesOnTheRight.IsEmpty) { return referencesOnTheRight; } if (positionInDocument == 0) { return default; } // Nothing was on the right of the caret. Return anything we were able to find on // the left of the caret. var referencesOnTheLeft = GetReferences(tree, positionInDocument - 1); return referencesOnTheLeft; } private ImmutableArray<HighlightSpan> GetReferences(RegexTree tree, int position) { var virtualChar = tree.Text.FirstOrNull(vc => vc.Span.Contains(position)); if (virtualChar == null) { return ImmutableArray<HighlightSpan>.Empty; } var ch = virtualChar.Value; return FindReferenceHighlights(tree, ch); } private ImmutableArray<HighlightSpan> FindReferenceHighlights(RegexTree tree, VirtualChar ch) { var node = FindReferenceNode(tree.Root, ch); if (node == null) { return ImmutableArray<HighlightSpan>.Empty; } var captureToken = GetCaptureToken(node); if (captureToken.Kind == RegexKind.NumberToken) { var val = (int)captureToken.Value; if (tree.CaptureNumbersToSpan.TryGetValue(val, out var captureSpan)) { return CreateHighlights(node, captureSpan); } } else { var val = (string)captureToken.Value; if (tree.CaptureNamesToSpan.TryGetValue(val, out var captureSpan)) { return CreateHighlights(node, captureSpan); } } return ImmutableArray<HighlightSpan>.Empty; } private static ImmutableArray<HighlightSpan> CreateHighlights( RegexEscapeNode node, TextSpan captureSpan) { return ImmutableArray.Create(CreateHighlightSpan(node.GetSpan()), CreateHighlightSpan(captureSpan)); } private static HighlightSpan CreateHighlightSpan(TextSpan textSpan) => new(textSpan, HighlightSpanKind.None); private static RegexToken GetCaptureToken(RegexEscapeNode node) => node switch { RegexBackreferenceEscapeNode backReference => backReference.NumberToken, RegexCaptureEscapeNode captureEscape => captureEscape.CaptureToken, RegexKCaptureEscapeNode kCaptureEscape => kCaptureEscape.CaptureToken, _ => throw new InvalidOperationException(), }; private RegexEscapeNode FindReferenceNode(RegexNode node, VirtualChar virtualChar) { if (node.Kind is RegexKind.BackreferenceEscape or RegexKind.CaptureEscape or RegexKind.KCaptureEscape) { if (node.Contains(virtualChar)) { return (RegexEscapeNode)node; } } foreach (var child in node) { if (child.IsNode) { var result = FindReferenceNode(child.Node, virtualChar); if (result != null) { return result; } } } 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. #nullable disable using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.EmbeddedLanguages.Common; using Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions; using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages.RegularExpressions { using RegexToken = EmbeddedSyntaxToken<RegexKind>; internal sealed class RegexDocumentHighlightsService : IDocumentHighlightsService { private readonly RegexEmbeddedLanguage _language; public RegexDocumentHighlightsService(RegexEmbeddedLanguage language) => _language = language; public async Task<ImmutableArray<DocumentHighlights>> GetDocumentHighlightsAsync( Document document, int position, IImmutableSet<Document> documentsToSearch, CancellationToken cancellationToken) { var option = document.Project.Solution.Workspace.Options.GetOption(RegularExpressionsOptions.HighlightRelatedRegexComponentsUnderCursor, document.Project.Language); if (!option) { return default; } var tree = await _language.TryGetTreeAtPositionAsync(document, position, cancellationToken).ConfigureAwait(false); return tree == null ? default : ImmutableArray.Create(new DocumentHighlights(document, GetHighlights(tree, position))); } private ImmutableArray<HighlightSpan> GetHighlights(RegexTree tree, int positionInDocument) { var referencesOnTheRight = GetReferences(tree, positionInDocument); if (!referencesOnTheRight.IsEmpty) { return referencesOnTheRight; } if (positionInDocument == 0) { return default; } // Nothing was on the right of the caret. Return anything we were able to find on // the left of the caret. var referencesOnTheLeft = GetReferences(tree, positionInDocument - 1); return referencesOnTheLeft; } private ImmutableArray<HighlightSpan> GetReferences(RegexTree tree, int position) { var virtualChar = tree.Text.FirstOrNull(vc => vc.Span.Contains(position)); if (virtualChar == null) { return ImmutableArray<HighlightSpan>.Empty; } var ch = virtualChar.Value; return FindReferenceHighlights(tree, ch); } private ImmutableArray<HighlightSpan> FindReferenceHighlights(RegexTree tree, VirtualChar ch) { var node = FindReferenceNode(tree.Root, ch); if (node == null) { return ImmutableArray<HighlightSpan>.Empty; } var captureToken = GetCaptureToken(node); if (captureToken.Kind == RegexKind.NumberToken) { var val = (int)captureToken.Value; if (tree.CaptureNumbersToSpan.TryGetValue(val, out var captureSpan)) { return CreateHighlights(node, captureSpan); } } else { var val = (string)captureToken.Value; if (tree.CaptureNamesToSpan.TryGetValue(val, out var captureSpan)) { return CreateHighlights(node, captureSpan); } } return ImmutableArray<HighlightSpan>.Empty; } private static ImmutableArray<HighlightSpan> CreateHighlights( RegexEscapeNode node, TextSpan captureSpan) { return ImmutableArray.Create(CreateHighlightSpan(node.GetSpan()), CreateHighlightSpan(captureSpan)); } private static HighlightSpan CreateHighlightSpan(TextSpan textSpan) => new(textSpan, HighlightSpanKind.None); private static RegexToken GetCaptureToken(RegexEscapeNode node) => node switch { RegexBackreferenceEscapeNode backReference => backReference.NumberToken, RegexCaptureEscapeNode captureEscape => captureEscape.CaptureToken, RegexKCaptureEscapeNode kCaptureEscape => kCaptureEscape.CaptureToken, _ => throw new InvalidOperationException(), }; private RegexEscapeNode FindReferenceNode(RegexNode node, VirtualChar virtualChar) { if (node.Kind is RegexKind.BackreferenceEscape or RegexKind.CaptureEscape or RegexKind.KCaptureEscape) { if (node.Contains(virtualChar)) { return (RegexEscapeNode)node; } } foreach (var child in node) { if (child.IsNode) { var result = FindReferenceNode(child.Node, virtualChar); if (result != null) { return result; } } } return null; } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/AnalyzerDependency/IBindingRedirectionService.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; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal interface IBindingRedirectionService { AssemblyIdentity ApplyBindingRedirects(AssemblyIdentity originalIdentity); } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.VisualStudio.LanguageServices.Implementation { internal interface IBindingRedirectionService { AssemblyIdentity ApplyBindingRedirects(AssemblyIdentity originalIdentity); } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Lsif/Generator/Utilities.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.LanguageServerIndexFormat.Generator { internal static class Utilities { public static string ToDisplayString(this TimeSpan timeSpan) { return timeSpan.TotalSeconds.ToString("N2") + " seconds"; } } }
// Licensed to the .NET Foundation under one or more 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.LanguageServerIndexFormat.Generator { internal static class Utilities { public static string ToDisplayString(this TimeSpan timeSpan) { return timeSpan.TotalSeconds.ToString("N2") + " seconds"; } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/TestUtilities/TodoComments/AbtractTodoCommentTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Implementation.TodoComments; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.CodeAnalysis.TodoComments; using Microsoft.CodeAnalysis.UnitTests; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities.TodoComments { public abstract class AbstractTodoCommentTests { protected const string DefaultTokenList = "HACK:1|TODO:1|UNDONE:1|UnresolvedMergeConflict:0"; protected abstract TestWorkspace CreateWorkspace(string codeWithMarker); protected async Task TestAsync(string codeWithMarker) { using var workspace = CreateWorkspace(codeWithMarker); var hostDocument = workspace.Documents.First(); var initialTextSnapshot = hostDocument.GetTextBuffer().CurrentSnapshot; var documentId = hostDocument.Id; var document = workspace.CurrentSolution.GetDocument(documentId); var service = document.GetLanguageService<ITodoCommentService>(); var todoComments = await service.GetTodoCommentsAsync(document, TodoCommentDescriptor.Parse(workspace.Options.GetOption(TodoCommentOptions.TokenList)), CancellationToken.None); using var _ = ArrayBuilder<TodoCommentData>.GetInstance(out var converted); await TodoComment.ConvertAsync(document, todoComments, converted, CancellationToken.None); var expectedLists = hostDocument.SelectedSpans; Assert.Equal(converted.Count, expectedLists.Count); var sourceText = await document.GetTextAsync(); var tree = await document.GetSyntaxTreeAsync(); for (var i = 0; i < converted.Count; i++) { var todo = converted[i]; var span = expectedLists[i]; var line = initialTextSnapshot.GetLineFromPosition(span.Start); var text = initialTextSnapshot.GetText(span.ToSpan()); Assert.Equal(todo.MappedLine, line.LineNumber); Assert.Equal(todo.MappedColumn, span.Start - line.Start); Assert.Equal(todo.Message, text); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.CodeAnalysis.Editor.Implementation.TodoComments; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.CodeAnalysis.TodoComments; using Microsoft.CodeAnalysis.UnitTests; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Test.Utilities.TodoComments { public abstract class AbstractTodoCommentTests { protected const string DefaultTokenList = "HACK:1|TODO:1|UNDONE:1|UnresolvedMergeConflict:0"; protected abstract TestWorkspace CreateWorkspace(string codeWithMarker); protected async Task TestAsync(string codeWithMarker) { using var workspace = CreateWorkspace(codeWithMarker); var hostDocument = workspace.Documents.First(); var initialTextSnapshot = hostDocument.GetTextBuffer().CurrentSnapshot; var documentId = hostDocument.Id; var document = workspace.CurrentSolution.GetDocument(documentId); var service = document.GetLanguageService<ITodoCommentService>(); var todoComments = await service.GetTodoCommentsAsync(document, TodoCommentDescriptor.Parse(workspace.Options.GetOption(TodoCommentOptions.TokenList)), CancellationToken.None); using var _ = ArrayBuilder<TodoCommentData>.GetInstance(out var converted); await TodoComment.ConvertAsync(document, todoComments, converted, CancellationToken.None); var expectedLists = hostDocument.SelectedSpans; Assert.Equal(converted.Count, expectedLists.Count); var sourceText = await document.GetTextAsync(); var tree = await document.GetSyntaxTreeAsync(); for (var i = 0; i < converted.Count; i++) { var todo = converted[i]; var span = expectedLists[i]; var line = initialTextSnapshot.GetLineFromPosition(span.Start); var text = initialTextSnapshot.GetText(span.ToSpan()); Assert.Equal(todo.MappedLine, line.LineNumber); Assert.Equal(todo.MappedColumn, span.Start - line.Start); Assert.Equal(todo.Message, text); } } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/MetadataReference/ModuleMetadata.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents an immutable snapshot of module CLI metadata. /// </summary> /// <remarks>This object may allocate significant resources or lock files depending upon how it is constructed.</remarks> public sealed partial class ModuleMetadata : Metadata { private bool _isDisposed; private readonly PEModule _module; private ModuleMetadata(PEReader peReader) : base(isImageOwner: true, id: MetadataId.CreateNewId()) { _module = new PEModule(this, peReader: peReader, metadataOpt: IntPtr.Zero, metadataSizeOpt: 0, includeEmbeddedInteropTypes: false, ignoreAssemblyRefs: false); } private ModuleMetadata(IntPtr metadata, int size, bool includeEmbeddedInteropTypes, bool ignoreAssemblyRefs) : base(isImageOwner: true, id: MetadataId.CreateNewId()) { _module = new PEModule(this, peReader: null, metadataOpt: metadata, metadataSizeOpt: size, includeEmbeddedInteropTypes: includeEmbeddedInteropTypes, ignoreAssemblyRefs: ignoreAssemblyRefs); } // creates a copy private ModuleMetadata(ModuleMetadata metadata) : base(isImageOwner: false, id: metadata.Id) { _module = metadata.Module; } /// <summary> /// Create metadata module from a raw memory pointer to metadata directory of a PE image or .cormeta section of an object file. /// Only manifest modules are currently supported. /// </summary> /// <param name="metadata">Pointer to the start of metadata block.</param> /// <param name="size">The size of the metadata block.</param> /// <exception cref="ArgumentNullException"><paramref name="metadata"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="size"/> is not positive.</exception> public static ModuleMetadata CreateFromMetadata(IntPtr metadata, int size) { if (metadata == IntPtr.Zero) { throw new ArgumentNullException(nameof(metadata)); } if (size <= 0) { throw new ArgumentOutOfRangeException(CodeAnalysisResources.SizeHasToBePositive, nameof(size)); } return new ModuleMetadata(metadata, size, includeEmbeddedInteropTypes: false, ignoreAssemblyRefs: false); } internal static ModuleMetadata CreateFromMetadata(IntPtr metadata, int size, bool includeEmbeddedInteropTypes, bool ignoreAssemblyRefs = false) { Debug.Assert(metadata != IntPtr.Zero); Debug.Assert(size > 0); return new ModuleMetadata(metadata, size, includeEmbeddedInteropTypes, ignoreAssemblyRefs); } /// <summary> /// Create metadata module from a raw memory pointer to a PE image or an object file. /// </summary> /// <param name="peImage">Pointer to the DOS header ("MZ") of a portable executable image.</param> /// <param name="size">The size of the image pointed to by <paramref name="peImage"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="size"/> is not positive.</exception> public static unsafe ModuleMetadata CreateFromImage(IntPtr peImage, int size) { if (peImage == IntPtr.Zero) { throw new ArgumentNullException(nameof(peImage)); } if (size <= 0) { throw new ArgumentOutOfRangeException(CodeAnalysisResources.SizeHasToBePositive, nameof(size)); } return new ModuleMetadata(new PEReader((byte*)peImage, size)); } /// <summary> /// Create metadata module from a sequence of bytes. /// </summary> /// <param name="peImage">The portable executable image beginning with the DOS header ("MZ").</param> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception> public static ModuleMetadata CreateFromImage(IEnumerable<byte> peImage) { if (peImage == null) { throw new ArgumentNullException(nameof(peImage)); } return CreateFromImage(ImmutableArray.CreateRange(peImage)); } /// <summary> /// Create metadata module from a byte array. /// </summary> /// <param name="peImage">Portable executable image beginning with the DOS header ("MZ").</param> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception> public static ModuleMetadata CreateFromImage(ImmutableArray<byte> peImage) { if (peImage.IsDefault) { throw new ArgumentNullException(nameof(peImage)); } return new ModuleMetadata(new PEReader(peImage)); } /// <summary> /// Create metadata module from a stream. /// </summary> /// <param name="peStream">Stream containing portable executable image. Position zero should contain the first byte of the DOS header ("MZ").</param> /// <param name="leaveOpen"> /// False to close the stream upon disposal of the metadata (the responsibility for disposal of the stream is transferred upon entry of the constructor /// unless the arguments given are invalid). /// </param> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> public static ModuleMetadata CreateFromStream(Stream peStream, bool leaveOpen = false) { return CreateFromStream(peStream, leaveOpen ? PEStreamOptions.LeaveOpen : PEStreamOptions.Default); } /// <summary> /// Create metadata module from a stream. /// </summary> /// <param name="peStream">Stream containing portable executable image. Position zero should contain the first byte of the DOS header ("MZ").</param> /// <param name="options"> /// Options specifying how sections of the PE image are read from the stream. /// Unless <see cref="PEStreamOptions.LeaveOpen"/> is specified, the responsibility for disposal of the stream is transferred upon entry of the constructor /// unless the arguments given are invalid. /// </param> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="ArgumentException">The stream doesn't support read and seek operations.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="options"/> has an invalid value.</exception> /// <exception cref="BadImageFormatException"> /// <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/> is specified and the PE headers of the image are invalid. /// </exception> /// <exception cref="IOException"> /// <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/> is specified and an error occurs while reading the stream. /// </exception> public static ModuleMetadata CreateFromStream(Stream peStream, PEStreamOptions options) { if (peStream == null) { throw new ArgumentNullException(nameof(peStream)); } if (!peStream.CanRead || !peStream.CanSeek) { throw new ArgumentException(CodeAnalysisResources.StreamMustSupportReadAndSeek, nameof(peStream)); } // Workaround of issue https://github.com/dotnet/corefx/issues/1815: if (peStream.Length == 0 && (options & PEStreamOptions.PrefetchEntireImage) != 0 && (options & PEStreamOptions.PrefetchMetadata) != 0) { // throws BadImageFormatException: new PEHeaders(peStream); } // ownership of the stream is passed on PEReader: return new ModuleMetadata(new PEReader(peStream, options)); } /// <summary> /// Creates metadata module from a file containing a portable executable image. /// </summary> /// <param name="path">File path.</param> /// <remarks> /// The file might remain mapped (and read-locked) until this object is disposed. /// The memory map is only created for large files. Small files are read into memory. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="path"/> is invalid.</exception> /// <exception cref="IOException">Error opening file <paramref name="path"/>. See <see cref="Exception.InnerException"/> for details.</exception> /// <exception cref="FileNotFoundException">File <paramref name="path"/> not found.</exception> /// <exception cref="NotSupportedException">Reading from a file path is not supported by the platform.</exception> public static ModuleMetadata CreateFromFile(string path) { return CreateFromStream(StandardFileSystem.Instance.OpenFileWithNormalizedException(path, FileMode.Open, FileAccess.Read, FileShare.Read)); } /// <summary> /// Creates a shallow copy of this object. /// </summary> /// <remarks> /// The resulting copy shares the metadata image and metadata information read from it with the original. /// It doesn't own the underlying metadata image and is not responsible for its disposal. /// /// This is used, for example, when a metadata cache needs to return the cached metadata to its users /// while keeping the ownership of the cached metadata object. /// </remarks> internal new ModuleMetadata Copy() { return new ModuleMetadata(this); } protected override Metadata CommonCopy() { return Copy(); } /// <summary> /// Frees memory and handles allocated for the module. /// </summary> public override void Dispose() { _isDisposed = true; if (IsImageOwner) { _module.Dispose(); } } /// <summary> /// True if the module has been disposed. /// </summary> public bool IsDisposed { get { return _isDisposed || _module.IsDisposed; } } internal PEModule Module { get { if (IsDisposed) { throw new ObjectDisposedException(nameof(ModuleMetadata)); } return _module; } } /// <summary> /// Name of the module. /// </summary> /// <exception cref="BadImageFormatException">Invalid metadata.</exception> /// <exception cref="ObjectDisposedException">Module has been disposed.</exception> public string Name { get { return Module.Name; } } /// <summary> /// Version of the module content. /// </summary> /// <exception cref="BadImageFormatException">Invalid metadata.</exception> /// <exception cref="ObjectDisposedException">Module has been disposed.</exception> public Guid GetModuleVersionId() { return Module.GetModuleVersionIdOrThrow(); } /// <summary> /// Returns the <see cref="MetadataImageKind"/> for this instance. /// </summary> public override MetadataImageKind Kind { get { return MetadataImageKind.Module; } } /// <summary> /// Returns the file names of linked managed modules. /// </summary> /// <exception cref="BadImageFormatException">When an invalid module name is encountered.</exception> /// <exception cref="ObjectDisposedException">Module has been disposed.</exception> public ImmutableArray<string> GetModuleNames() { return Module.GetMetadataModuleNamesOrThrow(); } /// <summary> /// Returns the metadata reader. /// </summary> /// <exception cref="ObjectDisposedException">Module has been disposed.</exception> /// <exception cref="BadImageFormatException">When an invalid module name is encountered.</exception> public MetadataReader GetMetadataReader() => MetadataReader; internal MetadataReader MetadataReader => Module.MetadataReader; /// <summary> /// Creates a reference to the module metadata. /// </summary> /// <param name="documentation">Provider of XML documentation comments for the metadata symbols contained in the module.</param> /// <param name="filePath">Path describing the location of the metadata, or null if the metadata have no location.</param> /// <param name="display">Display string used in error messages to identity the reference.</param> /// <returns>A reference to the module metadata.</returns> public PortableExecutableReference GetReference(DocumentationProvider? documentation = null, string? filePath = null, string? display = null) { return new MetadataImageReference(this, MetadataReferenceProperties.Module, documentation, filePath, display); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents an immutable snapshot of module CLI metadata. /// </summary> /// <remarks>This object may allocate significant resources or lock files depending upon how it is constructed.</remarks> public sealed partial class ModuleMetadata : Metadata { private bool _isDisposed; private readonly PEModule _module; private ModuleMetadata(PEReader peReader) : base(isImageOwner: true, id: MetadataId.CreateNewId()) { _module = new PEModule(this, peReader: peReader, metadataOpt: IntPtr.Zero, metadataSizeOpt: 0, includeEmbeddedInteropTypes: false, ignoreAssemblyRefs: false); } private ModuleMetadata(IntPtr metadata, int size, bool includeEmbeddedInteropTypes, bool ignoreAssemblyRefs) : base(isImageOwner: true, id: MetadataId.CreateNewId()) { _module = new PEModule(this, peReader: null, metadataOpt: metadata, metadataSizeOpt: size, includeEmbeddedInteropTypes: includeEmbeddedInteropTypes, ignoreAssemblyRefs: ignoreAssemblyRefs); } // creates a copy private ModuleMetadata(ModuleMetadata metadata) : base(isImageOwner: false, id: metadata.Id) { _module = metadata.Module; } /// <summary> /// Create metadata module from a raw memory pointer to metadata directory of a PE image or .cormeta section of an object file. /// Only manifest modules are currently supported. /// </summary> /// <param name="metadata">Pointer to the start of metadata block.</param> /// <param name="size">The size of the metadata block.</param> /// <exception cref="ArgumentNullException"><paramref name="metadata"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="size"/> is not positive.</exception> public static ModuleMetadata CreateFromMetadata(IntPtr metadata, int size) { if (metadata == IntPtr.Zero) { throw new ArgumentNullException(nameof(metadata)); } if (size <= 0) { throw new ArgumentOutOfRangeException(CodeAnalysisResources.SizeHasToBePositive, nameof(size)); } return new ModuleMetadata(metadata, size, includeEmbeddedInteropTypes: false, ignoreAssemblyRefs: false); } internal static ModuleMetadata CreateFromMetadata(IntPtr metadata, int size, bool includeEmbeddedInteropTypes, bool ignoreAssemblyRefs = false) { Debug.Assert(metadata != IntPtr.Zero); Debug.Assert(size > 0); return new ModuleMetadata(metadata, size, includeEmbeddedInteropTypes, ignoreAssemblyRefs); } /// <summary> /// Create metadata module from a raw memory pointer to a PE image or an object file. /// </summary> /// <param name="peImage">Pointer to the DOS header ("MZ") of a portable executable image.</param> /// <param name="size">The size of the image pointed to by <paramref name="peImage"/>.</param> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="size"/> is not positive.</exception> public static unsafe ModuleMetadata CreateFromImage(IntPtr peImage, int size) { if (peImage == IntPtr.Zero) { throw new ArgumentNullException(nameof(peImage)); } if (size <= 0) { throw new ArgumentOutOfRangeException(CodeAnalysisResources.SizeHasToBePositive, nameof(size)); } return new ModuleMetadata(new PEReader((byte*)peImage, size)); } /// <summary> /// Create metadata module from a sequence of bytes. /// </summary> /// <param name="peImage">The portable executable image beginning with the DOS header ("MZ").</param> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception> public static ModuleMetadata CreateFromImage(IEnumerable<byte> peImage) { if (peImage == null) { throw new ArgumentNullException(nameof(peImage)); } return CreateFromImage(ImmutableArray.CreateRange(peImage)); } /// <summary> /// Create metadata module from a byte array. /// </summary> /// <param name="peImage">Portable executable image beginning with the DOS header ("MZ").</param> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception> public static ModuleMetadata CreateFromImage(ImmutableArray<byte> peImage) { if (peImage.IsDefault) { throw new ArgumentNullException(nameof(peImage)); } return new ModuleMetadata(new PEReader(peImage)); } /// <summary> /// Create metadata module from a stream. /// </summary> /// <param name="peStream">Stream containing portable executable image. Position zero should contain the first byte of the DOS header ("MZ").</param> /// <param name="leaveOpen"> /// False to close the stream upon disposal of the metadata (the responsibility for disposal of the stream is transferred upon entry of the constructor /// unless the arguments given are invalid). /// </param> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="ArgumentException">The stream doesn't support seek operations.</exception> public static ModuleMetadata CreateFromStream(Stream peStream, bool leaveOpen = false) { return CreateFromStream(peStream, leaveOpen ? PEStreamOptions.LeaveOpen : PEStreamOptions.Default); } /// <summary> /// Create metadata module from a stream. /// </summary> /// <param name="peStream">Stream containing portable executable image. Position zero should contain the first byte of the DOS header ("MZ").</param> /// <param name="options"> /// Options specifying how sections of the PE image are read from the stream. /// Unless <see cref="PEStreamOptions.LeaveOpen"/> is specified, the responsibility for disposal of the stream is transferred upon entry of the constructor /// unless the arguments given are invalid. /// </param> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="ArgumentException">The stream doesn't support read and seek operations.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="options"/> has an invalid value.</exception> /// <exception cref="BadImageFormatException"> /// <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/> is specified and the PE headers of the image are invalid. /// </exception> /// <exception cref="IOException"> /// <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/> is specified and an error occurs while reading the stream. /// </exception> public static ModuleMetadata CreateFromStream(Stream peStream, PEStreamOptions options) { if (peStream == null) { throw new ArgumentNullException(nameof(peStream)); } if (!peStream.CanRead || !peStream.CanSeek) { throw new ArgumentException(CodeAnalysisResources.StreamMustSupportReadAndSeek, nameof(peStream)); } // Workaround of issue https://github.com/dotnet/corefx/issues/1815: if (peStream.Length == 0 && (options & PEStreamOptions.PrefetchEntireImage) != 0 && (options & PEStreamOptions.PrefetchMetadata) != 0) { // throws BadImageFormatException: new PEHeaders(peStream); } // ownership of the stream is passed on PEReader: return new ModuleMetadata(new PEReader(peStream, options)); } /// <summary> /// Creates metadata module from a file containing a portable executable image. /// </summary> /// <param name="path">File path.</param> /// <remarks> /// The file might remain mapped (and read-locked) until this object is disposed. /// The memory map is only created for large files. Small files are read into memory. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="path"/> is invalid.</exception> /// <exception cref="IOException">Error opening file <paramref name="path"/>. See <see cref="Exception.InnerException"/> for details.</exception> /// <exception cref="FileNotFoundException">File <paramref name="path"/> not found.</exception> /// <exception cref="NotSupportedException">Reading from a file path is not supported by the platform.</exception> public static ModuleMetadata CreateFromFile(string path) { return CreateFromStream(StandardFileSystem.Instance.OpenFileWithNormalizedException(path, FileMode.Open, FileAccess.Read, FileShare.Read)); } /// <summary> /// Creates a shallow copy of this object. /// </summary> /// <remarks> /// The resulting copy shares the metadata image and metadata information read from it with the original. /// It doesn't own the underlying metadata image and is not responsible for its disposal. /// /// This is used, for example, when a metadata cache needs to return the cached metadata to its users /// while keeping the ownership of the cached metadata object. /// </remarks> internal new ModuleMetadata Copy() { return new ModuleMetadata(this); } protected override Metadata CommonCopy() { return Copy(); } /// <summary> /// Frees memory and handles allocated for the module. /// </summary> public override void Dispose() { _isDisposed = true; if (IsImageOwner) { _module.Dispose(); } } /// <summary> /// True if the module has been disposed. /// </summary> public bool IsDisposed { get { return _isDisposed || _module.IsDisposed; } } internal PEModule Module { get { if (IsDisposed) { throw new ObjectDisposedException(nameof(ModuleMetadata)); } return _module; } } /// <summary> /// Name of the module. /// </summary> /// <exception cref="BadImageFormatException">Invalid metadata.</exception> /// <exception cref="ObjectDisposedException">Module has been disposed.</exception> public string Name { get { return Module.Name; } } /// <summary> /// Version of the module content. /// </summary> /// <exception cref="BadImageFormatException">Invalid metadata.</exception> /// <exception cref="ObjectDisposedException">Module has been disposed.</exception> public Guid GetModuleVersionId() { return Module.GetModuleVersionIdOrThrow(); } /// <summary> /// Returns the <see cref="MetadataImageKind"/> for this instance. /// </summary> public override MetadataImageKind Kind { get { return MetadataImageKind.Module; } } /// <summary> /// Returns the file names of linked managed modules. /// </summary> /// <exception cref="BadImageFormatException">When an invalid module name is encountered.</exception> /// <exception cref="ObjectDisposedException">Module has been disposed.</exception> public ImmutableArray<string> GetModuleNames() { return Module.GetMetadataModuleNamesOrThrow(); } /// <summary> /// Returns the metadata reader. /// </summary> /// <exception cref="ObjectDisposedException">Module has been disposed.</exception> /// <exception cref="BadImageFormatException">When an invalid module name is encountered.</exception> public MetadataReader GetMetadataReader() => MetadataReader; internal MetadataReader MetadataReader => Module.MetadataReader; /// <summary> /// Creates a reference to the module metadata. /// </summary> /// <param name="documentation">Provider of XML documentation comments for the metadata symbols contained in the module.</param> /// <param name="filePath">Path describing the location of the metadata, or null if the metadata have no location.</param> /// <param name="display">Display string used in error messages to identity the reference.</param> /// <returns>A reference to the module metadata.</returns> public PortableExecutableReference GetReference(DocumentationProvider? documentation = null, string? filePath = null, string? display = null) { return new MetadataImageReference(this, MetadataReferenceProperties.Module, documentation, filePath, display); } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/MemberInfo/ModuleImpl.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.VisualStudio.Debugger.Metadata; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal sealed class ModuleImpl : Module { internal readonly System.Reflection.Module Module; internal ModuleImpl(System.Reflection.Module module) { Debug.Assert(module != null); this.Module = module; } public override Type[] FindTypes(TypeFilter filter, object filterCriteria) { throw new NotImplementedException(); } public override IList<CustomAttributeData> GetCustomAttributesData() { throw new NotImplementedException(); } public override Type GetType(string className, bool throwOnError, bool ignoreCase) { throw new NotImplementedException(); } public override Type[] GetTypes() { throw new NotImplementedException(); } public override Guid ModuleVersionId { get { return this.Module.ModuleVersionId; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.VisualStudio.Debugger.Metadata; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal sealed class ModuleImpl : Module { internal readonly System.Reflection.Module Module; internal ModuleImpl(System.Reflection.Module module) { Debug.Assert(module != null); this.Module = module; } public override Type[] FindTypes(TypeFilter filter, object filterCriteria) { throw new NotImplementedException(); } public override IList<CustomAttributeData> GetCustomAttributesData() { throw new NotImplementedException(); } public override Type GetType(string className, bool throwOnError, bool ignoreCase) { throw new NotImplementedException(); } public override Type[] GetTypes() { throw new NotImplementedException(); } public override Guid ModuleVersionId { get { return this.Module.ModuleVersionId; } } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ULongKeywordRecommender.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 ULongKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public ULongKeywordRecommender() : base(SyntaxKind.ULongKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsAnyExpressionContext || 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.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_UInt64; } }
// Licensed to the .NET Foundation under one or more 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 ULongKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public ULongKeywordRecommender() : base(SyntaxKind.ULongKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsAnyExpressionContext || 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.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_UInt64; } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpDefaultExpressionReducer.Rewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpDefaultExpressionReducer { private class Rewriter : AbstractReductionRewriter { public Rewriter(ObjectPool<IReductionRewriter> pool) : base(pool) { _simplifyDefaultExpression = SimplifyDefaultExpression; } private readonly Func<DefaultExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> _simplifyDefaultExpression; private SyntaxNode SimplifyDefaultExpression( DefaultExpressionSyntax node, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { var preferSimpleDefaultExpression = optionSet.GetOption(CSharpCodeStyleOptions.PreferSimpleDefaultExpression).Value; if (node.CanReplaceWithDefaultLiteral(ParseOptions, preferSimpleDefaultExpression, semanticModel, cancellationToken)) { return SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression) .WithTriviaFrom(node); } return node; } public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node) { return SimplifyNode( node, newNode: base.VisitDefaultExpression(node), parentNode: node.Parent, simplifier: _simplifyDefaultExpression); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpDefaultExpressionReducer { private class Rewriter : AbstractReductionRewriter { public Rewriter(ObjectPool<IReductionRewriter> pool) : base(pool) { _simplifyDefaultExpression = SimplifyDefaultExpression; } private readonly Func<DefaultExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> _simplifyDefaultExpression; private SyntaxNode SimplifyDefaultExpression( DefaultExpressionSyntax node, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { var preferSimpleDefaultExpression = optionSet.GetOption(CSharpCodeStyleOptions.PreferSimpleDefaultExpression).Value; if (node.CanReplaceWithDefaultLiteral(ParseOptions, preferSimpleDefaultExpression, semanticModel, cancellationToken)) { return SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression) .WithTriviaFrom(node); } return node; } public override SyntaxNode VisitDefaultExpression(DefaultExpressionSyntax node) { return SimplifyNode( node, newNode: base.VisitDefaultExpression(node), parentNode: node.Parent, simplifier: _simplifyDefaultExpression); } } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/EnumKeywordRecommender.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 Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class EnumKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InternalKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, }; public EnumKeywordRecommender() : base(SyntaxKind.EnumKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsGlobalStatementContext || context.IsTypeDeclarationContext( validModifiers: s_validModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, 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. #nullable disable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class EnumKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { private static readonly ISet<SyntaxKind> s_validModifiers = new HashSet<SyntaxKind>(SyntaxFacts.EqualityComparer) { SyntaxKind.InternalKeyword, SyntaxKind.PublicKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, }; public EnumKeywordRecommender() : base(SyntaxKind.EnumKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return context.IsGlobalStatementContext || context.IsTypeDeclarationContext( validModifiers: s_validModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Core/Portable/Syntax/InternalSyntax/SyntaxDiagnosticInfoList.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.CodeAnalysis.Syntax.InternalSyntax { // Avoid implementing IEnumerable so we do not get any unintentional boxing. internal struct SyntaxDiagnosticInfoList { private readonly GreenNode _node; internal SyntaxDiagnosticInfoList(GreenNode node) { _node = node; } public Enumerator GetEnumerator() { return new Enumerator(_node); } internal bool Any(Func<DiagnosticInfo, bool> predicate) { var enumerator = GetEnumerator(); while (enumerator.MoveNext()) { if (predicate(enumerator.Current)) return true; } return false; } public struct Enumerator { private struct NodeIteration { internal readonly GreenNode Node; internal int DiagnosticIndex; internal int SlotIndex; internal NodeIteration(GreenNode node) { this.Node = node; this.SlotIndex = -1; this.DiagnosticIndex = -1; } } private NodeIteration[]? _stack; private int _count; public DiagnosticInfo Current { get; private set; } internal Enumerator(GreenNode node) { Current = null!; _stack = null; _count = 0; if (node != null && node.ContainsDiagnostics) { _stack = new NodeIteration[8]; this.PushNodeOrToken(node); } } public bool MoveNext() { while (_count > 0) { var diagIndex = _stack![_count - 1].DiagnosticIndex; var node = _stack[_count - 1].Node; var diags = node.GetDiagnostics(); if (diagIndex < diags.Length - 1) { diagIndex++; Current = diags[diagIndex]; _stack[_count - 1].DiagnosticIndex = diagIndex; return true; } var slotIndex = _stack[_count - 1].SlotIndex; tryAgain: if (slotIndex < node.SlotCount - 1) { slotIndex++; var child = node.GetSlot(slotIndex); if (child == null || !child.ContainsDiagnostics) { goto tryAgain; } _stack[_count - 1].SlotIndex = slotIndex; this.PushNodeOrToken(child); } else { this.Pop(); } } return false; } private void PushNodeOrToken(GreenNode node) { if (node.IsToken) { this.PushToken(node); } else { this.Push(node); } } private void PushToken(GreenNode token) { var trailing = token.GetTrailingTriviaCore(); if (trailing != null) { this.Push(trailing); } this.Push(token); var leading = token.GetLeadingTriviaCore(); if (leading != null) { this.Push(leading); } } private void Push(GreenNode node) { RoslynDebug.Assert(_stack is object); if (_count >= _stack.Length) { var tmp = new NodeIteration[_stack.Length * 2]; Array.Copy(_stack, tmp, _stack.Length); _stack = tmp; } _stack[_count] = new NodeIteration(node); _count++; } private void Pop() { _count--; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { // Avoid implementing IEnumerable so we do not get any unintentional boxing. internal struct SyntaxDiagnosticInfoList { private readonly GreenNode _node; internal SyntaxDiagnosticInfoList(GreenNode node) { _node = node; } public Enumerator GetEnumerator() { return new Enumerator(_node); } internal bool Any(Func<DiagnosticInfo, bool> predicate) { var enumerator = GetEnumerator(); while (enumerator.MoveNext()) { if (predicate(enumerator.Current)) return true; } return false; } public struct Enumerator { private struct NodeIteration { internal readonly GreenNode Node; internal int DiagnosticIndex; internal int SlotIndex; internal NodeIteration(GreenNode node) { this.Node = node; this.SlotIndex = -1; this.DiagnosticIndex = -1; } } private NodeIteration[]? _stack; private int _count; public DiagnosticInfo Current { get; private set; } internal Enumerator(GreenNode node) { Current = null!; _stack = null; _count = 0; if (node != null && node.ContainsDiagnostics) { _stack = new NodeIteration[8]; this.PushNodeOrToken(node); } } public bool MoveNext() { while (_count > 0) { var diagIndex = _stack![_count - 1].DiagnosticIndex; var node = _stack[_count - 1].Node; var diags = node.GetDiagnostics(); if (diagIndex < diags.Length - 1) { diagIndex++; Current = diags[diagIndex]; _stack[_count - 1].DiagnosticIndex = diagIndex; return true; } var slotIndex = _stack[_count - 1].SlotIndex; tryAgain: if (slotIndex < node.SlotCount - 1) { slotIndex++; var child = node.GetSlot(slotIndex); if (child == null || !child.ContainsDiagnostics) { goto tryAgain; } _stack[_count - 1].SlotIndex = slotIndex; this.PushNodeOrToken(child); } else { this.Pop(); } } return false; } private void PushNodeOrToken(GreenNode node) { if (node.IsToken) { this.PushToken(node); } else { this.Push(node); } } private void PushToken(GreenNode token) { var trailing = token.GetTrailingTriviaCore(); if (trailing != null) { this.Push(trailing); } this.Push(token); var leading = token.GetLeadingTriviaCore(); if (leading != null) { this.Push(leading); } } private void Push(GreenNode node) { RoslynDebug.Assert(_stack is object); if (_count >= _stack.Length) { var tmp = new NodeIteration[_stack.Length * 2]; Array.Copy(_stack, tmp, _stack.Length); _stack = tmp; } _stack[_count] = new NodeIteration(node); _count++; } private void Pop() { _count--; } } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/Test/Core/Compilation/BuildPathsUtil.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.IO; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis; namespace Microsoft.CodeAnalysis.Test.Utilities { internal static class BuildPathsUtil { } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis; namespace Microsoft.CodeAnalysis.Test.Utilities { internal static class BuildPathsUtil { } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Def/Implementation/Progression/RoslynGraphCategories.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.Text; using Microsoft.VisualStudio.GraphModel; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal static class RoslynGraphCategories { public static readonly GraphSchema Schema; public static readonly GraphCategory Overrides; static RoslynGraphCategories() { Schema = RoslynGraphProperties.Schema; Overrides = Schema.Categories.AddNewCategory( "Overrides", () => new GraphMetadata(GraphMetadataOptions.Sharable)); } } }
// Licensed to the .NET Foundation under one or more 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.Text; using Microsoft.VisualStudio.GraphModel; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal static class RoslynGraphCategories { public static readonly GraphSchema Schema; public static readonly GraphCategory Overrides; static RoslynGraphCategories() { Schema = RoslynGraphProperties.Schema; Overrides = Schema.Categories.AddNewCategory( "Overrides", () => new GraphMetadata(GraphMetadataOptions.Sharable)); } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/Core/Portable/SemanticModelReuse/ISemanticModelReuseLanguageService.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 System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.SemanticModelReuse { /// <summary> /// Interface only for use by <see cref="ISemanticModelReuseWorkspaceService"/>. Includes language specific /// implementations on how to get an appropriate speculated semantic model given an older semantic model and a /// changed method body. /// </summary> internal interface ISemanticModelReuseLanguageService : ILanguageService { /// <summary> /// Given a node, returns the parent method-body-esque node that we can get a new speculative semantic model /// for. Returns <see langword="null"/> if not in such a location. /// </summary> SyntaxNode? TryGetContainingMethodBodyForSpeculation(SyntaxNode node); /// <summary> /// Given a previous semantic model, and a method-eque node in the current tree for that same document, attempts /// to create a new speculative semantic model using the top level symbols of <paramref /// name="previousSemanticModel"/> but the new body level symbols produced for <paramref /// name="currentBodyNode"/>. /// <para> /// Note: it is critical that no top level changes have occurred between the syntax tree that <paramref /// name="previousSemanticModel"/> points at and the syntax tree that <paramref name="currentBodyNode"/> points /// at. In other words, they must be <see cref="SyntaxTree.IsEquivalentTo"/><c>(..., topLevel: true)</c>. This /// function is undefined if they are not. /// </para> /// </summary> Task<SemanticModel?> TryGetSpeculativeSemanticModelAsync(SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, 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.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.SemanticModelReuse { /// <summary> /// Interface only for use by <see cref="ISemanticModelReuseWorkspaceService"/>. Includes language specific /// implementations on how to get an appropriate speculated semantic model given an older semantic model and a /// changed method body. /// </summary> internal interface ISemanticModelReuseLanguageService : ILanguageService { /// <summary> /// Given a node, returns the parent method-body-esque node that we can get a new speculative semantic model /// for. Returns <see langword="null"/> if not in such a location. /// </summary> SyntaxNode? TryGetContainingMethodBodyForSpeculation(SyntaxNode node); /// <summary> /// Given a previous semantic model, and a method-eque node in the current tree for that same document, attempts /// to create a new speculative semantic model using the top level symbols of <paramref /// name="previousSemanticModel"/> but the new body level symbols produced for <paramref /// name="currentBodyNode"/>. /// <para> /// Note: it is critical that no top level changes have occurred between the syntax tree that <paramref /// name="previousSemanticModel"/> points at and the syntax tree that <paramref name="currentBodyNode"/> points /// at. In other words, they must be <see cref="SyntaxTree.IsEquivalentTo"/><c>(..., topLevel: true)</c>. This /// function is undefined if they are not. /// </para> /// </summary> Task<SemanticModel?> TryGetSpeculativeSemanticModelAsync(SemanticModel previousSemanticModel, SyntaxNode currentBodyNode, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/GenerateMember/GenerateConstructor/AbstractGenerateConstructorService.State.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor { internal abstract partial class AbstractGenerateConstructorService<TService, TExpressionSyntax> { protected internal class State { private readonly TService _service; private readonly SemanticDocument _document; private readonly NamingRule _fieldNamingRule; private readonly NamingRule _propertyNamingRule; private readonly NamingRule _parameterNamingRule; private ImmutableArray<Argument> _arguments; // The type we're creating a constructor for. Will be a class or struct type. public INamedTypeSymbol? TypeToGenerateIn { get; private set; } private ImmutableArray<RefKind> _parameterRefKinds; public ImmutableArray<ITypeSymbol> ParameterTypes; public SyntaxToken Token { get; private set; } public bool IsConstructorInitializerGeneration { get; private set; } private IMethodSymbol? _delegatedConstructor; private ImmutableArray<IParameterSymbol> _parameters; private ImmutableDictionary<string, ISymbol>? _parameterToExistingMemberMap; public ImmutableDictionary<string, string> ParameterToNewFieldMap { get; private set; } public ImmutableDictionary<string, string> ParameterToNewPropertyMap { get; private set; } public bool IsContainedInUnsafeType { get; private set; } private State(TService service, SemanticDocument document, NamingRule fieldNamingRule, NamingRule propertyNamingRule, NamingRule parameterNamingRule) { _service = service; _document = document; _fieldNamingRule = fieldNamingRule; _propertyNamingRule = propertyNamingRule; _parameterNamingRule = parameterNamingRule; ParameterToNewFieldMap = ImmutableDictionary<string, string>.Empty; ParameterToNewPropertyMap = ImmutableDictionary<string, string>.Empty; } public static async Task<State?> GenerateAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { var fieldNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Field, Accessibility.Private, cancellationToken).ConfigureAwait(false); var propertyNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Property, Accessibility.Public, cancellationToken).ConfigureAwait(false); var parameterNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Parameter, Accessibility.NotApplicable, cancellationToken).ConfigureAwait(false); var state = new State(service, document, fieldNamingRule, propertyNamingRule, parameterNamingRule); if (!await state.TryInitializeAsync(node, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( SyntaxNode node, CancellationToken cancellationToken) { if (_service.IsConstructorInitializerGeneration(_document, node, cancellationToken)) { if (!await TryInitializeConstructorInitializerGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsSimpleNameGeneration(_document, node, cancellationToken)) { if (!await TryInitializeSimpleNameGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsImplicitObjectCreation(_document, node, cancellationToken)) { if (!await TryInitializeImplicitObjectCreationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else { return false; } Contract.ThrowIfNull(TypeToGenerateIn); if (!CodeGenerator.CanAdd(_document.Project.Solution, TypeToGenerateIn, cancellationToken)) return false; ParameterTypes = ParameterTypes.IsDefault ? GetParameterTypes(cancellationToken) : ParameterTypes; _parameterRefKinds = _arguments.SelectAsArray(a => a.RefKind); if (ClashesWithExistingConstructor()) return false; if (!TryInitializeDelegatedConstructor(cancellationToken)) InitializeNonDelegatedConstructor(cancellationToken); IsContainedInUnsafeType = _service.ContainingTypesOrSelfHasUnsafeKeyword(TypeToGenerateIn); return true; } private void InitializeNonDelegatedConstructor(CancellationToken cancellationToken) { var typeParametersNames = TypeToGenerateIn.GetAllTypeParameters().Select(t => t.Name).ToImmutableArray(); var parameterNames = GetParameterNames(_arguments, typeParametersNames, cancellationToken); GetParameters(_arguments, ParameterTypes, parameterNames, cancellationToken); } private ImmutableArray<ParameterName> GetParameterNames( ImmutableArray<Argument> arguments, ImmutableArray<string> typeParametersNames, CancellationToken cancellationToken) { return _service.GenerateParameterNames(_document, arguments, typeParametersNames, _parameterNamingRule, cancellationToken); } private bool TryInitializeDelegatedConstructor(CancellationToken cancellationToken) { var parameters = ParameterTypes.Zip(_parameterRefKinds, (t, r) => CodeGenerationSymbolFactory.CreateParameterSymbol(r, t, name: "")).ToImmutableArray(); var expressions = _arguments.SelectAsArray(a => a.Expression); var delegatedConstructor = FindConstructorToDelegateTo(parameters, expressions, cancellationToken); if (delegatedConstructor == null) return false; // Map the first N parameters to the other constructor in this type. Then // try to map any further parameters to existing fields. Finally, generate // new fields if no such parameters exist. // Find the names of the parameters that will follow the parameters we're // delegating. var argumentCount = delegatedConstructor.Parameters.Length; var remainingArguments = _arguments.Skip(argumentCount).ToImmutableArray(); var remainingParameterNames = _service.GenerateParameterNames( _document, remainingArguments, delegatedConstructor.Parameters.Select(p => p.Name).ToList(), _parameterNamingRule, cancellationToken); // Can't generate the constructor if the parameter names we're copying over forcibly // conflict with any names we generated. if (delegatedConstructor.Parameters.Select(p => p.Name).Intersect(remainingParameterNames.Select(n => n.BestNameForParameter)).Any()) return false; var remainingParameterTypes = ParameterTypes.Skip(argumentCount).ToImmutableArray(); _delegatedConstructor = delegatedConstructor; GetParameters(remainingArguments, remainingParameterTypes, remainingParameterNames, cancellationToken); return true; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> allParameters, ImmutableArray<TExpressionSyntax?> allExpressions, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); Contract.ThrowIfNull(TypeToGenerateIn.BaseType); for (var i = allParameters.Length; i > 0; i--) { var parameters = allParameters.TakeAsArray(i); var expressions = allExpressions.TakeAsArray(i); var result = FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.InstanceConstructors, cancellationToken) ?? FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.BaseType.InstanceConstructors, cancellationToken); if (result != null) return result; } return null; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> parameters, ImmutableArray<TExpressionSyntax?> expressions, ImmutableArray<IMethodSymbol> constructors, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); foreach (var constructor in constructors) { // Don't bother delegating to an implicit constructor. We don't want to add `: base()` as that's just // redundant for subclasses and `: this()` won't even work as we won't have an implicit constructor once // we add this new constructor. if (constructor.IsImplicitlyDeclared) continue; // Don't delegate to another constructor in this type if it's got the same parameter types as the // one we're generating. This can happen if we're generating the new constructor because parameter // names don't match (when a user explicitly provides named parameters). if (TypeToGenerateIn.Equals(constructor.ContainingType) && constructor.Parameters.Select(p => p.Type).SequenceEqual(ParameterTypes)) { continue; } if (GenerateConstructorHelpers.CanDelegateTo(_document, parameters, expressions, constructor) && !_service.WillCauseConstructorCycle(this, _document, constructor, cancellationToken)) { return constructor; } } return null; } private bool ClashesWithExistingConstructor() { Contract.ThrowIfNull(TypeToGenerateIn); var destinationProvider = _document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var syntaxFacts = destinationProvider.GetRequiredService<ISyntaxFactsService>(); return TypeToGenerateIn.InstanceConstructors.Any(c => Matches(c, syntaxFacts)); } private bool Matches(IMethodSymbol ctor, ISyntaxFactsService service) { if (ctor.Parameters.Length != ParameterTypes.Length) return false; for (var i = 0; i < ParameterTypes.Length; i++) { var ctorParameter = ctor.Parameters[i]; var result = SymbolEquivalenceComparer.Instance.Equals(ctorParameter.Type, ParameterTypes[i]) && ctorParameter.RefKind == _parameterRefKinds[i]; var parameterName = GetParameterName(i); if (!string.IsNullOrEmpty(parameterName)) { result &= service.IsCaseSensitive ? ctorParameter.Name == parameterName : string.Equals(ctorParameter.Name, parameterName, StringComparison.OrdinalIgnoreCase); } if (result == false) return false; } return true; } private string GetParameterName(int index) => _arguments.IsDefault || index >= _arguments.Length ? string.Empty : _arguments[index].Name; internal ImmutableArray<ITypeSymbol> GetParameterTypes(CancellationToken cancellationToken) { var allTypeParameters = TypeToGenerateIn.GetAllTypeParameters(); var semanticModel = _document.SemanticModel; var allTypes = _arguments.Select(a => _service.GetArgumentType(_document.SemanticModel, a, cancellationToken)); return allTypes.Select(t => FixType(t, semanticModel, allTypeParameters)).ToImmutableArray(); } private static ITypeSymbol FixType(ITypeSymbol typeSymbol, SemanticModel semanticModel, IEnumerable<ITypeParameterSymbol> allTypeParameters) { var compilation = semanticModel.Compilation; return typeSymbol.RemoveAnonymousTypes(compilation) .RemoveUnavailableTypeParameters(compilation, allTypeParameters) .RemoveUnnamedErrorTypes(compilation); } private async Task<bool> TryInitializeConstructorInitializerGenerationAsync( SyntaxNode constructorInitializer, CancellationToken cancellationToken) { if (_service.TryInitializeConstructorInitializerGeneration( _document, constructorInitializer, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; IsConstructorInitializerGeneration = true; var semanticInfo = _document.SemanticModel.GetSymbolInfo(constructorInitializer, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeImplicitObjectCreationAsync(SyntaxNode implicitObjectCreation, CancellationToken cancellationToken) { if (_service.TryInitializeImplicitObjectCreation( _document, implicitObjectCreation, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; var semanticInfo = _document.SemanticModel.GetSymbolInfo(implicitObjectCreation, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeSimpleNameGenerationAsync( SyntaxNode simpleName, CancellationToken cancellationToken) { if (_service.TryInitializeSimpleNameGenerationState( _document, simpleName, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; } else if (_service.TryInitializeSimpleAttributeNameGenerationState( _document, simpleName, cancellationToken, out token, out arguments, out typeToGenerateIn)) { Token = token; _arguments = arguments; //// Attribute parameters are restricted to be constant values (simple types or string, etc). if (GetParameterTypes(cancellationToken).Any(t => !IsValidAttributeParameterType(t))) return false; } else { return false; } cancellationToken.ThrowIfCancellationRequested(); return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } private static bool IsValidAttributeParameterType(ITypeSymbol type) { if (type.Kind == SymbolKind.ArrayType) { var arrayType = (IArrayTypeSymbol)type; if (arrayType.Rank != 1) { return false; } type = arrayType.ElementType; } if (type.IsEnumType()) { return true; } switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Byte: case SpecialType.System_Char: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_String: return true; default: return false; } } private async Task<bool> TryDetermineTypeToGenerateInAsync( INamedTypeSymbol original, CancellationToken cancellationToken) { var definition = await SymbolFinder.FindSourceDefinitionAsync(original, _document.Project.Solution, cancellationToken).ConfigureAwait(false); TypeToGenerateIn = definition as INamedTypeSymbol; return TypeToGenerateIn?.TypeKind is (TypeKind?)TypeKind.Class or (TypeKind?)TypeKind.Struct; } private void GetParameters( ImmutableArray<Argument> arguments, ImmutableArray<ITypeSymbol> parameterTypes, ImmutableArray<ParameterName> parameterNames, CancellationToken cancellationToken) { var parameterToExistingMemberMap = ImmutableDictionary.CreateBuilder<string, ISymbol>(); var parameterToNewFieldMap = ImmutableDictionary.CreateBuilder<string, string>(); var parameterToNewPropertyMap = ImmutableDictionary.CreateBuilder<string, string>(); using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var parameters); for (var i = 0; i < parameterNames.Length; i++) { var parameterName = parameterNames[i]; var parameterType = parameterTypes[i]; var argument = arguments[i]; // See if there's a matching field or property we can use, or create a new member otherwise. FindExistingOrCreateNewMember( ref parameterName, parameterType, argument, parameterToExistingMemberMap, parameterToNewFieldMap, parameterToNewPropertyMap, cancellationToken); parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: argument.RefKind, isParams: false, type: parameterType, name: parameterName.BestNameForParameter)); } _parameters = parameters.ToImmutable(); _parameterToExistingMemberMap = parameterToExistingMemberMap.ToImmutable(); ParameterToNewFieldMap = parameterToNewFieldMap.ToImmutable(); ParameterToNewPropertyMap = parameterToNewPropertyMap.ToImmutable(); } private void FindExistingOrCreateNewMember( ref ParameterName parameterName, ITypeSymbol parameterType, Argument argument, ImmutableDictionary<string, ISymbol>.Builder parameterToExistingMemberMap, ImmutableDictionary<string, string>.Builder parameterToNewFieldMap, ImmutableDictionary<string, string>.Builder parameterToNewPropertyMap, CancellationToken cancellationToken) { var expectedFieldName = _fieldNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var expectedPropertyName = _propertyNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var isFixed = argument.IsNamed; // For non-out parameters, see if there's already a field there with the same name. // If so, and it has a compatible type, then we can just assign to that field. // Otherwise, we'll need to choose a different name for this member so that it // doesn't conflict with something already in the type. First check the current type // for a matching field. If so, defer to it. var unavailableMemberNames = GetUnavailableMemberNames().ToImmutableArray(); var members = from t in TypeToGenerateIn.GetBaseTypesAndThis() let ignoreAccessibility = t.Equals(TypeToGenerateIn) from m in t.GetMembers() where m.Name.Equals(expectedFieldName, StringComparison.OrdinalIgnoreCase) where ignoreAccessibility || IsSymbolAccessible(m, _document) select m; var membersArray = members.ToImmutableArray(); var symbol = membersArray.FirstOrDefault(m => m.Name.Equals(expectedFieldName, StringComparison.Ordinal)) ?? membersArray.FirstOrDefault(); if (symbol != null) { if (IsViableFieldOrProperty(parameterType, symbol)) { // Ok! We can just the existing field. parameterToExistingMemberMap[parameterName.BestNameForParameter] = symbol; } else { // Uh-oh. Now we have a problem. We can't assign this parameter to // this field. So we need to create a new field. Find a name not in // use so we can assign to that. var baseName = _service.GenerateNameForArgument(_document.SemanticModel, argument, cancellationToken); var baseFieldWithNamingStyle = _fieldNamingRule.NamingStyle.MakeCompliant(baseName).First(); var basePropertyWithNamingStyle = _propertyNamingRule.NamingStyle.MakeCompliant(baseName).First(); var newFieldName = NameGenerator.EnsureUniqueness(baseFieldWithNamingStyle, unavailableMemberNames.Concat(parameterToNewFieldMap.Values)); var newPropertyName = NameGenerator.EnsureUniqueness(basePropertyWithNamingStyle, unavailableMemberNames.Concat(parameterToNewPropertyMap.Values)); if (isFixed) { // Can't change the parameter name, so map the existing parameter // name to the new field name. parameterToNewFieldMap[parameterName.NameBasedOnArgument] = newFieldName; parameterToNewPropertyMap[parameterName.NameBasedOnArgument] = newPropertyName; } else { // Can change the parameter name, so do so. // But first remove any prefix added due to field naming styles var fieldNameMinusPrefix = newFieldName[_fieldNamingRule.NamingStyle.Prefix.Length..]; var newParameterName = new ParameterName(fieldNameMinusPrefix, isFixed: false, _parameterNamingRule); parameterName = newParameterName; parameterToNewFieldMap[newParameterName.BestNameForParameter] = newFieldName; parameterToNewPropertyMap[newParameterName.BestNameForParameter] = newPropertyName; } } return; } // If no matching field was found, use the fieldNamingRule to create suitable name var bestNameForParameter = parameterName.BestNameForParameter; var nameBasedOnArgument = parameterName.NameBasedOnArgument; parameterToNewFieldMap[bestNameForParameter] = _fieldNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); parameterToNewPropertyMap[bestNameForParameter] = _propertyNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); } private IEnumerable<string> GetUnavailableMemberNames() { Contract.ThrowIfNull(TypeToGenerateIn); return TypeToGenerateIn.MemberNames.Concat( from type in TypeToGenerateIn.GetBaseTypes() from member in type.GetMembers() select member.Name); } private bool IsViableFieldOrProperty( ITypeSymbol parameterType, ISymbol symbol) { if (parameterType.Language != symbol.Language) return false; if (symbol != null && !symbol.IsStatic) { if (symbol is IFieldSymbol field) { return !field.IsConst && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, field.Type); } else if (symbol is IPropertySymbol property) { return property.Parameters.Length == 0 && property.IsWritableInConstructor() && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, property.Type); } } return false; } public async Task<Document> GetChangedDocumentAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { // See if there's an accessible base constructor that would accept these // types, then just call into that instead of generating fields. // // then, see if there are any constructors that would take the first 'n' arguments // we've provided. If so, delegate to those, and then create a field for any // remaining arguments. Try to match from largest to smallest. // // Otherwise, just generate a normal constructor that assigns any provided // parameters into fields. return await GenerateThisOrBaseDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false) ?? await GenerateMemberDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); } private async Task<Document?> GenerateThisOrBaseDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { if (_delegatedConstructor == null) return null; Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var (members, assignments) = await GenerateMembersAndAssignmentsAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); var isThis = _delegatedConstructor.ContainingType.OriginalDefinition.Equals(TypeToGenerateIn.OriginalDefinition); var delegatingArguments = provider.GetService<SyntaxGenerator>().CreateArguments(_delegatedConstructor.Parameters); var newParameters = _delegatedConstructor.Parameters.Concat(_parameters); var generateUnsafe = !IsContainedInUnsafeType && newParameters.Any(p => p.RequiresUnsafeModifier()); var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isUnsafe: generateUnsafe), typeName: TypeToGenerateIn.Name, parameters: newParameters, statements: assignments, baseConstructorArguments: isThis ? default : delegatingArguments, thisConstructorArguments: isThis ? delegatingArguments : default); return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, members.Concat(constructor), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } private async Task<(ImmutableArray<ISymbol>, ImmutableArray<SyntaxNode>)> GenerateMembersAndAssignmentsAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var members = withFields ? SyntaxGeneratorExtensions.CreateFieldsForParameters(_parameters, ParameterToNewFieldMap, IsContainedInUnsafeType) : withProperties ? SyntaxGeneratorExtensions.CreatePropertiesForParameters(_parameters, ParameterToNewPropertyMap, IsContainedInUnsafeType) : ImmutableArray<ISymbol>.Empty; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var assignments = !withFields && !withProperties ? ImmutableArray<SyntaxNode>.Empty : provider.GetService<SyntaxGenerator>().CreateAssignmentStatements( semanticModel, _parameters, _parameterToExistingMemberMap, withFields ? ParameterToNewFieldMap : ParameterToNewPropertyMap, addNullChecks: false, preferThrowExpression: false); return (members, assignments); } private async Task<Document> GenerateMemberDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newMemberMap = withFields ? ParameterToNewFieldMap : withProperties ? ParameterToNewPropertyMap : ImmutableDictionary<string, string>.Empty; return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, provider.GetService<SyntaxGenerator>().CreateMemberDelegatingConstructor( semanticModel, TypeToGenerateIn.Name, TypeToGenerateIn, _parameters, _parameterToExistingMemberMap, newMemberMap, addNullChecks: false, preferThrowExpression: false, generateProperties: withProperties, IsContainedInUnsafeType), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor { internal abstract partial class AbstractGenerateConstructorService<TService, TExpressionSyntax> { protected internal class State { private readonly TService _service; private readonly SemanticDocument _document; private readonly NamingRule _fieldNamingRule; private readonly NamingRule _propertyNamingRule; private readonly NamingRule _parameterNamingRule; private ImmutableArray<Argument> _arguments; // The type we're creating a constructor for. Will be a class or struct type. public INamedTypeSymbol? TypeToGenerateIn { get; private set; } private ImmutableArray<RefKind> _parameterRefKinds; public ImmutableArray<ITypeSymbol> ParameterTypes; public SyntaxToken Token { get; private set; } public bool IsConstructorInitializerGeneration { get; private set; } private IMethodSymbol? _delegatedConstructor; private ImmutableArray<IParameterSymbol> _parameters; private ImmutableDictionary<string, ISymbol>? _parameterToExistingMemberMap; public ImmutableDictionary<string, string> ParameterToNewFieldMap { get; private set; } public ImmutableDictionary<string, string> ParameterToNewPropertyMap { get; private set; } public bool IsContainedInUnsafeType { get; private set; } private State(TService service, SemanticDocument document, NamingRule fieldNamingRule, NamingRule propertyNamingRule, NamingRule parameterNamingRule) { _service = service; _document = document; _fieldNamingRule = fieldNamingRule; _propertyNamingRule = propertyNamingRule; _parameterNamingRule = parameterNamingRule; ParameterToNewFieldMap = ImmutableDictionary<string, string>.Empty; ParameterToNewPropertyMap = ImmutableDictionary<string, string>.Empty; } public static async Task<State?> GenerateAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { var fieldNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Field, Accessibility.Private, cancellationToken).ConfigureAwait(false); var propertyNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Property, Accessibility.Public, cancellationToken).ConfigureAwait(false); var parameterNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Parameter, Accessibility.NotApplicable, cancellationToken).ConfigureAwait(false); var state = new State(service, document, fieldNamingRule, propertyNamingRule, parameterNamingRule); if (!await state.TryInitializeAsync(node, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( SyntaxNode node, CancellationToken cancellationToken) { if (_service.IsConstructorInitializerGeneration(_document, node, cancellationToken)) { if (!await TryInitializeConstructorInitializerGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsSimpleNameGeneration(_document, node, cancellationToken)) { if (!await TryInitializeSimpleNameGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsImplicitObjectCreation(_document, node, cancellationToken)) { if (!await TryInitializeImplicitObjectCreationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else { return false; } Contract.ThrowIfNull(TypeToGenerateIn); if (!CodeGenerator.CanAdd(_document.Project.Solution, TypeToGenerateIn, cancellationToken)) return false; ParameterTypes = ParameterTypes.IsDefault ? GetParameterTypes(cancellationToken) : ParameterTypes; _parameterRefKinds = _arguments.SelectAsArray(a => a.RefKind); if (ClashesWithExistingConstructor()) return false; if (!TryInitializeDelegatedConstructor(cancellationToken)) InitializeNonDelegatedConstructor(cancellationToken); IsContainedInUnsafeType = _service.ContainingTypesOrSelfHasUnsafeKeyword(TypeToGenerateIn); return true; } private void InitializeNonDelegatedConstructor(CancellationToken cancellationToken) { var typeParametersNames = TypeToGenerateIn.GetAllTypeParameters().Select(t => t.Name).ToImmutableArray(); var parameterNames = GetParameterNames(_arguments, typeParametersNames, cancellationToken); GetParameters(_arguments, ParameterTypes, parameterNames, cancellationToken); } private ImmutableArray<ParameterName> GetParameterNames( ImmutableArray<Argument> arguments, ImmutableArray<string> typeParametersNames, CancellationToken cancellationToken) { return _service.GenerateParameterNames(_document, arguments, typeParametersNames, _parameterNamingRule, cancellationToken); } private bool TryInitializeDelegatedConstructor(CancellationToken cancellationToken) { var parameters = ParameterTypes.Zip(_parameterRefKinds, (t, r) => CodeGenerationSymbolFactory.CreateParameterSymbol(r, t, name: "")).ToImmutableArray(); var expressions = _arguments.SelectAsArray(a => a.Expression); var delegatedConstructor = FindConstructorToDelegateTo(parameters, expressions, cancellationToken); if (delegatedConstructor == null) return false; // Map the first N parameters to the other constructor in this type. Then // try to map any further parameters to existing fields. Finally, generate // new fields if no such parameters exist. // Find the names of the parameters that will follow the parameters we're // delegating. var argumentCount = delegatedConstructor.Parameters.Length; var remainingArguments = _arguments.Skip(argumentCount).ToImmutableArray(); var remainingParameterNames = _service.GenerateParameterNames( _document, remainingArguments, delegatedConstructor.Parameters.Select(p => p.Name).ToList(), _parameterNamingRule, cancellationToken); // Can't generate the constructor if the parameter names we're copying over forcibly // conflict with any names we generated. if (delegatedConstructor.Parameters.Select(p => p.Name).Intersect(remainingParameterNames.Select(n => n.BestNameForParameter)).Any()) return false; var remainingParameterTypes = ParameterTypes.Skip(argumentCount).ToImmutableArray(); _delegatedConstructor = delegatedConstructor; GetParameters(remainingArguments, remainingParameterTypes, remainingParameterNames, cancellationToken); return true; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> allParameters, ImmutableArray<TExpressionSyntax?> allExpressions, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); Contract.ThrowIfNull(TypeToGenerateIn.BaseType); for (var i = allParameters.Length; i > 0; i--) { var parameters = allParameters.TakeAsArray(i); var expressions = allExpressions.TakeAsArray(i); var result = FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.InstanceConstructors, cancellationToken) ?? FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.BaseType.InstanceConstructors, cancellationToken); if (result != null) return result; } return null; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> parameters, ImmutableArray<TExpressionSyntax?> expressions, ImmutableArray<IMethodSymbol> constructors, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); foreach (var constructor in constructors) { // Don't bother delegating to an implicit constructor. We don't want to add `: base()` as that's just // redundant for subclasses and `: this()` won't even work as we won't have an implicit constructor once // we add this new constructor. if (constructor.IsImplicitlyDeclared) continue; // Don't delegate to another constructor in this type if it's got the same parameter types as the // one we're generating. This can happen if we're generating the new constructor because parameter // names don't match (when a user explicitly provides named parameters). if (TypeToGenerateIn.Equals(constructor.ContainingType) && constructor.Parameters.Select(p => p.Type).SequenceEqual(ParameterTypes)) { continue; } if (GenerateConstructorHelpers.CanDelegateTo(_document, parameters, expressions, constructor) && !_service.WillCauseConstructorCycle(this, _document, constructor, cancellationToken)) { return constructor; } } return null; } private bool ClashesWithExistingConstructor() { Contract.ThrowIfNull(TypeToGenerateIn); var destinationProvider = _document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var syntaxFacts = destinationProvider.GetRequiredService<ISyntaxFactsService>(); return TypeToGenerateIn.InstanceConstructors.Any(c => Matches(c, syntaxFacts)); } private bool Matches(IMethodSymbol ctor, ISyntaxFactsService service) { if (ctor.Parameters.Length != ParameterTypes.Length) return false; for (var i = 0; i < ParameterTypes.Length; i++) { var ctorParameter = ctor.Parameters[i]; var result = SymbolEquivalenceComparer.Instance.Equals(ctorParameter.Type, ParameterTypes[i]) && ctorParameter.RefKind == _parameterRefKinds[i]; var parameterName = GetParameterName(i); if (!string.IsNullOrEmpty(parameterName)) { result &= service.IsCaseSensitive ? ctorParameter.Name == parameterName : string.Equals(ctorParameter.Name, parameterName, StringComparison.OrdinalIgnoreCase); } if (result == false) return false; } return true; } private string GetParameterName(int index) => _arguments.IsDefault || index >= _arguments.Length ? string.Empty : _arguments[index].Name; internal ImmutableArray<ITypeSymbol> GetParameterTypes(CancellationToken cancellationToken) { var allTypeParameters = TypeToGenerateIn.GetAllTypeParameters(); var semanticModel = _document.SemanticModel; var allTypes = _arguments.Select(a => _service.GetArgumentType(_document.SemanticModel, a, cancellationToken)); return allTypes.Select(t => FixType(t, semanticModel, allTypeParameters)).ToImmutableArray(); } private static ITypeSymbol FixType(ITypeSymbol typeSymbol, SemanticModel semanticModel, IEnumerable<ITypeParameterSymbol> allTypeParameters) { var compilation = semanticModel.Compilation; return typeSymbol.RemoveAnonymousTypes(compilation) .RemoveUnavailableTypeParameters(compilation, allTypeParameters) .RemoveUnnamedErrorTypes(compilation); } private async Task<bool> TryInitializeConstructorInitializerGenerationAsync( SyntaxNode constructorInitializer, CancellationToken cancellationToken) { if (_service.TryInitializeConstructorInitializerGeneration( _document, constructorInitializer, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; IsConstructorInitializerGeneration = true; var semanticInfo = _document.SemanticModel.GetSymbolInfo(constructorInitializer, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeImplicitObjectCreationAsync(SyntaxNode implicitObjectCreation, CancellationToken cancellationToken) { if (_service.TryInitializeImplicitObjectCreation( _document, implicitObjectCreation, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; var semanticInfo = _document.SemanticModel.GetSymbolInfo(implicitObjectCreation, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeSimpleNameGenerationAsync( SyntaxNode simpleName, CancellationToken cancellationToken) { if (_service.TryInitializeSimpleNameGenerationState( _document, simpleName, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; } else if (_service.TryInitializeSimpleAttributeNameGenerationState( _document, simpleName, cancellationToken, out token, out arguments, out typeToGenerateIn)) { Token = token; _arguments = arguments; //// Attribute parameters are restricted to be constant values (simple types or string, etc). if (GetParameterTypes(cancellationToken).Any(t => !IsValidAttributeParameterType(t))) return false; } else { return false; } cancellationToken.ThrowIfCancellationRequested(); return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } private static bool IsValidAttributeParameterType(ITypeSymbol type) { if (type.Kind == SymbolKind.ArrayType) { var arrayType = (IArrayTypeSymbol)type; if (arrayType.Rank != 1) { return false; } type = arrayType.ElementType; } if (type.IsEnumType()) { return true; } switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Byte: case SpecialType.System_Char: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_String: return true; default: return false; } } private async Task<bool> TryDetermineTypeToGenerateInAsync( INamedTypeSymbol original, CancellationToken cancellationToken) { var definition = await SymbolFinder.FindSourceDefinitionAsync(original, _document.Project.Solution, cancellationToken).ConfigureAwait(false); TypeToGenerateIn = definition as INamedTypeSymbol; return TypeToGenerateIn?.TypeKind is (TypeKind?)TypeKind.Class or (TypeKind?)TypeKind.Struct; } private void GetParameters( ImmutableArray<Argument> arguments, ImmutableArray<ITypeSymbol> parameterTypes, ImmutableArray<ParameterName> parameterNames, CancellationToken cancellationToken) { var parameterToExistingMemberMap = ImmutableDictionary.CreateBuilder<string, ISymbol>(); var parameterToNewFieldMap = ImmutableDictionary.CreateBuilder<string, string>(); var parameterToNewPropertyMap = ImmutableDictionary.CreateBuilder<string, string>(); using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var parameters); for (var i = 0; i < parameterNames.Length; i++) { var parameterName = parameterNames[i]; var parameterType = parameterTypes[i]; var argument = arguments[i]; // See if there's a matching field or property we can use, or create a new member otherwise. FindExistingOrCreateNewMember( ref parameterName, parameterType, argument, parameterToExistingMemberMap, parameterToNewFieldMap, parameterToNewPropertyMap, cancellationToken); parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: argument.RefKind, isParams: false, type: parameterType, name: parameterName.BestNameForParameter)); } _parameters = parameters.ToImmutable(); _parameterToExistingMemberMap = parameterToExistingMemberMap.ToImmutable(); ParameterToNewFieldMap = parameterToNewFieldMap.ToImmutable(); ParameterToNewPropertyMap = parameterToNewPropertyMap.ToImmutable(); } private void FindExistingOrCreateNewMember( ref ParameterName parameterName, ITypeSymbol parameterType, Argument argument, ImmutableDictionary<string, ISymbol>.Builder parameterToExistingMemberMap, ImmutableDictionary<string, string>.Builder parameterToNewFieldMap, ImmutableDictionary<string, string>.Builder parameterToNewPropertyMap, CancellationToken cancellationToken) { var expectedFieldName = _fieldNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var expectedPropertyName = _propertyNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var isFixed = argument.IsNamed; // For non-out parameters, see if there's already a field there with the same name. // If so, and it has a compatible type, then we can just assign to that field. // Otherwise, we'll need to choose a different name for this member so that it // doesn't conflict with something already in the type. First check the current type // for a matching field. If so, defer to it. var unavailableMemberNames = GetUnavailableMemberNames().ToImmutableArray(); var members = from t in TypeToGenerateIn.GetBaseTypesAndThis() let ignoreAccessibility = t.Equals(TypeToGenerateIn) from m in t.GetMembers() where m.Name.Equals(expectedFieldName, StringComparison.OrdinalIgnoreCase) where ignoreAccessibility || IsSymbolAccessible(m, _document) select m; var membersArray = members.ToImmutableArray(); var symbol = membersArray.FirstOrDefault(m => m.Name.Equals(expectedFieldName, StringComparison.Ordinal)) ?? membersArray.FirstOrDefault(); if (symbol != null) { if (IsViableFieldOrProperty(parameterType, symbol)) { // Ok! We can just the existing field. parameterToExistingMemberMap[parameterName.BestNameForParameter] = symbol; } else { // Uh-oh. Now we have a problem. We can't assign this parameter to // this field. So we need to create a new field. Find a name not in // use so we can assign to that. var baseName = _service.GenerateNameForArgument(_document.SemanticModel, argument, cancellationToken); var baseFieldWithNamingStyle = _fieldNamingRule.NamingStyle.MakeCompliant(baseName).First(); var basePropertyWithNamingStyle = _propertyNamingRule.NamingStyle.MakeCompliant(baseName).First(); var newFieldName = NameGenerator.EnsureUniqueness(baseFieldWithNamingStyle, unavailableMemberNames.Concat(parameterToNewFieldMap.Values)); var newPropertyName = NameGenerator.EnsureUniqueness(basePropertyWithNamingStyle, unavailableMemberNames.Concat(parameterToNewPropertyMap.Values)); if (isFixed) { // Can't change the parameter name, so map the existing parameter // name to the new field name. parameterToNewFieldMap[parameterName.NameBasedOnArgument] = newFieldName; parameterToNewPropertyMap[parameterName.NameBasedOnArgument] = newPropertyName; } else { // Can change the parameter name, so do so. // But first remove any prefix added due to field naming styles var fieldNameMinusPrefix = newFieldName[_fieldNamingRule.NamingStyle.Prefix.Length..]; var newParameterName = new ParameterName(fieldNameMinusPrefix, isFixed: false, _parameterNamingRule); parameterName = newParameterName; parameterToNewFieldMap[newParameterName.BestNameForParameter] = newFieldName; parameterToNewPropertyMap[newParameterName.BestNameForParameter] = newPropertyName; } } return; } // If no matching field was found, use the fieldNamingRule to create suitable name var bestNameForParameter = parameterName.BestNameForParameter; var nameBasedOnArgument = parameterName.NameBasedOnArgument; parameterToNewFieldMap[bestNameForParameter] = _fieldNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); parameterToNewPropertyMap[bestNameForParameter] = _propertyNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); } private IEnumerable<string> GetUnavailableMemberNames() { Contract.ThrowIfNull(TypeToGenerateIn); return TypeToGenerateIn.MemberNames.Concat( from type in TypeToGenerateIn.GetBaseTypes() from member in type.GetMembers() select member.Name); } private bool IsViableFieldOrProperty( ITypeSymbol parameterType, ISymbol symbol) { if (parameterType.Language != symbol.Language) return false; if (symbol != null && !symbol.IsStatic) { if (symbol is IFieldSymbol field) { return !field.IsConst && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, field.Type); } else if (symbol is IPropertySymbol property) { return property.Parameters.Length == 0 && property.IsWritableInConstructor() && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, property.Type); } } return false; } public async Task<Document> GetChangedDocumentAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { // See if there's an accessible base constructor that would accept these // types, then just call into that instead of generating fields. // // then, see if there are any constructors that would take the first 'n' arguments // we've provided. If so, delegate to those, and then create a field for any // remaining arguments. Try to match from largest to smallest. // // Otherwise, just generate a normal constructor that assigns any provided // parameters into fields. return await GenerateThisOrBaseDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false) ?? await GenerateMemberDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); } private async Task<Document?> GenerateThisOrBaseDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { if (_delegatedConstructor == null) return null; Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var (members, assignments) = await GenerateMembersAndAssignmentsAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); var isThis = _delegatedConstructor.ContainingType.OriginalDefinition.Equals(TypeToGenerateIn.OriginalDefinition); var delegatingArguments = provider.GetService<SyntaxGenerator>().CreateArguments(_delegatedConstructor.Parameters); var newParameters = _delegatedConstructor.Parameters.Concat(_parameters); var generateUnsafe = !IsContainedInUnsafeType && newParameters.Any(p => p.RequiresUnsafeModifier()); var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isUnsafe: generateUnsafe), typeName: TypeToGenerateIn.Name, parameters: newParameters, statements: assignments, baseConstructorArguments: isThis ? default : delegatingArguments, thisConstructorArguments: isThis ? delegatingArguments : default); return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, members.Concat(constructor), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } private async Task<(ImmutableArray<ISymbol>, ImmutableArray<SyntaxNode>)> GenerateMembersAndAssignmentsAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var members = withFields ? SyntaxGeneratorExtensions.CreateFieldsForParameters(_parameters, ParameterToNewFieldMap, IsContainedInUnsafeType) : withProperties ? SyntaxGeneratorExtensions.CreatePropertiesForParameters(_parameters, ParameterToNewPropertyMap, IsContainedInUnsafeType) : ImmutableArray<ISymbol>.Empty; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var assignments = !withFields && !withProperties ? ImmutableArray<SyntaxNode>.Empty : provider.GetService<SyntaxGenerator>().CreateAssignmentStatements( semanticModel, _parameters, _parameterToExistingMemberMap, withFields ? ParameterToNewFieldMap : ParameterToNewPropertyMap, addNullChecks: false, preferThrowExpression: false); return (members, assignments); } private async Task<Document> GenerateMemberDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newMemberMap = withFields ? ParameterToNewFieldMap : withProperties ? ParameterToNewPropertyMap : ImmutableDictionary<string, string>.Empty; return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, provider.GetService<SyntaxGenerator>().CreateMemberDelegatingConstructor( semanticModel, TypeToGenerateIn.Name, TypeToGenerateIn, _parameters, _parameterToExistingMemberMap, newMemberMap, addNullChecks: false, preferThrowExpression: false, generateProperties: withProperties, IsContainedInUnsafeType), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Scripting/Core/Hosting/MemberFilter.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.Reflection; namespace Microsoft.CodeAnalysis.Scripting.Hosting { internal class MemberFilter { public virtual bool Include(StackFrame frame) => Include(frame.GetMethod()); public virtual bool Include(MemberInfo member) => true; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using System.Reflection; namespace Microsoft.CodeAnalysis.Scripting.Hosting { internal class MemberFilter { public virtual bool Include(StackFrame frame) => Include(frame.GetMethod()); public virtual bool Include(MemberInfo member) => true; } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Test/CodeModel/AbstractCodeEnumTests.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 EnvDTE Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public MustInherit Class AbstractCodeEnumTests Inherits AbstractCodeElementTests(Of EnvDTE.CodeEnum) Protected Overrides Function GetStartPointFunc(codeElement As EnvDTE.CodeEnum) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetStartPoint(part) End Function Protected Overrides Function GetEndPointFunc(codeElement As EnvDTE.CodeEnum) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetEndPoint(part) End Function Protected Overrides Function GetAccess(codeElement As EnvDTE.CodeEnum) As EnvDTE.vsCMAccess Return codeElement.Access End Function Protected Overrides Function GetAttributes(codeElement As EnvDTE.CodeEnum) As EnvDTE.CodeElements Return codeElement.Attributes End Function Protected Overrides Function GetBases(codeElement As EnvDTE.CodeEnum) As EnvDTE.CodeElements Return codeElement.Bases End Function Protected Overrides Function GetComment(codeElement As EnvDTE.CodeEnum) As String Return codeElement.Comment End Function Protected Overrides Function GetDocComment(codeElement As EnvDTE.CodeEnum) As String Return codeElement.DocComment End Function Protected Overrides Function GetFullName(codeElement As EnvDTE.CodeEnum) As String Return codeElement.FullName End Function Protected Overrides Function GetKind(codeElement As CodeEnum) As vsCMElement Return codeElement.Kind End Function Protected Overrides Function GetName(codeElement As EnvDTE.CodeEnum) As String Return codeElement.Name End Function Protected Overrides Function GetParent(codeElement As EnvDTE.CodeEnum) As Object Return codeElement.Parent End Function Protected Overrides Function AddEnumMember(codeElement As EnvDTE.CodeEnum, data As EnumMemberData) As EnvDTE.CodeVariable Return codeElement.AddMember(data.Name, data.Value, data.Position) End Function Protected Overrides Function AddAttribute(codeElement As EnvDTE.CodeEnum, data As AttributeData) As EnvDTE.CodeAttribute Return codeElement.AddAttribute(data.Name, data.Value, data.Position) End Function Protected Overrides Sub RemoveChild(codeElement As CodeEnum, child As Object) codeElement.RemoveMember(child) End Sub Protected Overrides Function GetAccessSetter(codeElement As EnvDTE.CodeEnum) As Action(Of EnvDTE.vsCMAccess) Return Sub(access) codeElement.Access = access End Function Protected Overrides Function GetNameSetter(codeElement As CodeEnum) As Action(Of String) Return Sub(name) codeElement.Name = name 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 EnvDTE Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Public MustInherit Class AbstractCodeEnumTests Inherits AbstractCodeElementTests(Of EnvDTE.CodeEnum) Protected Overrides Function GetStartPointFunc(codeElement As EnvDTE.CodeEnum) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetStartPoint(part) End Function Protected Overrides Function GetEndPointFunc(codeElement As EnvDTE.CodeEnum) As Func(Of EnvDTE.vsCMPart, EnvDTE.TextPoint) Return Function(part) codeElement.GetEndPoint(part) End Function Protected Overrides Function GetAccess(codeElement As EnvDTE.CodeEnum) As EnvDTE.vsCMAccess Return codeElement.Access End Function Protected Overrides Function GetAttributes(codeElement As EnvDTE.CodeEnum) As EnvDTE.CodeElements Return codeElement.Attributes End Function Protected Overrides Function GetBases(codeElement As EnvDTE.CodeEnum) As EnvDTE.CodeElements Return codeElement.Bases End Function Protected Overrides Function GetComment(codeElement As EnvDTE.CodeEnum) As String Return codeElement.Comment End Function Protected Overrides Function GetDocComment(codeElement As EnvDTE.CodeEnum) As String Return codeElement.DocComment End Function Protected Overrides Function GetFullName(codeElement As EnvDTE.CodeEnum) As String Return codeElement.FullName End Function Protected Overrides Function GetKind(codeElement As CodeEnum) As vsCMElement Return codeElement.Kind End Function Protected Overrides Function GetName(codeElement As EnvDTE.CodeEnum) As String Return codeElement.Name End Function Protected Overrides Function GetParent(codeElement As EnvDTE.CodeEnum) As Object Return codeElement.Parent End Function Protected Overrides Function AddEnumMember(codeElement As EnvDTE.CodeEnum, data As EnumMemberData) As EnvDTE.CodeVariable Return codeElement.AddMember(data.Name, data.Value, data.Position) End Function Protected Overrides Function AddAttribute(codeElement As EnvDTE.CodeEnum, data As AttributeData) As EnvDTE.CodeAttribute Return codeElement.AddAttribute(data.Name, data.Value, data.Position) End Function Protected Overrides Sub RemoveChild(codeElement As CodeEnum, child As Object) codeElement.RemoveMember(child) End Sub Protected Overrides Function GetAccessSetter(codeElement As EnvDTE.CodeEnum) As Action(Of EnvDTE.vsCMAccess) Return Sub(access) codeElement.Access = access End Function Protected Overrides Function GetNameSetter(codeElement As CodeEnum) As Action(Of String) Return Sub(name) codeElement.Name = name End Function End Class End Namespace
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/LanguageServer/Protocol/Handler/Formatting/FormatDocumentRangeHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportLspRequestHandlerProvider, Shared] [ProvidesMethod(Methods.TextDocumentRangeFormattingName)] internal class FormatDocumentRangeHandler : AbstractFormatDocumentHandlerBase<DocumentRangeFormattingParams, TextEdit[]> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FormatDocumentRangeHandler() { } public override string Method => Methods.TextDocumentRangeFormattingName; public override TextDocumentIdentifier? GetTextDocumentIdentifier(DocumentRangeFormattingParams request) => request.TextDocument; public override Task<TextEdit[]> HandleRequestAsync( DocumentRangeFormattingParams request, RequestContext context, CancellationToken cancellationToken) => GetTextEditsAsync(context, request.Options, cancellationToken, range: request.Range); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [ExportLspRequestHandlerProvider, Shared] [ProvidesMethod(Methods.TextDocumentRangeFormattingName)] internal class FormatDocumentRangeHandler : AbstractFormatDocumentHandlerBase<DocumentRangeFormattingParams, TextEdit[]> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FormatDocumentRangeHandler() { } public override string Method => Methods.TextDocumentRangeFormattingName; public override TextDocumentIdentifier? GetTextDocumentIdentifier(DocumentRangeFormattingParams request) => request.TextDocument; public override Task<TextEdit[]> HandleRequestAsync( DocumentRangeFormattingParams request, RequestContext context, CancellationToken cancellationToken) => GetTextEditsAsync(context, request.Options, cancellationToken, range: request.Range); } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/CharKeywordRecommender.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 CharKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public CharKeywordRecommender() : base(SyntaxKind.CharKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsAnyExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || 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_Char; } }
// Licensed to the .NET Foundation under one or more 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 CharKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public CharKeywordRecommender() : base(SyntaxKind.CharKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsAnyExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || 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_Char; } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/VisualStudio/Core/Test/Progression/IsUsedByGraphQueryTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression <UseExportProvider, Trait(Traits.Feature, Traits.Features.Progression)> Public Class IsUsedByGraphQueryTests <WpfFact> Public Async Function IsUsedByTests() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> public class C { public int $$X; public int Y = X * X; public void M() { int x = 10; int y = x + X; } } </Document> </Project> </Workspace>) Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync() Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New IsUsedByGraphQuery(), GraphContextDirection.Target) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 Type=C Member=X)" Category="CodeSchema_Field" CodeSchemaProperty_IsPublic="True" CommonLabel="X" Icon="Microsoft.VisualStudio.Field.Public" Label="X"/> <Node Id="(@2 StartLineNumber=2 StartCharacterOffset=45 EndLineNumber=2 EndCharacterOffset=46)" Category="CodeSchema_SourceLocation" Icon="Microsoft.VisualStudio.Reference.Public" Label="Project.cs (3, 46): public int X;"/> <Node Id="(@2 StartLineNumber=3 StartCharacterOffset=49 EndLineNumber=3 EndCharacterOffset=50)" Category="CodeSchema_SourceLocation" Icon="Microsoft.VisualStudio.Reference.Public" Label="Project.cs (4, 50): public int Y = X * X;"/> <Node Id="(@2 StartLineNumber=3 StartCharacterOffset=53 EndLineNumber=3 EndCharacterOffset=54)" Category="CodeSchema_SourceLocation" Icon="Microsoft.VisualStudio.Reference.Public" Label="Project.cs (4, 54): public int Y = X * X;"/> <Node Id="(@2 StartLineNumber=6 StartCharacterOffset=49 EndLineNumber=6 EndCharacterOffset=50)" Category="CodeSchema_SourceLocation" Icon="Microsoft.VisualStudio.Reference.Public" Label="Project.cs (7, 50): int y = x + X;"/> </Nodes> <Links> <Link Source="(@1 Type=C Member=X)" Target="(@2 StartLineNumber=2 StartCharacterOffset=45 EndLineNumber=2 EndCharacterOffset=46)" Category="CodeSchema_SourceReferences"/> <Link Source="(@1 Type=C Member=X)" Target="(@2 StartLineNumber=3 StartCharacterOffset=49 EndLineNumber=3 EndCharacterOffset=50)" Category="CodeSchema_SourceReferences"/> <Link Source="(@1 Type=C Member=X)" Target="(@2 StartLineNumber=3 StartCharacterOffset=53 EndLineNumber=3 EndCharacterOffset=54)" Category="CodeSchema_SourceReferences"/> <Link Source="(@1 Type=C Member=X)" Target="(@2 StartLineNumber=6 StartCharacterOffset=49 EndLineNumber=6 EndCharacterOffset=50)" Category="CodeSchema_SourceReferences"/> </Links> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/> <Alias n="2" Uri="Assembly=file:///Z:/Project.cs"/> </IdentifierAliases> </DirectedGraph>) 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.Tasks Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression <UseExportProvider, Trait(Traits.Feature, Traits.Features.Progression)> Public Class IsUsedByGraphQueryTests <WpfFact> Public Async Function IsUsedByTests() As Task Using testState = ProgressionTestState.Create( <Workspace> <Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj"> <Document FilePath="Z:\Project.cs"> public class C { public int $$X; public int Y = X * X; public void M() { int x = 10; int y = x + X; } } </Document> </Project> </Workspace>) Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync() Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New IsUsedByGraphQuery(), GraphContextDirection.Target) AssertSimplifiedGraphIs( outputContext.Graph, <DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml"> <Nodes> <Node Id="(@1 Type=C Member=X)" Category="CodeSchema_Field" CodeSchemaProperty_IsPublic="True" CommonLabel="X" Icon="Microsoft.VisualStudio.Field.Public" Label="X"/> <Node Id="(@2 StartLineNumber=2 StartCharacterOffset=45 EndLineNumber=2 EndCharacterOffset=46)" Category="CodeSchema_SourceLocation" Icon="Microsoft.VisualStudio.Reference.Public" Label="Project.cs (3, 46): public int X;"/> <Node Id="(@2 StartLineNumber=3 StartCharacterOffset=49 EndLineNumber=3 EndCharacterOffset=50)" Category="CodeSchema_SourceLocation" Icon="Microsoft.VisualStudio.Reference.Public" Label="Project.cs (4, 50): public int Y = X * X;"/> <Node Id="(@2 StartLineNumber=3 StartCharacterOffset=53 EndLineNumber=3 EndCharacterOffset=54)" Category="CodeSchema_SourceLocation" Icon="Microsoft.VisualStudio.Reference.Public" Label="Project.cs (4, 54): public int Y = X * X;"/> <Node Id="(@2 StartLineNumber=6 StartCharacterOffset=49 EndLineNumber=6 EndCharacterOffset=50)" Category="CodeSchema_SourceLocation" Icon="Microsoft.VisualStudio.Reference.Public" Label="Project.cs (7, 50): int y = x + X;"/> </Nodes> <Links> <Link Source="(@1 Type=C Member=X)" Target="(@2 StartLineNumber=2 StartCharacterOffset=45 EndLineNumber=2 EndCharacterOffset=46)" Category="CodeSchema_SourceReferences"/> <Link Source="(@1 Type=C Member=X)" Target="(@2 StartLineNumber=3 StartCharacterOffset=49 EndLineNumber=3 EndCharacterOffset=50)" Category="CodeSchema_SourceReferences"/> <Link Source="(@1 Type=C Member=X)" Target="(@2 StartLineNumber=3 StartCharacterOffset=53 EndLineNumber=3 EndCharacterOffset=54)" Category="CodeSchema_SourceReferences"/> <Link Source="(@1 Type=C Member=X)" Target="(@2 StartLineNumber=6 StartCharacterOffset=49 EndLineNumber=6 EndCharacterOffset=50)" Category="CodeSchema_SourceReferences"/> </Links> <IdentifierAliases> <Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/> <Alias n="2" Uri="Assembly=file:///Z:/Project.cs"/> </IdentifierAliases> </DirectedGraph>) End Using End Function End Class End Namespace
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Helpers/RemoveUnnecessaryImports/CSharpUnnecessaryImportsProvider.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.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryImports { internal sealed class CSharpUnnecessaryImportsProvider : AbstractUnnecessaryImportsProvider<UsingDirectiveSyntax> { public static readonly CSharpUnnecessaryImportsProvider Instance = new(); private CSharpUnnecessaryImportsProvider() { } protected override ImmutableArray<SyntaxNode> GetUnnecessaryImports( SemanticModel model, SyntaxNode root, Func<SyntaxNode, bool> predicate, CancellationToken cancellationToken) { predicate ??= Functions<SyntaxNode>.True; var diagnostics = model.GetDiagnostics(cancellationToken: cancellationToken); if (diagnostics.IsEmpty) { return ImmutableArray<SyntaxNode>.Empty; } var unnecessaryImports = new HashSet<SyntaxNode>(); foreach (var diagnostic in diagnostics) { if (diagnostic.Id == "CS8019") { if (root.FindNode(diagnostic.Location.SourceSpan) is UsingDirectiveSyntax node && predicate(node)) { unnecessaryImports.Add(node); } } } return unnecessaryImports.ToImmutableArray(); } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.RemoveUnnecessaryImports { internal sealed class CSharpUnnecessaryImportsProvider : AbstractUnnecessaryImportsProvider<UsingDirectiveSyntax> { public static readonly CSharpUnnecessaryImportsProvider Instance = new(); private CSharpUnnecessaryImportsProvider() { } protected override ImmutableArray<SyntaxNode> GetUnnecessaryImports( SemanticModel model, SyntaxNode root, Func<SyntaxNode, bool> predicate, CancellationToken cancellationToken) { predicate ??= Functions<SyntaxNode>.True; var diagnostics = model.GetDiagnostics(cancellationToken: cancellationToken); if (diagnostics.IsEmpty) { return ImmutableArray<SyntaxNode>.Empty; } var unnecessaryImports = new HashSet<SyntaxNode>(); foreach (var diagnostic in diagnostics) { if (diagnostic.Id == "CS8019") { if (root.FindNode(diagnostic.Location.SourceSpan) is UsingDirectiveSyntax node && predicate(node)) { unnecessaryImports.Add(node); } } } return unnecessaryImports.ToImmutableArray(); } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/TestUtilities/Utilities/TestFixtureHelper`1.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.CodeAnalysis.Editor.UnitTests { internal sealed class TestFixtureHelper<TFixture> where TFixture : class, IDisposable, new() { private readonly object _gate = new(); /// <summary> /// Holds a weak reference to the current test fixture instance. This reference allows /// <see cref="GetOrCreateFixture"/> to access and add a reference to the current test fixture if one exists, /// but does not prevent the fixture from being disposed after the last reference to it is released. /// </summary> private ReferenceCountedDisposable<TFixture>.WeakReference _weakFixture; /// <summary> /// Gets a reference to a test fixture, or creates it if one does not already exist. /// </summary> /// <remarks> /// <para>The resulting test fixture will not be disposed until the last referencer disposes of its reference. /// It is possible for more than one test fixture to be created during the life of any single test, but only one /// test fixture will be live at any given point.</para> /// /// <para>The following shows how a block of test code can ensure a single test fixture is created and used /// within any given block of code:</para> /// /// <code> /// using (var fixture = GetOrCreateFixture()) /// { /// // The test fixture 'fixture' is guaranteed to not be released or replaced within this block /// } /// </code> /// </remarks> /// <returns>The test fixture instance.</returns> internal ReferenceCountedDisposable<TFixture> GetOrCreateFixture() { lock (_gate) { if (_weakFixture.TryAddReference() is { } fixture) return fixture; var result = new ReferenceCountedDisposable<TFixture>(new TFixture()); _weakFixture = new ReferenceCountedDisposable<TFixture>.WeakReference(result); return result; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests { internal sealed class TestFixtureHelper<TFixture> where TFixture : class, IDisposable, new() { private readonly object _gate = new(); /// <summary> /// Holds a weak reference to the current test fixture instance. This reference allows /// <see cref="GetOrCreateFixture"/> to access and add a reference to the current test fixture if one exists, /// but does not prevent the fixture from being disposed after the last reference to it is released. /// </summary> private ReferenceCountedDisposable<TFixture>.WeakReference _weakFixture; /// <summary> /// Gets a reference to a test fixture, or creates it if one does not already exist. /// </summary> /// <remarks> /// <para>The resulting test fixture will not be disposed until the last referencer disposes of its reference. /// It is possible for more than one test fixture to be created during the life of any single test, but only one /// test fixture will be live at any given point.</para> /// /// <para>The following shows how a block of test code can ensure a single test fixture is created and used /// within any given block of code:</para> /// /// <code> /// using (var fixture = GetOrCreateFixture()) /// { /// // The test fixture 'fixture' is guaranteed to not be released or replaced within this block /// } /// </code> /// </remarks> /// <returns>The test fixture instance.</returns> internal ReferenceCountedDisposable<TFixture> GetOrCreateFixture() { lock (_gate) { if (_weakFixture.TryAddReference() is { } fixture) return fixture; var result = new ReferenceCountedDisposable<TFixture>(new TFixture()); _weakFixture = new ReferenceCountedDisposable<TFixture>.WeakReference(result); return result; } } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/LocalFunctionTests.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.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class LocalFunctionTests : ExpressionCompilerTestBase { [Fact] public void NoLocals() { var source = @"class C { void F(int x) { int y = x + 1; int G() { return 0; }; int z = G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.NotNull(assembly); Assert.Equal(0, assembly.Count); Assert.Equal(0, locals.Count); locals.Free(); }); } [Fact] public void Locals() { var source = @"class C { void F(int x) { int G(int y) { int z = y + 1; return z; }; G(x + 1); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "y", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (int V_0, //z int V_1) IL_0000: ldarg.0 IL_0001: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "z", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (int V_0, //z int V_1) IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); string error; context.CompileExpression("this.F(1)", out error, testData); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); }); } [Fact] public void CapturedVariable() { var source = @"class C { int x; void F(int y) { int G() { return x + y; }; int z = G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|1_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "this", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "y", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""int C.<>c__DisplayClass1_0.y"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("this.F(1)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 13 (0xd) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ldc.i4.1 IL_0007: callvirt ""void C.F(int)"" IL_000c: ret }"); }); } [Fact] public void MultipleDisplayClasses() { var source = @"class C { void F1(int x) { int F2(int y) { int F3() => x + y; return F3(); }; F2(1); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F1>g__F3|0_1"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "x", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "y", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: ldfld ""int C.<>c__DisplayClass0_1.y"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("x + y", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldarg.1 IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y"" IL_000c: add IL_000d: ret }"); }); } // Should not bind to unnamed display class parameters // (unnamed parameters are treated as named "value"). [Fact] public void CapturedVariableNamedValue() { var source = @"class C { void F(int value) { int G() { return value + 1; }; G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "value", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.value"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("value", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.value"" IL_0006: ret }"); }); } // Should not bind to unnamed display class parameters // (unnamed parameters are treated as named "value"). [WorkItem(18426, "https://github.com/dotnet/roslyn/issues/18426")] [Fact(Skip = "18426")] public void DisplayClassParameter() { var source = @"class C { void F(int x) { int G() { return x + 1; }; G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); string error; context.CompileExpression("value", out error, testData); Assert.Equal("error CS0103: The name 'value' does not exist in the current context", error); }); } } }
// Licensed to the .NET Foundation under one or more 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.CodeGen; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class LocalFunctionTests : ExpressionCompilerTestBase { [Fact] public void NoLocals() { var source = @"class C { void F(int x) { int y = x + 1; int G() { return 0; }; int z = G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.NotNull(assembly); Assert.Equal(0, assembly.Count); Assert.Equal(0, locals.Count); locals.Free(); }); } [Fact] public void Locals() { var source = @"class C { void F(int x) { int G(int y) { int z = y + 1; return z; }; G(x + 1); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "y", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (int V_0, //z int V_1) IL_0000: ldarg.0 IL_0001: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "z", expectedILOpt: @"{ // Code size 2 (0x2) .maxstack 1 .locals init (int V_0, //z int V_1) IL_0000: ldloc.0 IL_0001: ret }"); locals.Free(); string error; context.CompileExpression("this.F(1)", out error, testData); Assert.Equal("error CS0027: Keyword 'this' is not available in the current context", error); }); } [Fact] public void CapturedVariable() { var source = @"class C { int x; void F(int y) { int G() { return x + y; }; int z = G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|1_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "this", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "y", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""int C.<>c__DisplayClass1_0.y"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("this.F(1)", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 13 (0xd) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.1 IL_0001: ldfld ""C C.<>c__DisplayClass1_0.<>4__this"" IL_0006: ldc.i4.1 IL_0007: callvirt ""void C.F(int)"" IL_000c: ret }"); }); } [Fact] public void MultipleDisplayClasses() { var source = @"class C { void F1(int x) { int F2(int y) { int F3() => x + y; return F3(); }; F2(1); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F1>g__F3|0_1"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(2, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "x", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ret }"); VerifyLocal(testData, typeName, locals[1], "<>m1", "y", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: ldfld ""int C.<>c__DisplayClass0_1.y"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("x + y", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.x"" IL_0006: ldarg.1 IL_0007: ldfld ""int C.<>c__DisplayClass0_1.y"" IL_000c: add IL_000d: ret }"); }); } // Should not bind to unnamed display class parameters // (unnamed parameters are treated as named "value"). [Fact] public void CapturedVariableNamedValue() { var source = @"class C { void F(int value) { int G() { return value + 1; }; G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); var locals = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData); Assert.Equal(1, locals.Count); VerifyLocal(testData, typeName, locals[0], "<>m0", "value", expectedILOpt: @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.value"" IL_0006: ret }"); locals.Free(); testData = new CompilationTestData(); string error; context.CompileExpression("value", out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldfld ""int C.<>c__DisplayClass0_0.value"" IL_0006: ret }"); }); } // Should not bind to unnamed display class parameters // (unnamed parameters are treated as named "value"). [WorkItem(18426, "https://github.com/dotnet/roslyn/issues/18426")] [Fact(Skip = "18426")] public void DisplayClassParameter() { var source = @"class C { void F(int x) { int G() { return x + 1; }; G(); } }"; var compilation0 = CreateCompilation(source, options: TestOptions.DebugDll); WithRuntimeInstance(compilation0, runtime => { var context = CreateMethodContext(runtime, "C.<F>g__G|0_0"); var testData = new CompilationTestData(); string error; context.CompileExpression("value", out error, testData); Assert.Equal("error CS0103: The name 'value' does not exist in the current context", error); }); } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Test/PdbUtilities/Writer/SymWriterTestUtilities.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.DiaSymReader; namespace Roslyn.Test.PdbUtilities { internal static class SymWriterTestUtilities { public static readonly Func<ISymWriterMetadataProvider, SymUnmanagedWriter> ThrowingFactory = _ => throw new SymUnmanagedWriterException("xxx", new NotSupportedException(), "<lib name>"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using Microsoft.DiaSymReader; namespace Roslyn.Test.PdbUtilities { internal static class SymWriterTestUtilities { public static readonly Func<ISymWriterMetadataProvider, SymUnmanagedWriter> ThrowingFactory = _ => throw new SymUnmanagedWriterException("xxx", new NotSupportedException(), "<lib name>"); } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Analyzers/VisualBasic/CodeFixes/FileHeaders/VisualBasicFileHeaderCodeFixProvider.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 Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.FileHeaders Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Namespace Microsoft.CodeAnalysis.VisualBasic.FileHeaders <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.FileHeader)> <[Shared]> Friend Class VisualBasicFileHeaderCodeFixProvider Inherits AbstractFileHeaderCodeFixProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides ReadOnly Property FileHeaderHelper As AbstractFileHeaderHelper Get Return VisualBasicFileHeaderHelper.Instance End Get End Property Protected Overrides ReadOnly Property SyntaxFacts As ISyntaxFacts Get Return VisualBasicSyntaxFacts.Instance End Get End Property Protected Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds Get Return VisualBasicSyntaxKinds.Instance End Get End Property Protected Overrides Function EndOfLine(text As String) As SyntaxTrivia Return SyntaxFactory.EndOfLine(text) 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 Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.FileHeaders Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Namespace Microsoft.CodeAnalysis.VisualBasic.FileHeaders <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.FileHeader)> <[Shared]> Friend Class VisualBasicFileHeaderCodeFixProvider Inherits AbstractFileHeaderCodeFixProvider <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Protected Overrides ReadOnly Property FileHeaderHelper As AbstractFileHeaderHelper Get Return VisualBasicFileHeaderHelper.Instance End Get End Property Protected Overrides ReadOnly Property SyntaxFacts As ISyntaxFacts Get Return VisualBasicSyntaxFacts.Instance End Get End Property Protected Overrides ReadOnly Property SyntaxKinds As ISyntaxKinds Get Return VisualBasicSyntaxKinds.Instance End Get End Property Protected Overrides Function EndOfLine(text As String) As SyntaxTrivia Return SyntaxFactory.EndOfLine(text) End Function End Class End Namespace
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/ClassKeywordRecommenderTests.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 ClassKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Class") End Sub <Fact, WorkItem(530727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530727")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassFollowsClassTest() Dim code = <File> Class C1 End Class | </File> VerifyRecommendationsContain(code, "Class") End Sub <Fact, WorkItem(530727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530727")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassPrecedesClassTest() Dim code = <File> | Class C1 End Class </File> VerifyRecommendationsContain(code, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassFollowsDelegateDeclarationTest() Dim code = <File> Delegate Sub DelegateType() | </File> VerifyRecommendationsContain(code, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotInMethodDeclarationTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassInNamespaceTest() VerifyRecommendationsContain(<NamespaceDeclaration>|</NamespaceDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassInInterfaceTest() VerifyRecommendationsContain(<InterfaceDeclaration>|</InterfaceDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotInEnumTest() VerifyRecommendationsMissing(<EnumDeclaration>|</EnumDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassInStructureTest() VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassInModuleTest() VerifyRecommendationsContain(<ModuleDeclaration>|</ModuleDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterPartialTest() VerifyRecommendationsContain(<File>Partial |</File>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterPublicInFileTest() VerifyRecommendationsContain(<File>Public |</File>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterPublicInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>Public |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassMissingAfterProtectedInFileTest() VerifyRecommendationsMissing(<File>Protected |</File>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassExistsAfterProtectedInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>Protected |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterFriendInFileTest() VerifyRecommendationsContain(<File>Friend |</File>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterFriendInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>Friend |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterPrivateInFileTest() VerifyRecommendationsMissing(<File>Private |</File>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterPrivateInNestedClassTest() VerifyRecommendationsContain(<ClassDeclaration>Private |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterPrivateInNamespaceTest() VerifyRecommendationsMissing(<File> Namespace Goo Private | End Namespace</File>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterProtectedFriendInFileTest() VerifyRecommendationsMissing(<File>Protected Friend |</File>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterProtectedFriendInClassTest() VerifyRecommendationsContain(<ClassDeclaration>Protected Friend |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterOverloadsTest() VerifyRecommendationsMissing(<ClassDeclaration>Overloads |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterMustOverrideOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride Overrides |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterNotOverridableOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable Overrides |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterConstTest() VerifyRecommendationsMissing(<ClassDeclaration>Const |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterDefaultTest() VerifyRecommendationsMissing(<ClassDeclaration>Default |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterMustInheritTest() VerifyRecommendationsContain(<ClassDeclaration>MustInherit |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterNotInheritableTest() VerifyRecommendationsContain(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterWideningTest() VerifyRecommendationsMissing(<ClassDeclaration>Widening |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterReadOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>ReadOnly |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterWriteOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>WriteOnly |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterCustomTest() VerifyRecommendationsMissing(<ClassDeclaration>Custom |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterSharedTest() VerifyRecommendationsMissing(<ClassDeclaration>Shared |</ClassDeclaration>, "Class") End Sub <WorkItem(547254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547254")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterAsyncTest() VerifyRecommendationsMissing(<ClassDeclaration>Async |</ClassDeclaration>, "Class") End Sub <WorkItem(20837, "https://github.com/dotnet/roslyn/issues/20837")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterAttribute() VerifyRecommendationsContain(<File>&lt;AttributeApplication&gt; |</File>, "Class") 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 ClassKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Class") End Sub <Fact, WorkItem(530727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530727")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassFollowsClassTest() Dim code = <File> Class C1 End Class | </File> VerifyRecommendationsContain(code, "Class") End Sub <Fact, WorkItem(530727, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530727")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassPrecedesClassTest() Dim code = <File> | Class C1 End Class </File> VerifyRecommendationsContain(code, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassFollowsDelegateDeclarationTest() Dim code = <File> Delegate Sub DelegateType() | </File> VerifyRecommendationsContain(code, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotInMethodDeclarationTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassInNamespaceTest() VerifyRecommendationsContain(<NamespaceDeclaration>|</NamespaceDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassInInterfaceTest() VerifyRecommendationsContain(<InterfaceDeclaration>|</InterfaceDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotInEnumTest() VerifyRecommendationsMissing(<EnumDeclaration>|</EnumDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassInStructureTest() VerifyRecommendationsContain(<StructureDeclaration>|</StructureDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassInModuleTest() VerifyRecommendationsContain(<ModuleDeclaration>|</ModuleDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterPartialTest() VerifyRecommendationsContain(<File>Partial |</File>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterPublicInFileTest() VerifyRecommendationsContain(<File>Public |</File>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterPublicInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>Public |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassMissingAfterProtectedInFileTest() VerifyRecommendationsMissing(<File>Protected |</File>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassExistsAfterProtectedInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>Protected |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterFriendInFileTest() VerifyRecommendationsContain(<File>Friend |</File>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterFriendInClassDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>Friend |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterPrivateInFileTest() VerifyRecommendationsMissing(<File>Private |</File>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterPrivateInNestedClassTest() VerifyRecommendationsContain(<ClassDeclaration>Private |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterPrivateInNamespaceTest() VerifyRecommendationsMissing(<File> Namespace Goo Private | End Namespace</File>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterProtectedFriendInFileTest() VerifyRecommendationsMissing(<File>Protected Friend |</File>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterProtectedFriendInClassTest() VerifyRecommendationsContain(<ClassDeclaration>Protected Friend |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterOverloadsTest() VerifyRecommendationsMissing(<ClassDeclaration>Overloads |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>Overrides |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>Overridable |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterNotOverridableTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterMustOverrideTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterMustOverrideOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>MustOverride Overrides |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterNotOverridableOverridesTest() VerifyRecommendationsMissing(<ClassDeclaration>NotOverridable Overrides |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterConstTest() VerifyRecommendationsMissing(<ClassDeclaration>Const |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterDefaultTest() VerifyRecommendationsMissing(<ClassDeclaration>Default |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterMustInheritTest() VerifyRecommendationsContain(<ClassDeclaration>MustInherit |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassAfterNotInheritableTest() VerifyRecommendationsContain(<ClassDeclaration>NotInheritable |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterNarrowingTest() VerifyRecommendationsMissing(<ClassDeclaration>Narrowing |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterWideningTest() VerifyRecommendationsMissing(<ClassDeclaration>Widening |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterReadOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>ReadOnly |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterWriteOnlyTest() VerifyRecommendationsMissing(<ClassDeclaration>WriteOnly |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterCustomTest() VerifyRecommendationsMissing(<ClassDeclaration>Custom |</ClassDeclaration>, "Class") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ClassNotAfterSharedTest() VerifyRecommendationsMissing(<ClassDeclaration>Shared |</ClassDeclaration>, "Class") End Sub <WorkItem(547254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547254")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterAsyncTest() VerifyRecommendationsMissing(<ClassDeclaration>Async |</ClassDeclaration>, "Class") End Sub <WorkItem(20837, "https://github.com/dotnet/roslyn/issues/20837")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterAttribute() VerifyRecommendationsContain(<File>&lt;AttributeApplication&gt; |</File>, "Class") End Sub End Class End Namespace
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasicTest/Recommendations/OnErrorStatements/ErrorKeywordRecommenderTests.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.OnErrorStatements Public Class ErrorKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ErrorOptionsAfterOnTest() ' We can always exit a Sub/Function, so it should be there VerifyRecommendationsAreExactly(<MethodBody>On |</MethodBody>, "Error Resume Next", "Error GoTo") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ErrorStatementInMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Error") End Sub <Fact> <WorkItem(899057, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899057")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ErrorStatementInLambdaTest() Dim code = <File> Public Class Z Public Sub Main() Dim c = Sub() | End Sub End Class</File> VerifyRecommendationsContain(code, "Error") 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.OnErrorStatements Public Class ErrorKeywordRecommenderTests <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ErrorOptionsAfterOnTest() ' We can always exit a Sub/Function, so it should be there VerifyRecommendationsAreExactly(<MethodBody>On |</MethodBody>, "Error Resume Next", "Error GoTo") End Sub <Fact> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ErrorStatementInMethodBodyTest() VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Error") End Sub <Fact> <WorkItem(899057, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899057")> <Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub ErrorStatementInLambdaTest() Dim code = <File> Public Class Z Public Sub Main() Dim c = Sub() | End Sub End Class</File> VerifyRecommendationsContain(code, "Error") End Sub End Class End Namespace
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/IReferenceCountedDisposable.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 Roslyn.Utilities { /// <summary> /// A covariant interface form of <see cref="ReferenceCountedDisposable{T}"/> that lets you re-cast an <see cref="ReferenceCountedDisposable{T}"/> /// to a more base type. This can include types that do not implement <see cref="IDisposable"/> if you want to prevent a caller from accidentally /// disposing <see cref="Target"/> directly. /// </summary> /// <typeparam name="T"></typeparam> internal interface IReferenceCountedDisposable<out T> : IDisposable #if !CODE_STYLE , IAsyncDisposable #endif where T : class { /// <summary> /// Gets the target object. /// </summary> /// <remarks> /// <para>This call is not valid after <see cref="IDisposable.Dispose"/> is called. If this property or the target /// object is used concurrently with a call to <see cref="IDisposable.Dispose"/>, it is possible for the code to be /// using a disposed object. After the current instance is disposed, this property throws /// <see cref="ObjectDisposedException"/>. However, the exact time when this property starts throwing after /// <see cref="IDisposable.Dispose"/> is called is unspecified; code is expected to not use this property or the object /// it returns after any code invokes <see cref="IDisposable.Dispose"/>.</para> /// </remarks> /// <value>The target object.</value> T Target { get; } /// <summary> /// Increments the reference count for the disposable object, and returns a new disposable reference to it. /// </summary> /// <remarks> /// <para>The returned object is an independent reference to the same underlying object. Disposing of the /// returned value multiple times will only cause the reference count to be decreased once.</para> /// </remarks> /// <returns>A new <see cref="ReferenceCountedDisposable{T}"/> pointing to the same underlying object, if it /// has not yet been disposed; otherwise, <see langword="null"/> if this reference to the underlying object /// has already been disposed.</returns> IReferenceCountedDisposable<T>? TryAddReference(); } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities { /// <summary> /// A covariant interface form of <see cref="ReferenceCountedDisposable{T}"/> that lets you re-cast an <see cref="ReferenceCountedDisposable{T}"/> /// to a more base type. This can include types that do not implement <see cref="IDisposable"/> if you want to prevent a caller from accidentally /// disposing <see cref="Target"/> directly. /// </summary> /// <typeparam name="T"></typeparam> internal interface IReferenceCountedDisposable<out T> : IDisposable #if !CODE_STYLE , IAsyncDisposable #endif where T : class { /// <summary> /// Gets the target object. /// </summary> /// <remarks> /// <para>This call is not valid after <see cref="IDisposable.Dispose"/> is called. If this property or the target /// object is used concurrently with a call to <see cref="IDisposable.Dispose"/>, it is possible for the code to be /// using a disposed object. After the current instance is disposed, this property throws /// <see cref="ObjectDisposedException"/>. However, the exact time when this property starts throwing after /// <see cref="IDisposable.Dispose"/> is called is unspecified; code is expected to not use this property or the object /// it returns after any code invokes <see cref="IDisposable.Dispose"/>.</para> /// </remarks> /// <value>The target object.</value> T Target { get; } /// <summary> /// Increments the reference count for the disposable object, and returns a new disposable reference to it. /// </summary> /// <remarks> /// <para>The returned object is an independent reference to the same underlying object. Disposing of the /// returned value multiple times will only cause the reference count to be decreased once.</para> /// </remarks> /// <returns>A new <see cref="ReferenceCountedDisposable{T}"/> pointing to the same underlying object, if it /// has not yet been disposed; otherwise, <see langword="null"/> if this reference to the underlying object /// has already been disposed.</returns> IReferenceCountedDisposable<T>? TryAddReference(); } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/xlf/Resources.pl.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pl" original="../Resources.resx"> <body> <trans-unit id="InvalidDebuggerStatement"> <source>Statements of type '{0}' are not allowed in the Immediate window.</source> <target state="translated">Instrukcje typu „{0}” nie są dozwolone w oknie bezpośrednim.</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="pl" original="../Resources.resx"> <body> <trans-unit id="InvalidDebuggerStatement"> <source>Statements of type '{0}' are not allowed in the Immediate window.</source> <target state="translated">Instrukcje typu „{0}” nie są dozwolone w oknie bezpośrednim.</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Extensions/SyntaxEditorExtensions.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.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SyntaxEditorExtensions { /// <summary> /// Performs several edits to a document. If multiple edits are made within the same /// expression context, then the document/semantic-model will be forked after each edit /// so that further edits can see if they're still safe to apply. /// </summary> public static Task ApplyExpressionLevelSemanticEditsAsync<TType, TNode>( this SyntaxEditor editor, Document document, ImmutableArray<TType> originalNodes, Func<TType, (TNode semanticNode, IEnumerable<TNode> additionalNodes)> selector, Func<SemanticModel, TType, TNode, bool> canReplace, Func<SemanticModel, SyntaxNode, TType, TNode, SyntaxNode> updateRoot, CancellationToken cancellationToken) where TNode : SyntaxNode { return ApplySemanticEditsAsync( editor, document, originalNodes, selector, (syntaxFacts, node) => GetExpressionSemanticBoundary(syntaxFacts, node), canReplace, updateRoot, cancellationToken); } /// <summary> /// Performs several edits to a document. If multiple edits are made within the same /// expression context, then the document/semantic-model will be forked after each edit /// so that further edits can see if they're still safe to apply. /// </summary> public static Task ApplyExpressionLevelSemanticEditsAsync<TType, TNode>( this SyntaxEditor editor, Document document, ImmutableArray<TType> originalNodes, Func<TType, TNode> selector, Func<SemanticModel, TType, TNode, bool> canReplace, Func<SemanticModel, SyntaxNode, TType, TNode, SyntaxNode> updateRoot, CancellationToken cancellationToken) where TNode : SyntaxNode { return ApplySemanticEditsAsync( editor, document, originalNodes, t => (selector(t), Enumerable.Empty<TNode>()), (syntaxFacts, node) => GetExpressionSemanticBoundary(syntaxFacts, node), canReplace, updateRoot, cancellationToken); } /// <summary> /// Performs several edits to a document. If multiple edits are made within the same /// expression context, then the document/semantic-model will be forked after each edit /// so that further edits can see if they're still safe to apply. /// </summary> public static Task ApplyExpressionLevelSemanticEditsAsync<TNode>( this SyntaxEditor editor, Document document, ImmutableArray<TNode> originalNodes, Func<SemanticModel, TNode, bool> canReplace, Func<SemanticModel, SyntaxNode, TNode, SyntaxNode> updateRoot, CancellationToken cancellationToken) where TNode : SyntaxNode { return ApplyExpressionLevelSemanticEditsAsync( editor, document, originalNodes, t => (t, Enumerable.Empty<TNode>()), (semanticModel, _, node) => canReplace(semanticModel, node), (semanticModel, currentRoot, _, node) => updateRoot(semanticModel, currentRoot, node), cancellationToken); } /// <summary> /// Performs several edits to a document. If multiple edits are made within a method /// body then the document/semantic-model will be forked after each edit so that further /// edits can see if they're still safe to apply. /// </summary> public static Task ApplyMethodBodySemanticEditsAsync<TType, TNode>( this SyntaxEditor editor, Document document, ImmutableArray<TType> originalNodes, Func<TType, (TNode semanticNode, IEnumerable<TNode> additionalNodes)> selector, Func<SemanticModel, TType, TNode, bool> canReplace, Func<SemanticModel, SyntaxNode, TType, TNode, SyntaxNode> updateRoot, CancellationToken cancellationToken) where TNode : SyntaxNode { return ApplySemanticEditsAsync( editor, document, originalNodes, selector, (syntaxFacts, node) => GetMethodBodySemanticBoundary(syntaxFacts, node), canReplace, updateRoot, cancellationToken); } /// <summary> /// Performs several edits to a document. If multiple edits are made within a method /// body then the document/semantic-model will be forked after each edit so that further /// edits can see if they're still safe to apply. /// </summary> public static Task ApplyMethodBodySemanticEditsAsync<TNode>( this SyntaxEditor editor, Document document, ImmutableArray<TNode> originalNodes, Func<SemanticModel, TNode, bool> canReplace, Func<SemanticModel, SyntaxNode, TNode, SyntaxNode> updateRoot, CancellationToken cancellationToken) where TNode : SyntaxNode { return ApplyMethodBodySemanticEditsAsync( editor, document, originalNodes, t => (t, Enumerable.Empty<TNode>()), (semanticModel, node, _) => canReplace(semanticModel, node), (semanticModel, currentRoot, _, node) => updateRoot(semanticModel, currentRoot, node), cancellationToken); } /// <summary> /// Helper function for fix-all fixes where individual fixes may affect the viability /// of another. For example, consider the following code: /// /// if ((double)x == (double)y) /// /// In this code either cast can be removed, but at least one cast must remain. Even /// though an analyzer marks both, a fixer must not remove both. One way to accomplish /// this would be to have the fixer do a semantic check after each application. However /// This is extremely expensive, especially for hte common cases where one fix does /// not affect each other. /// /// To address that, this helper groups fixes at certain boundary points. i.e. at /// statement boundaries. If there is only one fix within the boundary, it does not /// do any semantic verification. However, if there are multiple fixes in a boundary /// it will call into <paramref name="canReplace"/> to validate if the subsequent fix /// can be made or not. /// </summary> private static async Task ApplySemanticEditsAsync<TType, TNode>( this SyntaxEditor editor, Document document, ImmutableArray<TType> originalNodes, Func<TType, (TNode semanticNode, IEnumerable<TNode> additionalNodes)> selector, Func<ISyntaxFactsService, SyntaxNode, SyntaxNode> getSemanticBoundary, Func<SemanticModel, TType, TNode, bool> canReplace, Func<SemanticModel, SyntaxNode, TType, TNode, SyntaxNode> updateRoot, CancellationToken cancellationToken) where TNode : SyntaxNode { IEnumerable<(TType instance, (TNode semanticNode, IEnumerable<TNode> additionalNodes) nodes)> originalNodePairs = originalNodes.Select(n => (n, selector(n))); // This code fix will not make changes that affect the semantics of a statement // or declaration. Therefore, we can skip the expensive verification step in // cases where only one expression appears within the group. var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var nodesBySemanticBoundary = originalNodePairs.GroupBy(pair => getSemanticBoundary(syntaxFacts, pair.nodes.semanticNode)); var nodesToVerify = nodesBySemanticBoundary.Where(group => group.Skip(1).Any()).Flatten().ToSet(); // We're going to be continually editing this tree. Track all the nodes we // care about so we can find them across each edit. var originalRoot = editor.OriginalRoot; document = document.WithSyntaxRoot(originalRoot.TrackNodes(originalNodePairs.SelectMany(pair => pair.nodes.additionalNodes.Concat(pair.nodes.semanticNode)))); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); foreach (var nodePair in originalNodePairs) { var (instance, (node, _)) = nodePair; var currentNode = currentRoot.GetCurrentNode(node); var skipVerification = !nodesToVerify.Contains(nodePair); if (skipVerification || canReplace(semanticModel, instance, currentNode)) { var replacementRoot = updateRoot(semanticModel, currentRoot, instance, currentNode); document = document.WithSyntaxRoot(replacementRoot); semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } } editor.ReplaceNode(originalRoot, currentRoot); } private static SyntaxNode GetExpressionSemanticBoundary(ISyntaxFactsService syntaxFacts, SyntaxNode node) { // Notes: // 1. Syntax which doesn't fall into one of the "safe buckets" will get placed into a // single group keyed off the root of the tree. If more than one such node exists // in the document, all will be verified. // 2. Cannot include ArgumentSyntax because it could affect generic argument inference. return node.FirstAncestorOrSelf<SyntaxNode, ISyntaxFactsService>( (n, syntaxFacts) => syntaxFacts.IsExecutableStatement(n) || syntaxFacts.IsParameter(n) || syntaxFacts.IsVariableDeclarator(n) || n.Parent == null, syntaxFacts); } private static SyntaxNode GetMethodBodySemanticBoundary(ISyntaxFactsService syntaxFacts, SyntaxNode node) { return node.FirstAncestorOrSelf<SyntaxNode, ISyntaxFactsService>( (n, syntaxFacts) => syntaxFacts.IsMethodBody(n) || n.Parent == null, syntaxFacts); } } }
// Licensed to the .NET Foundation under one or more 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.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static class SyntaxEditorExtensions { /// <summary> /// Performs several edits to a document. If multiple edits are made within the same /// expression context, then the document/semantic-model will be forked after each edit /// so that further edits can see if they're still safe to apply. /// </summary> public static Task ApplyExpressionLevelSemanticEditsAsync<TType, TNode>( this SyntaxEditor editor, Document document, ImmutableArray<TType> originalNodes, Func<TType, (TNode semanticNode, IEnumerable<TNode> additionalNodes)> selector, Func<SemanticModel, TType, TNode, bool> canReplace, Func<SemanticModel, SyntaxNode, TType, TNode, SyntaxNode> updateRoot, CancellationToken cancellationToken) where TNode : SyntaxNode { return ApplySemanticEditsAsync( editor, document, originalNodes, selector, (syntaxFacts, node) => GetExpressionSemanticBoundary(syntaxFacts, node), canReplace, updateRoot, cancellationToken); } /// <summary> /// Performs several edits to a document. If multiple edits are made within the same /// expression context, then the document/semantic-model will be forked after each edit /// so that further edits can see if they're still safe to apply. /// </summary> public static Task ApplyExpressionLevelSemanticEditsAsync<TType, TNode>( this SyntaxEditor editor, Document document, ImmutableArray<TType> originalNodes, Func<TType, TNode> selector, Func<SemanticModel, TType, TNode, bool> canReplace, Func<SemanticModel, SyntaxNode, TType, TNode, SyntaxNode> updateRoot, CancellationToken cancellationToken) where TNode : SyntaxNode { return ApplySemanticEditsAsync( editor, document, originalNodes, t => (selector(t), Enumerable.Empty<TNode>()), (syntaxFacts, node) => GetExpressionSemanticBoundary(syntaxFacts, node), canReplace, updateRoot, cancellationToken); } /// <summary> /// Performs several edits to a document. If multiple edits are made within the same /// expression context, then the document/semantic-model will be forked after each edit /// so that further edits can see if they're still safe to apply. /// </summary> public static Task ApplyExpressionLevelSemanticEditsAsync<TNode>( this SyntaxEditor editor, Document document, ImmutableArray<TNode> originalNodes, Func<SemanticModel, TNode, bool> canReplace, Func<SemanticModel, SyntaxNode, TNode, SyntaxNode> updateRoot, CancellationToken cancellationToken) where TNode : SyntaxNode { return ApplyExpressionLevelSemanticEditsAsync( editor, document, originalNodes, t => (t, Enumerable.Empty<TNode>()), (semanticModel, _, node) => canReplace(semanticModel, node), (semanticModel, currentRoot, _, node) => updateRoot(semanticModel, currentRoot, node), cancellationToken); } /// <summary> /// Performs several edits to a document. If multiple edits are made within a method /// body then the document/semantic-model will be forked after each edit so that further /// edits can see if they're still safe to apply. /// </summary> public static Task ApplyMethodBodySemanticEditsAsync<TType, TNode>( this SyntaxEditor editor, Document document, ImmutableArray<TType> originalNodes, Func<TType, (TNode semanticNode, IEnumerable<TNode> additionalNodes)> selector, Func<SemanticModel, TType, TNode, bool> canReplace, Func<SemanticModel, SyntaxNode, TType, TNode, SyntaxNode> updateRoot, CancellationToken cancellationToken) where TNode : SyntaxNode { return ApplySemanticEditsAsync( editor, document, originalNodes, selector, (syntaxFacts, node) => GetMethodBodySemanticBoundary(syntaxFacts, node), canReplace, updateRoot, cancellationToken); } /// <summary> /// Performs several edits to a document. If multiple edits are made within a method /// body then the document/semantic-model will be forked after each edit so that further /// edits can see if they're still safe to apply. /// </summary> public static Task ApplyMethodBodySemanticEditsAsync<TNode>( this SyntaxEditor editor, Document document, ImmutableArray<TNode> originalNodes, Func<SemanticModel, TNode, bool> canReplace, Func<SemanticModel, SyntaxNode, TNode, SyntaxNode> updateRoot, CancellationToken cancellationToken) where TNode : SyntaxNode { return ApplyMethodBodySemanticEditsAsync( editor, document, originalNodes, t => (t, Enumerable.Empty<TNode>()), (semanticModel, node, _) => canReplace(semanticModel, node), (semanticModel, currentRoot, _, node) => updateRoot(semanticModel, currentRoot, node), cancellationToken); } /// <summary> /// Helper function for fix-all fixes where individual fixes may affect the viability /// of another. For example, consider the following code: /// /// if ((double)x == (double)y) /// /// In this code either cast can be removed, but at least one cast must remain. Even /// though an analyzer marks both, a fixer must not remove both. One way to accomplish /// this would be to have the fixer do a semantic check after each application. However /// This is extremely expensive, especially for hte common cases where one fix does /// not affect each other. /// /// To address that, this helper groups fixes at certain boundary points. i.e. at /// statement boundaries. If there is only one fix within the boundary, it does not /// do any semantic verification. However, if there are multiple fixes in a boundary /// it will call into <paramref name="canReplace"/> to validate if the subsequent fix /// can be made or not. /// </summary> private static async Task ApplySemanticEditsAsync<TType, TNode>( this SyntaxEditor editor, Document document, ImmutableArray<TType> originalNodes, Func<TType, (TNode semanticNode, IEnumerable<TNode> additionalNodes)> selector, Func<ISyntaxFactsService, SyntaxNode, SyntaxNode> getSemanticBoundary, Func<SemanticModel, TType, TNode, bool> canReplace, Func<SemanticModel, SyntaxNode, TType, TNode, SyntaxNode> updateRoot, CancellationToken cancellationToken) where TNode : SyntaxNode { IEnumerable<(TType instance, (TNode semanticNode, IEnumerable<TNode> additionalNodes) nodes)> originalNodePairs = originalNodes.Select(n => (n, selector(n))); // This code fix will not make changes that affect the semantics of a statement // or declaration. Therefore, we can skip the expensive verification step in // cases where only one expression appears within the group. var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); var nodesBySemanticBoundary = originalNodePairs.GroupBy(pair => getSemanticBoundary(syntaxFacts, pair.nodes.semanticNode)); var nodesToVerify = nodesBySemanticBoundary.Where(group => group.Skip(1).Any()).Flatten().ToSet(); // We're going to be continually editing this tree. Track all the nodes we // care about so we can find them across each edit. var originalRoot = editor.OriginalRoot; document = document.WithSyntaxRoot(originalRoot.TrackNodes(originalNodePairs.SelectMany(pair => pair.nodes.additionalNodes.Concat(pair.nodes.semanticNode)))); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); foreach (var nodePair in originalNodePairs) { var (instance, (node, _)) = nodePair; var currentNode = currentRoot.GetCurrentNode(node); var skipVerification = !nodesToVerify.Contains(nodePair); if (skipVerification || canReplace(semanticModel, instance, currentNode)) { var replacementRoot = updateRoot(semanticModel, currentRoot, instance, currentNode); document = document.WithSyntaxRoot(replacementRoot); semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); currentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } } editor.ReplaceNode(originalRoot, currentRoot); } private static SyntaxNode GetExpressionSemanticBoundary(ISyntaxFactsService syntaxFacts, SyntaxNode node) { // Notes: // 1. Syntax which doesn't fall into one of the "safe buckets" will get placed into a // single group keyed off the root of the tree. If more than one such node exists // in the document, all will be verified. // 2. Cannot include ArgumentSyntax because it could affect generic argument inference. return node.FirstAncestorOrSelf<SyntaxNode, ISyntaxFactsService>( (n, syntaxFacts) => syntaxFacts.IsExecutableStatement(n) || syntaxFacts.IsParameter(n) || syntaxFacts.IsVariableDeclarator(n) || n.Parent == null, syntaxFacts); } private static SyntaxNode GetMethodBodySemanticBoundary(ISyntaxFactsService syntaxFacts, SyntaxNode node) { return node.FirstAncestorOrSelf<SyntaxNode, ISyntaxFactsService>( (n, syntaxFacts) => syntaxFacts.IsMethodBody(n) || n.Parent == null, syntaxFacts); } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/CSharp/Portable/Lowering/AsyncRewriter/AsyncStateMachine.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The class that represents a translated async or async-iterator method. /// </summary> internal sealed class AsyncStateMachine : StateMachineTypeSymbol { private readonly TypeKind _typeKind; private readonly MethodSymbol _constructor; private readonly ImmutableArray<NamedTypeSymbol> _interfaces; internal readonly TypeSymbol IteratorElementType; // only for async-iterators public AsyncStateMachine(VariableSlotAllocator variableAllocatorOpt, TypeCompilationState compilationState, MethodSymbol asyncMethod, int asyncMethodOrdinal, TypeKind typeKind) : base(variableAllocatorOpt, compilationState, asyncMethod, asyncMethodOrdinal) { _typeKind = typeKind; CSharpCompilation compilation = asyncMethod.DeclaringCompilation; var interfaces = ArrayBuilder<NamedTypeSymbol>.GetInstance(); bool isIterator = asyncMethod.IsIterator; if (isIterator) { var elementType = TypeMap.SubstituteType(asyncMethod.IteratorElementTypeWithAnnotations).Type; this.IteratorElementType = elementType; bool isEnumerable = asyncMethod.IsAsyncReturningIAsyncEnumerable(compilation); if (isEnumerable) { // IAsyncEnumerable<TResult> interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T).Construct(elementType)); } // IAsyncEnumerator<TResult> interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T).Construct(elementType)); // IValueTaskSource<bool> interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T).Construct(compilation.GetSpecialType(SpecialType.System_Boolean))); // IValueTaskSource interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource)); // IAsyncDisposable interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable)); } interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine)); _interfaces = interfaces.ToImmutableAndFree(); _constructor = isIterator ? (MethodSymbol)new IteratorConstructor(this) : new AsyncConstructor(this); } public override TypeKind TypeKind { get { return _typeKind; } } internal override MethodSymbol Constructor { get { return _constructor; } } internal override bool IsRecord => false; internal override bool IsRecordStruct => false; internal override bool HasPossibleWellKnownCloneMethod() => false; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved) { return _interfaces; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The class that represents a translated async or async-iterator method. /// </summary> internal sealed class AsyncStateMachine : StateMachineTypeSymbol { private readonly TypeKind _typeKind; private readonly MethodSymbol _constructor; private readonly ImmutableArray<NamedTypeSymbol> _interfaces; internal readonly TypeSymbol IteratorElementType; // only for async-iterators public AsyncStateMachine(VariableSlotAllocator variableAllocatorOpt, TypeCompilationState compilationState, MethodSymbol asyncMethod, int asyncMethodOrdinal, TypeKind typeKind) : base(variableAllocatorOpt, compilationState, asyncMethod, asyncMethodOrdinal) { _typeKind = typeKind; CSharpCompilation compilation = asyncMethod.DeclaringCompilation; var interfaces = ArrayBuilder<NamedTypeSymbol>.GetInstance(); bool isIterator = asyncMethod.IsIterator; if (isIterator) { var elementType = TypeMap.SubstituteType(asyncMethod.IteratorElementTypeWithAnnotations).Type; this.IteratorElementType = elementType; bool isEnumerable = asyncMethod.IsAsyncReturningIAsyncEnumerable(compilation); if (isEnumerable) { // IAsyncEnumerable<TResult> interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T).Construct(elementType)); } // IAsyncEnumerator<TResult> interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T).Construct(elementType)); // IValueTaskSource<bool> interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource_T).Construct(compilation.GetSpecialType(SpecialType.System_Boolean))); // IValueTaskSource interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Sources_IValueTaskSource)); // IAsyncDisposable interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_IAsyncDisposable)); } interfaces.Add(compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IAsyncStateMachine)); _interfaces = interfaces.ToImmutableAndFree(); _constructor = isIterator ? (MethodSymbol)new IteratorConstructor(this) : new AsyncConstructor(this); } public override TypeKind TypeKind { get { return _typeKind; } } internal override MethodSymbol Constructor { get { return _constructor; } } internal override bool IsRecord => false; internal override bool IsRecordStruct => false; internal override bool HasPossibleWellKnownCloneMethod() => false; internal override ImmutableArray<NamedTypeSymbol> InterfacesNoUseSiteDiagnostics(ConsList<TypeSymbol> basesBeingResolved) { return _interfaces; } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Features/Core/Portable/MetadataAsSource/MetadataAsSourceFileService.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.Composition; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DecompiledSource; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolMapping; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MetadataAsSource { [Export(typeof(IMetadataAsSourceFileService)), Shared] internal class MetadataAsSourceFileService : IMetadataAsSourceFileService { /// <summary> /// A lock to guard parallel accesses to this type. In practice, we presume that it's not /// an important scenario that we can be generating multiple documents in parallel, and so /// we simply take this lock around all public entrypoints to enforce sequential access. /// </summary> private readonly SemaphoreSlim _gate = new(initialCount: 1); /// <summary> /// For a description of the key, see GetKeyAsync. /// </summary> private readonly Dictionary<UniqueDocumentKey, MetadataAsSourceGeneratedFileInfo> _keyToInformation = new(); private readonly Dictionary<string, MetadataAsSourceGeneratedFileInfo> _generatedFilenameToInformation = new(StringComparer.OrdinalIgnoreCase); private IBidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId> _openedDocumentIds = BidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId>.Empty; private MetadataAsSourceWorkspace? _workspace; /// <summary> /// We create a mutex so other processes can see if our directory is still alive. We destroy the mutex when /// we purge our generated files. /// </summary> private Mutex? _mutex; private string? _rootTemporaryPathWithGuid; private readonly string _rootTemporaryPath; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MetadataAsSourceFileService() => _rootTemporaryPath = Path.Combine(Path.GetTempPath(), "MetadataAsSource"); private static string CreateMutexName(string directoryName) => "MetadataAsSource-" + directoryName; private string GetRootPathWithGuid_NoLock() { if (_rootTemporaryPathWithGuid == null) { var guidString = Guid.NewGuid().ToString("N"); _rootTemporaryPathWithGuid = Path.Combine(_rootTemporaryPath, guidString); _mutex = new Mutex(initiallyOwned: true, name: CreateMutexName(guidString)); } return _rootTemporaryPathWithGuid; } public async Task<MetadataAsSourceFile> GetGeneratedFileAsync(Project project, ISymbol symbol, bool allowDecompilation, CancellationToken cancellationToken = default) { if (project == null) { throw new ArgumentNullException(nameof(project)); } if (symbol == null) { throw new ArgumentNullException(nameof(symbol)); } if (symbol.Kind == SymbolKind.Namespace) { throw new ArgumentException(FeaturesResources.symbol_cannot_be_a_namespace, nameof(symbol)); } symbol = symbol.GetOriginalUnreducedDefinition(); MetadataAsSourceGeneratedFileInfo fileInfo; Location? navigateLocation = null; var topLevelNamedType = MetadataAsSourceHelpers.GetTopLevelContainingNamedType(symbol); var symbolId = SymbolKey.Create(symbol, cancellationToken); var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { InitializeWorkspace(project); Contract.ThrowIfNull(_workspace); var infoKey = await GetUniqueDocumentKeyAsync(project, topLevelNamedType, allowDecompilation, cancellationToken).ConfigureAwait(false); fileInfo = _keyToInformation.GetOrAdd(infoKey, _ => new MetadataAsSourceGeneratedFileInfo(GetRootPathWithGuid_NoLock(), project, topLevelNamedType, allowDecompilation)); _generatedFilenameToInformation[fileInfo.TemporaryFilePath] = fileInfo; if (!File.Exists(fileInfo.TemporaryFilePath)) { // We need to generate this. First, we'll need a temporary project to do the generation into. We // avoid loading the actual file from disk since it doesn't exist yet. var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: false); var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1) .GetDocument(temporaryProjectInfoAndDocumentId.Item2); Contract.ThrowIfNull(temporaryDocument, "The temporary ProjectInfo didn't contain the document it said it would."); var useDecompiler = allowDecompilation; if (useDecompiler) { useDecompiler = !symbol.ContainingAssembly.GetAttributes().Any(attribute => attribute.AttributeClass?.Name == nameof(SuppressIldasmAttribute) && attribute.AttributeClass.ToNameDisplayString() == typeof(SuppressIldasmAttribute).FullName); } if (useDecompiler) { try { var decompiledSourceService = temporaryDocument.GetLanguageService<IDecompiledSourceService>(); if (decompiledSourceService != null) { temporaryDocument = await decompiledSourceService.AddSourceToAsync(temporaryDocument, compilation, symbol, cancellationToken).ConfigureAwait(false); } else { useDecompiler = false; } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { useDecompiler = false; } } if (!useDecompiler) { var sourceFromMetadataService = temporaryDocument.Project.LanguageServices.GetRequiredService<IMetadataAsSourceService>(); temporaryDocument = await sourceFromMetadataService.AddSourceToAsync(temporaryDocument, compilation, symbol, cancellationToken).ConfigureAwait(false); } // We have the content, so write it out to disk var text = await temporaryDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); // Create the directory. It's possible a parallel deletion is happening in another process, so we may have // to retry this a few times. var directoryToCreate = Path.GetDirectoryName(fileInfo.TemporaryFilePath)!; while (!Directory.Exists(directoryToCreate)) { try { Directory.CreateDirectory(directoryToCreate); } catch (DirectoryNotFoundException) { } catch (UnauthorizedAccessException) { } } using (var textWriter = new StreamWriter(fileInfo.TemporaryFilePath, append: false, encoding: MetadataAsSourceGeneratedFileInfo.Encoding)) { text.Write(textWriter, cancellationToken); } // Mark read-only new FileInfo(fileInfo.TemporaryFilePath).IsReadOnly = true; // Locate the target in the thing we just created navigateLocation = await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false); } // If we don't have a location yet, then that means we're re-using an existing file. In this case, we'll want to relocate the symbol. if (navigateLocation == null) { navigateLocation = await RelocateSymbol_NoLockAsync(fileInfo, symbolId, cancellationToken).ConfigureAwait(false); } } var documentName = string.Format( "{0} [{1}]", topLevelNamedType.Name, FeaturesResources.from_metadata); var documentTooltip = topLevelNamedType.ToDisplayString(new SymbolDisplayFormat(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces)); return new MetadataAsSourceFile(fileInfo.TemporaryFilePath, navigateLocation, documentName, documentTooltip); } private async Task<Location> RelocateSymbol_NoLockAsync(MetadataAsSourceGeneratedFileInfo fileInfo, SymbolKey symbolId, CancellationToken cancellationToken) { Contract.ThrowIfNull(_workspace); // We need to relocate the symbol in the already existing file. If the file is open, we can just // reuse that workspace. Otherwise, we have to go spin up a temporary project to do the binding. if (_openedDocumentIds.TryGetValue(fileInfo, out var openDocumentId)) { // Awesome, it's already open. Let's try to grab a document for it var document = _workspace.CurrentSolution.GetDocument(openDocumentId); return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, document, cancellationToken).ConfigureAwait(false); } // Annoying case: the file is still on disk. Only real option here is to spin up a fake project to go and bind in. var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true); var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1) .GetDocument(temporaryProjectInfoAndDocumentId.Item2); return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false); } public bool TryAddDocumentToWorkspace(string filePath, SourceTextContainer sourceTextContainer) { using (_gate.DisposableWait()) { if (_generatedFilenameToInformation.TryGetValue(filePath, out var fileInfo)) { Contract.ThrowIfNull(_workspace); Contract.ThrowIfTrue(_openedDocumentIds.ContainsKey(fileInfo)); // We do own the file, so let's open it up in our workspace var newProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true); _workspace.OnProjectAdded(newProjectInfoAndDocumentId.Item1); _workspace.OnDocumentOpened(newProjectInfoAndDocumentId.Item2, sourceTextContainer); _openedDocumentIds = _openedDocumentIds.Add(fileInfo, newProjectInfoAndDocumentId.Item2); return true; } } return false; } public bool TryRemoveDocumentFromWorkspace(string filePath) { using (_gate.DisposableWait()) { if (_generatedFilenameToInformation.TryGetValue(filePath, out var fileInfo)) { if (_openedDocumentIds.ContainsKey(fileInfo)) { RemoveDocumentFromWorkspace_NoLock(fileInfo); return true; } } } return false; } private void RemoveDocumentFromWorkspace_NoLock(MetadataAsSourceGeneratedFileInfo fileInfo) { var documentId = _openedDocumentIds.GetValueOrDefault(fileInfo); Contract.ThrowIfNull(documentId); Contract.ThrowIfNull(_workspace); _workspace.OnDocumentClosed(documentId, new FileTextLoader(fileInfo.TemporaryFilePath, MetadataAsSourceGeneratedFileInfo.Encoding)); _workspace.OnProjectRemoved(documentId.ProjectId); _openedDocumentIds = _openedDocumentIds.RemoveKey(fileInfo); } private static async Task<UniqueDocumentKey> GetUniqueDocumentKeyAsync(Project project, INamedTypeSymbol topLevelNamedType, bool allowDecompilation, CancellationToken cancellationToken) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(compilation, "We are trying to produce a key for a language that doesn't support compilations."); var peMetadataReference = compilation.GetMetadataReference(topLevelNamedType.ContainingAssembly) as PortableExecutableReference; if (peMetadataReference?.FilePath != null) { return new UniqueDocumentKey(peMetadataReference.FilePath, peMetadataReference.GetMetadataId(), project.Language, SymbolKey.Create(topLevelNamedType, cancellationToken), allowDecompilation); } else { var containingAssembly = topLevelNamedType.ContainingAssembly; return new UniqueDocumentKey(containingAssembly.Identity, containingAssembly.GetMetadata()?.Id, project.Language, SymbolKey.Create(topLevelNamedType, cancellationToken), allowDecompilation); } } private void InitializeWorkspace(Project project) { if (_workspace == null) { _workspace = new MetadataAsSourceWorkspace(this, project.Solution.Workspace.Services.HostServices); } } internal async Task<SymbolMappingResult?> MapSymbolAsync(Document document, SymbolKey symbolId, CancellationToken cancellationToken) { MetadataAsSourceGeneratedFileInfo? fileInfo; using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { if (!_openedDocumentIds.TryGetKey(document.Id, out fileInfo)) { return null; } } // WARNING: do not touch any state fields outside the lock. var solution = fileInfo.Workspace.CurrentSolution; var project = solution.GetProject(fileInfo.SourceProjectId); if (project == null) { return null; } var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var resolutionResult = symbolId.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken); if (resolutionResult.Symbol == null) { return null; } return new SymbolMappingResult(project, resolutionResult.Symbol); } public void CleanupGeneratedFiles() { using (_gate.DisposableWait()) { // Release our mutex to indicate we're no longer using our directory and reset state if (_mutex != null) { _mutex.Dispose(); _mutex = null; _rootTemporaryPathWithGuid = null; } // Clone the list so we don't break our own enumeration var generatedFileInfoList = _generatedFilenameToInformation.Values.ToList(); foreach (var generatedFileInfo in generatedFileInfoList) { if (_openedDocumentIds.ContainsKey(generatedFileInfo)) { RemoveDocumentFromWorkspace_NoLock(generatedFileInfo); } } _generatedFilenameToInformation.Clear(); _keyToInformation.Clear(); Contract.ThrowIfFalse(_openedDocumentIds.IsEmpty); try { if (Directory.Exists(_rootTemporaryPath)) { var deletedEverything = true; // Let's look through directories to delete. foreach (var directoryInfo in new DirectoryInfo(_rootTemporaryPath).EnumerateDirectories()) { // Is there a mutex for this one? if (Mutex.TryOpenExisting(CreateMutexName(directoryInfo.Name), out var acquiredMutex)) { acquiredMutex.Dispose(); deletedEverything = false; continue; } TryDeleteFolderWhichContainsReadOnlyFiles(directoryInfo.FullName); } if (deletedEverything) { Directory.Delete(_rootTemporaryPath); } } } catch (Exception) { } } } private static void TryDeleteFolderWhichContainsReadOnlyFiles(string directoryPath) { try { foreach (var fileInfo in new DirectoryInfo(directoryPath).EnumerateFiles("*", SearchOption.AllDirectories)) { fileInfo.IsReadOnly = false; } Directory.Delete(directoryPath, recursive: true); } catch (Exception) { } } public bool IsNavigableMetadataSymbol(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.NamedType: case SymbolKind.Property: case SymbolKind.Parameter: return true; } return false; } public Workspace? TryGetWorkspace() => _workspace; private class UniqueDocumentKey : IEquatable<UniqueDocumentKey> { private static readonly IEqualityComparer<SymbolKey> s_symbolIdComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); /// <summary> /// The path to the assembly. Null in the case of in-memory assemblies, where we then use assembly identity. /// </summary> private readonly string? _filePath; /// <summary> /// Assembly identity. Only non-null if <see cref="_filePath"/> is null, where it's an in-memory assembly. /// </summary> private readonly AssemblyIdentity? _assemblyIdentity; private readonly MetadataId? _metadataId; private readonly string _language; private readonly SymbolKey _symbolId; private readonly bool _allowDecompilation; public UniqueDocumentKey(string filePath, MetadataId? metadataId, string language, SymbolKey symbolId, bool allowDecompilation) { Contract.ThrowIfNull(filePath); _filePath = filePath; _metadataId = metadataId; _language = language; _symbolId = symbolId; _allowDecompilation = allowDecompilation; } public UniqueDocumentKey(AssemblyIdentity assemblyIdentity, MetadataId? metadataId, string language, SymbolKey symbolId, bool allowDecompilation) { Contract.ThrowIfNull(assemblyIdentity); _assemblyIdentity = assemblyIdentity; _metadataId = metadataId; _language = language; _symbolId = symbolId; _allowDecompilation = allowDecompilation; } public bool Equals(UniqueDocumentKey? other) { if (other == null) { return false; } return StringComparer.OrdinalIgnoreCase.Equals(_filePath, other._filePath) && object.Equals(_assemblyIdentity, other._assemblyIdentity) && object.Equals(_metadataId, other._metadataId) && _language == other._language && s_symbolIdComparer.Equals(_symbolId, other._symbolId) && _allowDecompilation == other._allowDecompilation; } public override bool Equals(object? obj) => Equals(obj as UniqueDocumentKey); public override int GetHashCode() { return Hash.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(_filePath ?? string.Empty), Hash.Combine(_assemblyIdentity?.GetHashCode() ?? 0, Hash.Combine(_metadataId?.GetHashCode() ?? 0, Hash.Combine(_language.GetHashCode(), Hash.Combine(s_symbolIdComparer.GetHashCode(_symbolId), _allowDecompilation.GetHashCode()))))); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Composition; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DecompiledSource; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SymbolMapping; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MetadataAsSource { [Export(typeof(IMetadataAsSourceFileService)), Shared] internal class MetadataAsSourceFileService : IMetadataAsSourceFileService { /// <summary> /// A lock to guard parallel accesses to this type. In practice, we presume that it's not /// an important scenario that we can be generating multiple documents in parallel, and so /// we simply take this lock around all public entrypoints to enforce sequential access. /// </summary> private readonly SemaphoreSlim _gate = new(initialCount: 1); /// <summary> /// For a description of the key, see GetKeyAsync. /// </summary> private readonly Dictionary<UniqueDocumentKey, MetadataAsSourceGeneratedFileInfo> _keyToInformation = new(); private readonly Dictionary<string, MetadataAsSourceGeneratedFileInfo> _generatedFilenameToInformation = new(StringComparer.OrdinalIgnoreCase); private IBidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId> _openedDocumentIds = BidirectionalMap<MetadataAsSourceGeneratedFileInfo, DocumentId>.Empty; private MetadataAsSourceWorkspace? _workspace; /// <summary> /// We create a mutex so other processes can see if our directory is still alive. We destroy the mutex when /// we purge our generated files. /// </summary> private Mutex? _mutex; private string? _rootTemporaryPathWithGuid; private readonly string _rootTemporaryPath; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MetadataAsSourceFileService() => _rootTemporaryPath = Path.Combine(Path.GetTempPath(), "MetadataAsSource"); private static string CreateMutexName(string directoryName) => "MetadataAsSource-" + directoryName; private string GetRootPathWithGuid_NoLock() { if (_rootTemporaryPathWithGuid == null) { var guidString = Guid.NewGuid().ToString("N"); _rootTemporaryPathWithGuid = Path.Combine(_rootTemporaryPath, guidString); _mutex = new Mutex(initiallyOwned: true, name: CreateMutexName(guidString)); } return _rootTemporaryPathWithGuid; } public async Task<MetadataAsSourceFile> GetGeneratedFileAsync(Project project, ISymbol symbol, bool allowDecompilation, CancellationToken cancellationToken = default) { if (project == null) { throw new ArgumentNullException(nameof(project)); } if (symbol == null) { throw new ArgumentNullException(nameof(symbol)); } if (symbol.Kind == SymbolKind.Namespace) { throw new ArgumentException(FeaturesResources.symbol_cannot_be_a_namespace, nameof(symbol)); } symbol = symbol.GetOriginalUnreducedDefinition(); MetadataAsSourceGeneratedFileInfo fileInfo; Location? navigateLocation = null; var topLevelNamedType = MetadataAsSourceHelpers.GetTopLevelContainingNamedType(symbol); var symbolId = SymbolKey.Create(symbol, cancellationToken); var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { InitializeWorkspace(project); Contract.ThrowIfNull(_workspace); var infoKey = await GetUniqueDocumentKeyAsync(project, topLevelNamedType, allowDecompilation, cancellationToken).ConfigureAwait(false); fileInfo = _keyToInformation.GetOrAdd(infoKey, _ => new MetadataAsSourceGeneratedFileInfo(GetRootPathWithGuid_NoLock(), project, topLevelNamedType, allowDecompilation)); _generatedFilenameToInformation[fileInfo.TemporaryFilePath] = fileInfo; if (!File.Exists(fileInfo.TemporaryFilePath)) { // We need to generate this. First, we'll need a temporary project to do the generation into. We // avoid loading the actual file from disk since it doesn't exist yet. var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: false); var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1) .GetDocument(temporaryProjectInfoAndDocumentId.Item2); Contract.ThrowIfNull(temporaryDocument, "The temporary ProjectInfo didn't contain the document it said it would."); var useDecompiler = allowDecompilation; if (useDecompiler) { useDecompiler = !symbol.ContainingAssembly.GetAttributes().Any(attribute => attribute.AttributeClass?.Name == nameof(SuppressIldasmAttribute) && attribute.AttributeClass.ToNameDisplayString() == typeof(SuppressIldasmAttribute).FullName); } if (useDecompiler) { try { var decompiledSourceService = temporaryDocument.GetLanguageService<IDecompiledSourceService>(); if (decompiledSourceService != null) { temporaryDocument = await decompiledSourceService.AddSourceToAsync(temporaryDocument, compilation, symbol, cancellationToken).ConfigureAwait(false); } else { useDecompiler = false; } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e, cancellationToken)) { useDecompiler = false; } } if (!useDecompiler) { var sourceFromMetadataService = temporaryDocument.Project.LanguageServices.GetRequiredService<IMetadataAsSourceService>(); temporaryDocument = await sourceFromMetadataService.AddSourceToAsync(temporaryDocument, compilation, symbol, cancellationToken).ConfigureAwait(false); } // We have the content, so write it out to disk var text = await temporaryDocument.GetTextAsync(cancellationToken).ConfigureAwait(false); // Create the directory. It's possible a parallel deletion is happening in another process, so we may have // to retry this a few times. var directoryToCreate = Path.GetDirectoryName(fileInfo.TemporaryFilePath)!; while (!Directory.Exists(directoryToCreate)) { try { Directory.CreateDirectory(directoryToCreate); } catch (DirectoryNotFoundException) { } catch (UnauthorizedAccessException) { } } using (var textWriter = new StreamWriter(fileInfo.TemporaryFilePath, append: false, encoding: MetadataAsSourceGeneratedFileInfo.Encoding)) { text.Write(textWriter, cancellationToken); } // Mark read-only new FileInfo(fileInfo.TemporaryFilePath).IsReadOnly = true; // Locate the target in the thing we just created navigateLocation = await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false); } // If we don't have a location yet, then that means we're re-using an existing file. In this case, we'll want to relocate the symbol. if (navigateLocation == null) { navigateLocation = await RelocateSymbol_NoLockAsync(fileInfo, symbolId, cancellationToken).ConfigureAwait(false); } } var documentName = string.Format( "{0} [{1}]", topLevelNamedType.Name, FeaturesResources.from_metadata); var documentTooltip = topLevelNamedType.ToDisplayString(new SymbolDisplayFormat(typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces)); return new MetadataAsSourceFile(fileInfo.TemporaryFilePath, navigateLocation, documentName, documentTooltip); } private async Task<Location> RelocateSymbol_NoLockAsync(MetadataAsSourceGeneratedFileInfo fileInfo, SymbolKey symbolId, CancellationToken cancellationToken) { Contract.ThrowIfNull(_workspace); // We need to relocate the symbol in the already existing file. If the file is open, we can just // reuse that workspace. Otherwise, we have to go spin up a temporary project to do the binding. if (_openedDocumentIds.TryGetValue(fileInfo, out var openDocumentId)) { // Awesome, it's already open. Let's try to grab a document for it var document = _workspace.CurrentSolution.GetDocument(openDocumentId); return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, document, cancellationToken).ConfigureAwait(false); } // Annoying case: the file is still on disk. Only real option here is to spin up a fake project to go and bind in. var temporaryProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true); var temporaryDocument = _workspace.CurrentSolution.AddProject(temporaryProjectInfoAndDocumentId.Item1) .GetDocument(temporaryProjectInfoAndDocumentId.Item2); return await MetadataAsSourceHelpers.GetLocationInGeneratedSourceAsync(symbolId, temporaryDocument, cancellationToken).ConfigureAwait(false); } public bool TryAddDocumentToWorkspace(string filePath, SourceTextContainer sourceTextContainer) { using (_gate.DisposableWait()) { if (_generatedFilenameToInformation.TryGetValue(filePath, out var fileInfo)) { Contract.ThrowIfNull(_workspace); Contract.ThrowIfTrue(_openedDocumentIds.ContainsKey(fileInfo)); // We do own the file, so let's open it up in our workspace var newProjectInfoAndDocumentId = fileInfo.GetProjectInfoAndDocumentId(_workspace, loadFileFromDisk: true); _workspace.OnProjectAdded(newProjectInfoAndDocumentId.Item1); _workspace.OnDocumentOpened(newProjectInfoAndDocumentId.Item2, sourceTextContainer); _openedDocumentIds = _openedDocumentIds.Add(fileInfo, newProjectInfoAndDocumentId.Item2); return true; } } return false; } public bool TryRemoveDocumentFromWorkspace(string filePath) { using (_gate.DisposableWait()) { if (_generatedFilenameToInformation.TryGetValue(filePath, out var fileInfo)) { if (_openedDocumentIds.ContainsKey(fileInfo)) { RemoveDocumentFromWorkspace_NoLock(fileInfo); return true; } } } return false; } private void RemoveDocumentFromWorkspace_NoLock(MetadataAsSourceGeneratedFileInfo fileInfo) { var documentId = _openedDocumentIds.GetValueOrDefault(fileInfo); Contract.ThrowIfNull(documentId); Contract.ThrowIfNull(_workspace); _workspace.OnDocumentClosed(documentId, new FileTextLoader(fileInfo.TemporaryFilePath, MetadataAsSourceGeneratedFileInfo.Encoding)); _workspace.OnProjectRemoved(documentId.ProjectId); _openedDocumentIds = _openedDocumentIds.RemoveKey(fileInfo); } private static async Task<UniqueDocumentKey> GetUniqueDocumentKeyAsync(Project project, INamedTypeSymbol topLevelNamedType, bool allowDecompilation, CancellationToken cancellationToken) { var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(compilation, "We are trying to produce a key for a language that doesn't support compilations."); var peMetadataReference = compilation.GetMetadataReference(topLevelNamedType.ContainingAssembly) as PortableExecutableReference; if (peMetadataReference?.FilePath != null) { return new UniqueDocumentKey(peMetadataReference.FilePath, peMetadataReference.GetMetadataId(), project.Language, SymbolKey.Create(topLevelNamedType, cancellationToken), allowDecompilation); } else { var containingAssembly = topLevelNamedType.ContainingAssembly; return new UniqueDocumentKey(containingAssembly.Identity, containingAssembly.GetMetadata()?.Id, project.Language, SymbolKey.Create(topLevelNamedType, cancellationToken), allowDecompilation); } } private void InitializeWorkspace(Project project) { if (_workspace == null) { _workspace = new MetadataAsSourceWorkspace(this, project.Solution.Workspace.Services.HostServices); } } internal async Task<SymbolMappingResult?> MapSymbolAsync(Document document, SymbolKey symbolId, CancellationToken cancellationToken) { MetadataAsSourceGeneratedFileInfo? fileInfo; using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { if (!_openedDocumentIds.TryGetKey(document.Id, out fileInfo)) { return null; } } // WARNING: do not touch any state fields outside the lock. var solution = fileInfo.Workspace.CurrentSolution; var project = solution.GetProject(fileInfo.SourceProjectId); if (project == null) { return null; } var compilation = await project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false); var resolutionResult = symbolId.Resolve(compilation, ignoreAssemblyKey: true, cancellationToken: cancellationToken); if (resolutionResult.Symbol == null) { return null; } return new SymbolMappingResult(project, resolutionResult.Symbol); } public void CleanupGeneratedFiles() { using (_gate.DisposableWait()) { // Release our mutex to indicate we're no longer using our directory and reset state if (_mutex != null) { _mutex.Dispose(); _mutex = null; _rootTemporaryPathWithGuid = null; } // Clone the list so we don't break our own enumeration var generatedFileInfoList = _generatedFilenameToInformation.Values.ToList(); foreach (var generatedFileInfo in generatedFileInfoList) { if (_openedDocumentIds.ContainsKey(generatedFileInfo)) { RemoveDocumentFromWorkspace_NoLock(generatedFileInfo); } } _generatedFilenameToInformation.Clear(); _keyToInformation.Clear(); Contract.ThrowIfFalse(_openedDocumentIds.IsEmpty); try { if (Directory.Exists(_rootTemporaryPath)) { var deletedEverything = true; // Let's look through directories to delete. foreach (var directoryInfo in new DirectoryInfo(_rootTemporaryPath).EnumerateDirectories()) { // Is there a mutex for this one? if (Mutex.TryOpenExisting(CreateMutexName(directoryInfo.Name), out var acquiredMutex)) { acquiredMutex.Dispose(); deletedEverything = false; continue; } TryDeleteFolderWhichContainsReadOnlyFiles(directoryInfo.FullName); } if (deletedEverything) { Directory.Delete(_rootTemporaryPath); } } } catch (Exception) { } } } private static void TryDeleteFolderWhichContainsReadOnlyFiles(string directoryPath) { try { foreach (var fileInfo in new DirectoryInfo(directoryPath).EnumerateFiles("*", SearchOption.AllDirectories)) { fileInfo.IsReadOnly = false; } Directory.Delete(directoryPath, recursive: true); } catch (Exception) { } } public bool IsNavigableMetadataSymbol(ISymbol symbol) { switch (symbol.Kind) { case SymbolKind.Event: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.NamedType: case SymbolKind.Property: case SymbolKind.Parameter: return true; } return false; } public Workspace? TryGetWorkspace() => _workspace; private class UniqueDocumentKey : IEquatable<UniqueDocumentKey> { private static readonly IEqualityComparer<SymbolKey> s_symbolIdComparer = SymbolKey.GetComparer(ignoreCase: false, ignoreAssemblyKeys: true); /// <summary> /// The path to the assembly. Null in the case of in-memory assemblies, where we then use assembly identity. /// </summary> private readonly string? _filePath; /// <summary> /// Assembly identity. Only non-null if <see cref="_filePath"/> is null, where it's an in-memory assembly. /// </summary> private readonly AssemblyIdentity? _assemblyIdentity; private readonly MetadataId? _metadataId; private readonly string _language; private readonly SymbolKey _symbolId; private readonly bool _allowDecompilation; public UniqueDocumentKey(string filePath, MetadataId? metadataId, string language, SymbolKey symbolId, bool allowDecompilation) { Contract.ThrowIfNull(filePath); _filePath = filePath; _metadataId = metadataId; _language = language; _symbolId = symbolId; _allowDecompilation = allowDecompilation; } public UniqueDocumentKey(AssemblyIdentity assemblyIdentity, MetadataId? metadataId, string language, SymbolKey symbolId, bool allowDecompilation) { Contract.ThrowIfNull(assemblyIdentity); _assemblyIdentity = assemblyIdentity; _metadataId = metadataId; _language = language; _symbolId = symbolId; _allowDecompilation = allowDecompilation; } public bool Equals(UniqueDocumentKey? other) { if (other == null) { return false; } return StringComparer.OrdinalIgnoreCase.Equals(_filePath, other._filePath) && object.Equals(_assemblyIdentity, other._assemblyIdentity) && object.Equals(_metadataId, other._metadataId) && _language == other._language && s_symbolIdComparer.Equals(_symbolId, other._symbolId) && _allowDecompilation == other._allowDecompilation; } public override bool Equals(object? obj) => Equals(obj as UniqueDocumentKey); public override int GetHashCode() { return Hash.Combine(StringComparer.OrdinalIgnoreCase.GetHashCode(_filePath ?? string.Empty), Hash.Combine(_assemblyIdentity?.GetHashCode() ?? 0, Hash.Combine(_metadataId?.GetHashCode() ?? 0, Hash.Combine(_language.GetHashCode(), Hash.Combine(s_symbolIdComparer.GetHashCode(_symbolId), _allowDecompilation.GetHashCode()))))); } } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/PredefinedType.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.LanguageServices { internal enum PredefinedType { None = 0, Boolean = 1, Byte = 1 << 1, Char = 1 << 2, DateTime = 1 << 3, Decimal = 1 << 4, Double = 1 << 5, Int16 = 1 << 6, Int32 = 1 << 7, Int64 = 1 << 8, Object = 1 << 9, SByte = 1 << 10, Single = 1 << 11, String = 1 << 12, UInt16 = 1 << 13, UInt32 = 1 << 14, UInt64 = 1 << 15, Void = 1 << 16, } }
// Licensed to the .NET Foundation under one or more 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.LanguageServices { internal enum PredefinedType { None = 0, Boolean = 1, Byte = 1 << 1, Char = 1 << 2, DateTime = 1 << 3, Decimal = 1 << 4, Double = 1 << 5, Int16 = 1 << 6, Int32 = 1 << 7, Int64 = 1 << 8, Object = 1 << 9, SByte = 1 << 10, Single = 1 << 11, String = 1 << 12, UInt16 = 1 << 13, UInt32 = 1 << 14, UInt64 = 1 << 15, Void = 1 << 16, } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Test/CodeFixes/ErrorCases/CodeFixExceptionInFixableDiagnosticIds.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeFixes.ErrorCases { public class ExceptionInFixableDiagnosticIds : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds { get { throw new Exception($"Exception thrown in FixableDiagnosticIds of {nameof(ExceptionInFixableDiagnosticIds)}"); } } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) => Task.FromResult(true); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeFixes.ErrorCases { public class ExceptionInFixableDiagnosticIds : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds { get { throw new Exception($"Exception thrown in FixableDiagnosticIds of {nameof(ExceptionInFixableDiagnosticIds)}"); } } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) => Task.FromResult(true); } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/VisualBasicTest/ImplementAbstractClass/ImplementAbstractClassTests_FixAllTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.ImplementAbstractClass Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ImplementAbstractClass Partial Public Class ImplementAbstractClassTests <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInDocument() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class {|FixAllInDocument:B1|} Inherits A1 Implements I1 Private Class C1 Inherits A1 Implements I1 End Class End Class]]> </Document> <Document><![CDATA[ Class B2 Inherits A1 Implements I1 Private Class C2 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Class B3 Inherits A1 Implements I1 Private Class C3 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class B1 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub Private Class C1 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub End Class End Class]]> </Document> <Document><![CDATA[ Class B2 Inherits A1 Implements I1 Private Class C2 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Class B3 Inherits A1 Implements I1 Private Class C3 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInProject() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class {|FixAllInProject:B1|} Inherits A1 Implements I1 Private Class C1 Inherits A1 Implements I1 End Class End Class]]> </Document> <Document><![CDATA[ Class B2 Inherits A1 Implements I1 Private Class C2 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Class B3 Inherits A1 Implements I1 Private Class C3 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class B1 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub Private Class C1 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub End Class End Class]]> </Document> <Document><![CDATA[ Class B2 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub Private Class C2 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub End Class End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Class B3 Inherits A1 Implements I1 Private Class C3 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInSolution() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class {|FixAllInSolution:B1|} Inherits A1 Implements I1 Private Class C1 Inherits A1 Implements I1 End Class End Class]]> </Document> <Document><![CDATA[ Class B2 Inherits A1 Implements I1 Private Class C2 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Class B3 Inherits A1 Implements I1 Private Class C3 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class B1 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub Private Class C1 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub End Class End Class]]> </Document> <Document><![CDATA[ Class B2 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub Private Class C2 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub End Class End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Class B3 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub Private Class C3 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub End Class End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInSolution_DifferentAssemblyWithSameTypeName() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class {|FixAllInSolution:B1|} Inherits A1 Implements I1 Private Class C1 Inherits A1 Implements I1 End Class End Class]]> </Document> <Document><![CDATA[ Class B2 Inherits A1 Implements I1 Private Class C2 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class B3 Inherits A1 Implements I1 Private Class C3 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class B1 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub Private Class C1 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub End Class End Class]]> </Document> <Document><![CDATA[ Class B2 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub Private Class C2 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub End Class End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class B3 Inherits A1 Implements I1 Private Class C3 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.ImplementAbstractClass Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ImplementAbstractClass Partial Public Class ImplementAbstractClassTests <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInDocument() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class {|FixAllInDocument:B1|} Inherits A1 Implements I1 Private Class C1 Inherits A1 Implements I1 End Class End Class]]> </Document> <Document><![CDATA[ Class B2 Inherits A1 Implements I1 Private Class C2 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Class B3 Inherits A1 Implements I1 Private Class C3 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class B1 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub Private Class C1 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub End Class End Class]]> </Document> <Document><![CDATA[ Class B2 Inherits A1 Implements I1 Private Class C2 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Class B3 Inherits A1 Implements I1 Private Class C3 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInProject() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class {|FixAllInProject:B1|} Inherits A1 Implements I1 Private Class C1 Inherits A1 Implements I1 End Class End Class]]> </Document> <Document><![CDATA[ Class B2 Inherits A1 Implements I1 Private Class C2 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Class B3 Inherits A1 Implements I1 Private Class C3 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class B1 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub Private Class C1 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub End Class End Class]]> </Document> <Document><![CDATA[ Class B2 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub Private Class C2 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub End Class End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Class B3 Inherits A1 Implements I1 Private Class C3 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInSolution() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class {|FixAllInSolution:B1|} Inherits A1 Implements I1 Private Class C1 Inherits A1 Implements I1 End Class End Class]]> </Document> <Document><![CDATA[ Class B2 Inherits A1 Implements I1 Private Class C2 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Class B3 Inherits A1 Implements I1 Private Class C3 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class B1 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub Private Class C1 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub End Class End Class]]> </Document> <Document><![CDATA[ Class B2 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub Private Class C2 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub End Class End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <ProjectReference>Assembly1</ProjectReference> <Document><![CDATA[ Class B3 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub Private Class C3 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub End Class End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function <Fact> <Trait(Traits.Feature, Traits.Features.CodeActionsImplementAbstractClass)> <Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)> Public Async Function TestFixAllInSolution_DifferentAssemblyWithSameTypeName() As Task Dim input = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class {|FixAllInSolution:B1|} Inherits A1 Implements I1 Private Class C1 Inherits A1 Implements I1 End Class End Class]]> </Document> <Document><![CDATA[ Class B2 Inherits A1 Implements I1 Private Class C2 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class B3 Inherits A1 Implements I1 Private Class C3 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> </Workspace>.ToString() Dim expected = <Workspace> <Project Language="Visual Basic" AssemblyName="Assembly1" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class B1 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub Private Class C1 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub End Class End Class]]> </Document> <Document><![CDATA[ Class B2 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub Private Class C2 Inherits A1 Implements I1 Public Overrides Sub F1() Throw New NotImplementedException() End Sub End Class End Class]]> </Document> </Project> <Project Language="Visual Basic" AssemblyName="Assembly2" CommonReferences="true"> <Document><![CDATA[ Public MustInherit Class A1 Public MustOverride Sub F1() End Class Public Interface I1 Sub F2() End Interface Class B3 Inherits A1 Implements I1 Private Class C3 Inherits A1 Implements I1 End Class End Class]]> </Document> </Project> </Workspace>.ToString() Await TestInRegularAndScriptAsync(input, expected) End Function End Class End Namespace
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/EditorFeatures/Core.Cocoa/Preview/PreviewPaneService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Composition; using System.Globalization; using AppKit; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Core.Imaging; using Microsoft.VisualStudio.Imaging; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { [ExportWorkspaceServiceFactory(typeof(IPreviewPaneService), ServiceLayer.Host), Shared] internal class PreviewPaneService : ForegroundThreadAffinitizedObject, IPreviewPaneService, IWorkspaceServiceFactory { private readonly IImageService imageService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewPaneService(IThreadingContext threadingContext, IImageService imageService) : base(threadingContext) { this.imageService = imageService; } IWorkspaceService IWorkspaceServiceFactory.CreateService(HostWorkspaceServices workspaceServices) { return this; } #pragma warning disable IDE0051 // Remove unused private members private NSImage GetSeverityIconForDiagnostic(DiagnosticData diagnostic) #pragma warning restore IDE0051 // Remove unused private members { int? moniker = null; switch (diagnostic.Severity) { case DiagnosticSeverity.Error: moniker = KnownImageIds.StatusError; break; case DiagnosticSeverity.Warning: moniker = KnownImageIds.StatusWarning; break; case DiagnosticSeverity.Info: moniker = KnownImageIds.StatusInformation; break; case DiagnosticSeverity.Hidden: moniker = KnownImageIds.StatusHidden; break; } if (moniker.HasValue) { return (NSImage)imageService.GetImage(new ImageId(KnownImageIds.ImageCatalogGuid, moniker.Value)); } return null; } object IPreviewPaneService.GetPreviewPane( DiagnosticData data, IReadOnlyList<object> previewContent) { var title = data?.Message; if (string.IsNullOrWhiteSpace(title)) { if (previewContent == null) { // Bail out in cases where there is nothing to put in the header section // of the preview pane and no preview content (i.e. no diff view) either. return null; } return new PreviewPane( severityIcon: null, id: null, title: null, description: null, helpLink: null, helpLinkToolTipText: null, previewContent: previewContent, logIdVerbatimInTelemetry: false); } else { if (previewContent == null) { // TODO: Mac, if we have title but no content, we should still display title/help link... return null; } } var helpLinkUri = BrowserHelper.GetHelpLink(data); var helpLinkToolTip = BrowserHelper.GetHelpLinkToolTip(data.Id, helpLinkUri); return new PreviewPane( severityIcon: null,//TODO: Mac GetSeverityIconForDiagnostic(diagnostic), id: data.Id, title: title, description: data.Description.ToString(CultureInfo.CurrentUICulture), helpLink: helpLinkUri, helpLinkToolTipText: helpLinkToolTip, previewContent: previewContent, logIdVerbatimInTelemetry: data.CustomTags.Contains(WellKnownDiagnosticTags.Telemetry)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Composition; using System.Globalization; using AppKit; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Core.Imaging; using Microsoft.VisualStudio.Imaging; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { [ExportWorkspaceServiceFactory(typeof(IPreviewPaneService), ServiceLayer.Host), Shared] internal class PreviewPaneService : ForegroundThreadAffinitizedObject, IPreviewPaneService, IWorkspaceServiceFactory { private readonly IImageService imageService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewPaneService(IThreadingContext threadingContext, IImageService imageService) : base(threadingContext) { this.imageService = imageService; } IWorkspaceService IWorkspaceServiceFactory.CreateService(HostWorkspaceServices workspaceServices) { return this; } #pragma warning disable IDE0051 // Remove unused private members private NSImage GetSeverityIconForDiagnostic(DiagnosticData diagnostic) #pragma warning restore IDE0051 // Remove unused private members { int? moniker = null; switch (diagnostic.Severity) { case DiagnosticSeverity.Error: moniker = KnownImageIds.StatusError; break; case DiagnosticSeverity.Warning: moniker = KnownImageIds.StatusWarning; break; case DiagnosticSeverity.Info: moniker = KnownImageIds.StatusInformation; break; case DiagnosticSeverity.Hidden: moniker = KnownImageIds.StatusHidden; break; } if (moniker.HasValue) { return (NSImage)imageService.GetImage(new ImageId(KnownImageIds.ImageCatalogGuid, moniker.Value)); } return null; } object IPreviewPaneService.GetPreviewPane( DiagnosticData data, IReadOnlyList<object> previewContent) { var title = data?.Message; if (string.IsNullOrWhiteSpace(title)) { if (previewContent == null) { // Bail out in cases where there is nothing to put in the header section // of the preview pane and no preview content (i.e. no diff view) either. return null; } return new PreviewPane( severityIcon: null, id: null, title: null, description: null, helpLink: null, helpLinkToolTipText: null, previewContent: previewContent, logIdVerbatimInTelemetry: false); } else { if (previewContent == null) { // TODO: Mac, if we have title but no content, we should still display title/help link... return null; } } var helpLinkUri = BrowserHelper.GetHelpLink(data); var helpLinkToolTip = BrowserHelper.GetHelpLinkToolTip(data.Id, helpLinkUri); return new PreviewPane( severityIcon: null,//TODO: Mac GetSeverityIconForDiagnostic(diagnostic), id: data.Id, title: title, description: data.Description.ToString(CultureInfo.CurrentUICulture), helpLink: helpLinkUri, helpLinkToolTipText: helpLinkToolTip, previewContent: previewContent, logIdVerbatimInTelemetry: data.CustomTags.Contains(WellKnownDiagnosticTags.Telemetry)); } } }
-1
dotnet/roslyn
55,019
Fix 'match folder and namespace' with file scoped namespaces
Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
CyrusNajmabadi
2021-07-21T18:54:22Z
2021-07-22T01:00:50Z
3345d9cdff847536cd42369fd2a7529066078ee7
57f6e216347063ab2b3e21ac7e656643c1916a04
Fix 'match folder and namespace' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000
./src/Compilers/VisualBasic/Portable/BoundTree/BoundRedimClause.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundRedimClause #If DEBUG Then Private Sub Validate() Select Case Operand.Kind Case BoundKind.LateInvocation Dim invocation = DirectCast(Operand, BoundLateInvocation) If Not invocation.ArgumentsOpt.IsDefault Then For Each arg In invocation.ArgumentsOpt Debug.Assert(Not arg.IsSupportingAssignment()) Next End If End Select End Sub #End If End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundRedimClause #If DEBUG Then Private Sub Validate() Select Case Operand.Kind Case BoundKind.LateInvocation Dim invocation = DirectCast(Operand, BoundLateInvocation) If Not invocation.ArgumentsOpt.IsDefault Then For Each arg In invocation.ArgumentsOpt Debug.Assert(Not arg.IsSupportingAssignment()) Next End If End Select End Sub #End If End Class End Namespace
-1