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
unknown
date_merged
unknown
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
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Workspaces/Remote/ServiceHub/Host/TemporaryWorkspaceOptionsServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { [ExportWorkspaceServiceFactory(typeof(IOptionService), WorkspaceKind.RemoteTemporaryWorkspace), Shared] internal class TemporaryWorkspaceOptionsServiceFactory : IWorkspaceServiceFactory { private readonly IWorkspaceThreadingService? _workspaceThreadingService; private readonly ImmutableArray<Lazy<IOptionProvider, LanguageMetadata>> _providers; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TemporaryWorkspaceOptionsServiceFactory( [Import(AllowDefault = true)] IWorkspaceThreadingService? workspaceThreadingService, [ImportMany] IEnumerable<Lazy<IOptionProvider, LanguageMetadata>> optionProviders) { _workspaceThreadingService = workspaceThreadingService; _providers = optionProviders.ToImmutableArray(); } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { // give out new option service per workspace return new OptionServiceFactory.OptionService( new GlobalOptionService(_workspaceThreadingService, _providers, SpecializedCollections.EmptyEnumerable<Lazy<IOptionPersisterProvider>>()), workspaceServices); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { [ExportWorkspaceServiceFactory(typeof(IOptionService), WorkspaceKind.RemoteTemporaryWorkspace), Shared] internal class TemporaryWorkspaceOptionsServiceFactory : IWorkspaceServiceFactory { private readonly IWorkspaceThreadingService? _workspaceThreadingService; private readonly ImmutableArray<Lazy<IOptionProvider, LanguageMetadata>> _providers; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TemporaryWorkspaceOptionsServiceFactory( [Import(AllowDefault = true)] IWorkspaceThreadingService? workspaceThreadingService, [ImportMany] IEnumerable<Lazy<IOptionProvider, LanguageMetadata>> optionProviders) { _workspaceThreadingService = workspaceThreadingService; _providers = optionProviders.ToImmutableArray(); } public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices) { // give out new option service per workspace return new OptionServiceFactory.OptionService( new GlobalOptionService(_workspaceThreadingService, _providers, SpecializedCollections.EmptyEnumerable<Lazy<IOptionPersisterProvider>>()), workspaceServices); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/CSharp/Test/Semantic/Semantics/MultiDimensionalArrayTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class MultiDimensionalArrayTests : SemanticModelTestBase { [Fact] public void TestMultiDimensionalArray() { // Verify that operations on multidimensional arrays work and cause side effects only once. string source = @" using System; class P { static int M(ref int x) { int y = x; x = 456; return y; } static int counter; static int[,] A(int[,] a) { Console.Write('A'); Console.Write(counter); ++counter; return a; } static int B(int b) { Console.Write('B'); Console.Write(counter); ++counter; return b; } static int C(int c) { Console.Write('C'); Console.Write(counter); ++counter; return c; } static void Main() { int x = 4; int y = 5; int[,] a = new int[x,y]; V((A(a)[B(3),C(4)] = 123) == 123); V(M(ref A(a)[B(1),C(2)]) == 0); V(A(a)[B(1),C(2)] == 456); V(A(a)[B(3),C(4)] == 123); V(A(a)[B(0),C(0)] == 0); V(A(a)[B(0),C(0)]++ == 0); V(A(a)[B(0),C(0)] == 1); V(++A(a)[B(0),C(0)] == 2); V(A(a)[B(0),C(0)] == 2); V((A(a)[B(1),C(1)] += 3) == 3); V((A(a)[B(1),C(1)] -= 2) == 1); } static void V(bool b) { Console.WriteLine(b ? 't' : 'f'); } }"; string expected = @"A0B1C2t A3B4C5t A6B7C8t A9B10C11t A12B13C14t A15B16C17t A18B19C20t A21B22C23t A24B25C26t A27B28C29t A30B31C32t"; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [Fact] public void TestMultiDimensionalArrayInitializers() { // Verify that operations on multidimensional arrays work and cause side effects only once. string source = @" using System; class P { static void Main() { byte[,,] b = new byte[,,]{ { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } } }; int x = 999; int y = 888; int[,,] i = new int[,,]{ { { 1, 2, 3 }, { 4, 5, y } }, { { x, 8, 9 }, { 10, 11, 12 } } }; double[,,] d = new double[,,]{ { { y, y, y }, { x, x, x } }, { { x, y, x }, { 10, 11, 12 } } }; for (int j = 0 ; j < 2; ++j) for (int k = 0; k < 2; ++k) for (int l = 0; l < 3; ++l) Console.Write(b[j,k,l]); Console.WriteLine(); for (int j = 0 ; j < 2; ++j) for (int k = 0; k < 2; ++k) for (int l = 0; l < 3; ++l) Console.Write(i[j,k,l]); Console.WriteLine(); for (int j = 0 ; j < 2; ++j) for (int k = 0; k < 2; ++k) for (int l = 0; l < 3; ++l) Console.Write(d[j,k,l]); } }"; string expected = @"123456789101112 1234588899989101112 888888888999999999999888999101112"; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [Fact] public void TestMultiDimensionalArrayForEach() { string source = @" public class C { public static void Main() { int y = 50; foreach (var x in new int[2, 3] {{10, 20, 30}, {40, y, 60}}) { System.Console.Write(x); } } }"; string expected = @"102030405060"; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [WorkItem(544081, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544081")] [Fact()] public void MultiDimArrayGenericTypeWiderThanArrayType() { string source = @" class Program { public static void Ref<T>(T[,] array) { array[0, 0].GetType(); } static void Main(string[] args) { Ref<object>(new string[,] { { System.String.Empty } }); } }"; string expected = @""; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [WorkItem(544364, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544364")] [Fact] public void MissingNestedArrayInitializerWithNullConst() { var text = @"class Program { static void Main(string[] args) { int?[ , ] ar1 = { null }; } }"; CreateCompilation(text).VerifyDiagnostics( // (5,27): error CS0846: A nested array initializer is expected // int?[ , ] ar1 = { null }; Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "null") ); } private static readonly string s_arraysOfRank1IlSource = @" .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Test1::.ctor .method public hidebysig newslot virtual instance float64[0...] Test1() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test1"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) ldc.i4.0 ldc.i4.1 newobj instance void float64[...]::.ctor(int32, int32) dup ldc.i4.0 ldc.r8 -100 call instance void float64[...]::Set(int32, float64) IL_000a: ret } // end of method Test::Test1 .method public hidebysig newslot virtual instance float64 Test2(float64[0...] x) cil managed { // Code size 11 (0xb) .maxstack 2 IL_0000: ldstr ""Test2"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) ldarg.1 ldc.i4.0 call instance float64 float64[...]::Get(int32) IL_000a: ret } // end of method Test::Test2 .method public hidebysig newslot virtual instance void Test3(float64[0...] x) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 2 IL_000a: ret } // end of method Test::Test3 .method public hidebysig static void M1<T>(!!T[0...] a) cil managed { // Code size 18 (0x12) .maxstack 8 IL_0000: nop IL_0001: ldtoken !!T IL_0006: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_000b: call void [mscorlib]System.Console::WriteLine(object) IL_0010: nop IL_0011: ret } // end of method M1 .method public hidebysig static void M2<T>(!!T[] a, !!T[0...] b) cil managed { // Code size 18 (0x12) .maxstack 8 IL_0000: nop IL_0001: ldtoken !!T IL_0006: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_000b: call void [mscorlib]System.Console::WriteLine(object) IL_0010: nop IL_0011: ret } // end of method M2 } // end of class Test "; [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_GetElement() { var source = @"class C { static void Main() { var t = new Test(); System.Console.WriteLine(t.Test1()[0]); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 -100"); verifier.VerifyIL("C.Main", @" { // Code size 22 (0x16) .maxstack 2 IL_0000: newobj ""Test..ctor()"" IL_0005: callvirt ""double[*] Test.Test1()"" IL_000a: ldc.i4.0 IL_000b: call ""double[*].Get"" IL_0010: call ""void System.Console.WriteLine(double)"" IL_0015: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_SetElement() { var source = @"class C { static void Main() { var t = new Test(); var a = t.Test1(); a[0] = 123; System.Console.WriteLine(t.Test2(a)); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 Test2 123"); verifier.VerifyIL("C.Main", @" { // Code size 40 (0x28) .maxstack 4 .locals init (double[*] V_0) //a IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: callvirt ""double[*] Test.Test1()"" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: ldc.i4.0 IL_000e: ldc.r8 123 IL_0017: call ""double[*].Set"" IL_001c: ldloc.0 IL_001d: callvirt ""double Test.Test2(double[*])"" IL_0022: call ""void System.Console.WriteLine(double)"" IL_0027: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_ElementAddress() { var source = @"class C { static void Main() { var t = new Test(); var a = t.Test1(); TestRef(ref a[0]); System.Console.WriteLine(t.Test2(a)); } static void TestRef(ref double val) { val = 123; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 Test2 123"); verifier.VerifyIL("C.Main", @" { // Code size 36 (0x24) .maxstack 3 .locals init (double[*] V_0) //a IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: callvirt ""double[*] Test.Test1()"" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: ldc.i4.0 IL_000e: call ""double[*].Address"" IL_0013: call ""void C.TestRef(ref double)"" IL_0018: ldloc.0 IL_0019: callvirt ""double Test.Test2(double[*])"" IL_001e: call ""void System.Console.WriteLine(double)"" IL_0023: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_Overriding01() { var source = @"class C : Test { public override double[] Test1() { return null; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (3,30): error CS0508: 'C.Test1()': return type must be 'double[*]' to match overridden member 'Test.Test1()' // public override double[] Test1() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "Test1").WithArguments("C.Test1()", "Test.Test1()", "double[*]").WithLocation(3, 30) ); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_Overriding02() { var source = @"class C : Test { public override double Test2(double[] x) { return x[0]; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (3,28): error CS0115: 'C.Test2(double[])': no suitable method found to override // public override double Test2(double[] x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Test2").WithArguments("C.Test2(double[])").WithLocation(3, 28) ); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_Conversions() { var source = @"class C { static void Main() { var t = new Test(); double[] a1 = t.Test1(); double[] a2 = (double[])t.Test1(); System.Collections.Generic.IList<double> a3 = t.Test1(); double [] a4 = null; t.Test2(a4); var a5 = (System.Collections.Generic.IList<double>)t.Test1(); System.Collections.Generic.IList<double> ilist = new double [] {}; var mdarray = t.Test1(); mdarray = ilist; mdarray = t.Test1(); mdarray = new [] { 3.0d }; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,23): error CS0029: Cannot implicitly convert type 'double[*]' to 'double[]' // double[] a1 = t.Test1(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "t.Test1()").WithArguments("double[*]", "double[]").WithLocation(6, 23), // (7,23): error CS0030: Cannot convert type 'double[*]' to 'double[]' // double[] a2 = (double[])t.Test1(); Diagnostic(ErrorCode.ERR_NoExplicitConv, "(double[])t.Test1()").WithArguments("double[*]", "double[]").WithLocation(7, 23), // (8,55): error CS0029: Cannot implicitly convert type 'double[*]' to 'System.Collections.Generic.IList<double>' // System.Collections.Generic.IList<double> a3 = t.Test1(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "t.Test1()").WithArguments("double[*]", "System.Collections.Generic.IList<double>").WithLocation(8, 55), // (10,17): error CS1503: Argument 1: cannot convert from 'double[]' to 'double[*]' // t.Test2(a4); Diagnostic(ErrorCode.ERR_BadArgType, "a4").WithArguments("1", "double[]", "double[*]").WithLocation(10, 17), // (11,18): error CS0030: Cannot convert type 'double[*]' to 'System.Collections.Generic.IList<double>' // var a5 = (System.Collections.Generic.IList<double>)t.Test1(); Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Collections.Generic.IList<double>)t.Test1()").WithArguments("double[*]", "System.Collections.Generic.IList<double>").WithLocation(11, 18), // (14,19): error CS0029: Cannot implicitly convert type 'System.Collections.Generic.IList<double>' to 'double[*]' // mdarray = ilist; Diagnostic(ErrorCode.ERR_NoImplicitConv, "ilist").WithArguments("System.Collections.Generic.IList<double>", "double[*]").WithLocation(14, 19), // (16,19): error CS0029: Cannot implicitly convert type 'double[]' to 'double[*]' // mdarray = new [] { 3.0d }; Diagnostic(ErrorCode.ERR_NoImplicitConv, "new [] { 3.0d }").WithArguments("double[]", "double[*]").WithLocation(16, 19) ); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_TypeArgumentInference01() { var source = @"class C { static void Main() { var t = new Test(); var md = t.Test1(); var sz = new double [] {}; M1(sz); M1(md); M2(sz, sz); M2(md, md); M2(sz, md); M2(md, sz); M3(sz); M3(md); Test.M1(sz); Test.M1(md); Test.M2(sz, sz); Test.M2(md, md); Test.M2(sz, md); Test.M2(md, sz); } static void M1<T>(T [] a){} static void M2<T>(T a, T b){} static void M3<T>(System.Collections.Generic.IList<T> a){} }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var m2 = compilation.GetTypeByMetadataName("Test").GetMember<MethodSymbol>("M2"); var szArray = (ArrayTypeSymbol)m2.Parameters.First().Type; Assert.Equal("T[]", szArray.ToTestDisplayString()); Assert.True(szArray.IsSZArray); Assert.Equal(1, szArray.Rank); Assert.True(szArray.Sizes.IsEmpty); Assert.True(szArray.LowerBounds.IsDefault); var mdArray = (ArrayTypeSymbol)m2.Parameters.Last().Type; Assert.Equal("T[*]", mdArray.ToTestDisplayString()); Assert.False(mdArray.IsSZArray); Assert.Equal(1, mdArray.Rank); Assert.True(mdArray.Sizes.IsEmpty); Assert.True(mdArray.LowerBounds.IsDefault); compilation.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'C.M1<T>(T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M1(md); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("C.M1<T>(T[])").WithLocation(10, 9), // (13,9): error CS0411: The type arguments for method 'C.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M2(sz, md); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("C.M2<T>(T, T)").WithLocation(13, 9), // (14,9): error CS0411: The type arguments for method 'C.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M2(md, sz); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("C.M2<T>(T, T)").WithLocation(14, 9), // (16,9): error CS0411: The type arguments for method 'C.M3<T>(IList<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(md); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("C.M3<T>(System.Collections.Generic.IList<T>)").WithLocation(16, 9), // (18,14): error CS0411: The type arguments for method 'Test.M1<T>(T[*])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test.M1(sz); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Test.M1<T>(T[*])").WithLocation(18, 14), // (20,21): error CS1503: Argument 2: cannot convert from 'double[]' to 'double[*]' // Test.M2(sz, sz); Diagnostic(ErrorCode.ERR_BadArgType, "sz").WithArguments("2", "double[]", "double[*]").WithLocation(20, 21), // (21,17): error CS1503: Argument 1: cannot convert from 'double[*]' to 'double[]' // Test.M2(md, md); Diagnostic(ErrorCode.ERR_BadArgType, "md").WithArguments("1", "double[*]", "double[]").WithLocation(21, 17), // (23,14): error CS0411: The type arguments for method 'Test.M2<T>(T[], T[*])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test.M2(md, sz); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Test.M2<T>(T[], T[*])").WithLocation(23, 14) ); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_TypeArgumentInference02() { var source = @"class C { static void Main() { var t = new Test(); var md = t.Test1(); var sz = new double [] {}; M2(md, md); Test.M1(md); Test.M2(sz, md); } static void M2<T>(T a, T b) { System.Console.WriteLine(typeof(T)); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @"Test1 System.Double[*] System.Double System.Double "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_ForEach() { var source = @"class C { static void Main() { var t = new Test(); foreach (var d in t.Test1()) { System.Console.WriteLine(d); } } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 -100"); verifier.VerifyIL("C.Main", @" { // Code size 50 (0x32) .maxstack 2 .locals init (double[*] V_0, int V_1, int V_2) IL_0000: newobj ""Test..ctor()"" IL_0005: callvirt ""double[*] Test.Test1()"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldc.i4.0 IL_000d: callvirt ""int System.Array.GetUpperBound(int)"" IL_0012: stloc.1 IL_0013: ldloc.0 IL_0014: ldc.i4.0 IL_0015: callvirt ""int System.Array.GetLowerBound(int)"" IL_001a: stloc.2 IL_001b: br.s IL_002d IL_001d: ldloc.0 IL_001e: ldloc.2 IL_001f: call ""double[*].Get"" IL_0024: call ""void System.Console.WriteLine(double)"" IL_0029: ldloc.2 IL_002a: ldc.i4.1 IL_002b: add IL_002c: stloc.2 IL_002d: ldloc.2 IL_002e: ldloc.1 IL_002f: ble.s IL_001d IL_0031: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_Length() { var source = @"class C { static void Main() { var t = new Test(); System.Console.WriteLine(t.Test1().Length); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 1"); verifier.VerifyIL("C.Main", @" { // Code size 21 (0x15) .maxstack 1 IL_0000: newobj ""Test..ctor()"" IL_0005: callvirt ""double[*] Test.Test1()"" IL_000a: callvirt ""int System.Array.Length.get"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_LongLength() { var source = @"class C { static void Main() { var t = new Test(); System.Console.WriteLine(t.Test1().LongLength); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 1"); verifier.VerifyIL("C.Main", @" { // Code size 21 (0x15) .maxstack 1 IL_0000: newobj ""Test..ctor()"" IL_0005: callvirt ""double[*] Test.Test1()"" IL_000a: callvirt ""long System.Array.LongLength.get"" IL_000f: call ""void System.Console.WriteLine(long)"" IL_0014: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_ParamArray() { var source = @"class C { static void Main() { var t = new Test(); double d = 1.2; t.Test3(d); t.Test3(new double [] {d}); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (7,17): error CS1503: Argument 1: cannot convert from 'double' to 'params double[*]' // t.Test3(d); Diagnostic(ErrorCode.ERR_BadArgType, "d").WithArguments("1", "double", "params double[*]").WithLocation(7, 17), // (8,17): error CS1503: Argument 1: cannot convert from 'double[]' to 'params double[*]' // t.Test3(new double [] {d}); Diagnostic(ErrorCode.ERR_BadArgType, "new double [] {d}").WithArguments("1", "double[]", "params double[*]").WithLocation(8, 17) ); } [WorkItem(4954, "https://github.com/dotnet/roslyn/issues/4954")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void SizesAndLowerBounds_01() { var ilSource = @" .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Test1::.ctor .method public hidebysig newslot virtual instance float64[,] Test1() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test1"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[...,] Test2() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test2"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[...,...] Test3() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test3"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,] Test4() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test4"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,...] Test5() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test5"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,5] Test6() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test6"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,2...] Test7() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test7"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,2...8] Test8() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test8"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,] Test9() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test9"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,...] Test10() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test10"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,5] Test11() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test11"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,2...] Test12() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test12"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,2...8] Test13() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test13"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...,] Test14() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test14"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...,...] Test15() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test15"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...,2...] Test16() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test16"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5] Test17() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test17"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } } // end of class Test "; var source = @"class C : Test { static void Main() { double[,] a; var t = new Test(); a = t.Test1(); a = t.Test2(); a = t.Test3(); a = t.Test4(); a = t.Test5(); a = t.Test6(); a = t.Test7(); a = t.Test8(); a = t.Test9(); a = t.Test10(); a = t.Test11(); a = t.Test12(); a = t.Test13(); a = t.Test14(); a = t.Test15(); a = t.Test16(); t = new C(); a = t.Test1(); a = t.Test2(); a = t.Test3(); a = t.Test4(); a = t.Test5(); a = t.Test6(); a = t.Test7(); a = t.Test8(); a = t.Test9(); a = t.Test10(); a = t.Test11(); a = t.Test12(); a = t.Test13(); a = t.Test14(); a = t.Test15(); a = t.Test16(); } public override double[,] Test1() { System.Console.WriteLine(""Overridden 1""); return null; } public override double[,] Test2() { System.Console.WriteLine(""Overridden 2""); return null; } public override double[,] Test3() { System.Console.WriteLine(""Overridden 3""); return null; } public override double[,] Test4() { System.Console.WriteLine(""Overridden 4""); return null; } public override double[,] Test5() { System.Console.WriteLine(""Overridden 5""); return null; } public override double[,] Test6() { System.Console.WriteLine(""Overridden 6""); return null; } public override double[,] Test7() { System.Console.WriteLine(""Overridden 7""); return null; } public override double[,] Test8() { System.Console.WriteLine(""Overridden 8""); return null; } public override double[,] Test9() { System.Console.WriteLine(""Overridden 9""); return null; } public override double[,] Test10() { System.Console.WriteLine(""Overridden 10""); return null; } public override double[,] Test11() { System.Console.WriteLine(""Overridden 11""); return null; } public override double[,] Test12() { System.Console.WriteLine(""Overridden 12""); return null; } public override double[,] Test13() { System.Console.WriteLine(""Overridden 13""); return null; } public override double[,] Test14() { System.Console.WriteLine(""Overridden 14""); return null; } public override double[,] Test15() { System.Console.WriteLine(""Overridden 15""); return null; } public override double[,] Test16() { System.Console.WriteLine(""Overridden 16""); return null; } } "; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource, options: TestOptions.ReleaseExe); var test = compilation.GetTypeByMetadataName("Test"); var array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test1").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.True(array.LowerBounds.IsEmpty); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test2").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.True(array.LowerBounds.IsEmpty); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test3").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.True(array.LowerBounds.IsEmpty); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test4").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 0 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test5").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 0 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test6").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5, 5 }, array.Sizes); Assert.True(array.LowerBounds.IsDefault); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test7").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 0, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test8").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5, 7 }, array.Sizes); Assert.Equal(new[] { 0, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test9").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 1 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test10").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 1 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test11").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5, 5 }, array.Sizes); Assert.Equal(new[] { 1, 0 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test12").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 1, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test13").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5, 7 }, array.Sizes); Assert.Equal(new[] { 1, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test14").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.Equal(new[] { 1 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test15").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.Equal(new[] { 1 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test16").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.Equal(new[] { 1, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test17").ReturnType; Assert.Equal("System.Double[*]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(1, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 1 }, array.LowerBounds); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 Test2 Test3 Test4 Test5 Test6 Test7 Test8 Test9 Test10 Test11 Test12 Test13 Test14 Test15 Test16 Overridden 1 Overridden 2 Overridden 3 Overridden 4 Overridden 5 Overridden 6 Overridden 7 Overridden 8 Overridden 9 Overridden 10 Overridden 11 Overridden 12 Overridden 13 Overridden 14 Overridden 15 Overridden 16 "); } [WorkItem(4954, "https://github.com/dotnet/roslyn/issues/4954")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void SizesAndLowerBounds_02() { var ilSource = @" .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Test1::.ctor .method public hidebysig newslot virtual instance void Test1(float64[,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test1"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test2(float64[...,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test2"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test3(float64[...,...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test3"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test4(float64[5,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test4"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test5(float64[5,...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test5"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test6(float64[5,5] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test6"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test7(float64[5,2...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test7"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test8(float64[5,2...8] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test8"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test9(float64[1...5,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test9"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test10(float64[1...5,...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test10"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test11(float64[1...5,5] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test11"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test12(float64[1...5,2...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test12"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test13(float64[1...5,2...8] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test13"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test14(float64[1...,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test14"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test15(float64[1...,...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test15"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test16(float64[1...,2...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test16"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } } // end of class Test "; var source = @"class C : Test { static void Main() { double[,] a = new double [,] {}; var t = new Test(); t.Test1(a); t.Test2(a); t.Test3(a); t.Test4(a); t.Test5(a); t.Test6(a); t.Test7(a); t.Test8(a); t.Test9(a); t.Test10(a); t.Test11(a); t.Test12(a); t.Test13(a); t.Test14(a); t.Test15(a); t.Test16(a); t = new C(); t.Test1(a); t.Test2(a); t.Test3(a); t.Test4(a); t.Test5(a); t.Test6(a); t.Test7(a); t.Test8(a); t.Test9(a); t.Test10(a); t.Test11(a); t.Test12(a); t.Test13(a); t.Test14(a); t.Test15(a); t.Test16(a); } public override void Test1(double[,] x) { System.Console.WriteLine(""Overridden 1""); } public override void Test2(double[,] x) { System.Console.WriteLine(""Overridden 2""); } public override void Test3(double[,] x) { System.Console.WriteLine(""Overridden 3""); } public override void Test4(double[,] x) { System.Console.WriteLine(""Overridden 4""); } public override void Test5(double[,] x) { System.Console.WriteLine(""Overridden 5""); } public override void Test6(double[,] x) { System.Console.WriteLine(""Overridden 6""); } public override void Test7(double[,] x) { System.Console.WriteLine(""Overridden 7""); } public override void Test8(double[,] x) { System.Console.WriteLine(""Overridden 8""); } public override void Test9(double[,] x) { System.Console.WriteLine(""Overridden 9""); } public override void Test10(double[,] x) { System.Console.WriteLine(""Overridden 10""); } public override void Test11(double[,] x) { System.Console.WriteLine(""Overridden 11""); } public override void Test12(double[,] x) { System.Console.WriteLine(""Overridden 12""); } public override void Test13(double[,] x) { System.Console.WriteLine(""Overridden 13""); } public override void Test14(double[,] x) { System.Console.WriteLine(""Overridden 14""); } public override void Test15(double[,] x) { System.Console.WriteLine(""Overridden 15""); } public override void Test16(double[,] x) { System.Console.WriteLine(""Overridden 16""); } } "; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 Test2 Test3 Test4 Test5 Test6 Test7 Test8 Test9 Test10 Test11 Test12 Test13 Test14 Test15 Test16 Overridden 1 Overridden 2 Overridden 3 Overridden 4 Overridden 5 Overridden 6 Overridden 7 Overridden 8 Overridden 9 Overridden 10 Overridden 11 Overridden 12 Overridden 13 Overridden 14 Overridden 15 Overridden 16 "); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] [WorkItem(4958, "https://github.com/dotnet/roslyn/issues/4958")] public void ArraysOfRank1_InAttributes() { var ilSource = @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { .method public hidebysig instance void Test1() cil managed { .custom instance void TestAttribute::.ctor(class [mscorlib] System.Type) = {type(class 'System.Int32[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')} // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Program::Test1 .method public hidebysig instance void Test2() cil managed { .custom instance void TestAttribute::.ctor(class [mscorlib] System.Type) = {type(class 'System.Int32[*], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')} // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Program::Test2 .method public hidebysig instance void Test3() cil managed { .custom instance void TestAttribute::.ctor(class [mscorlib] System.Type) = {type(class 'System.Int32[*,*], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')} // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Program::Test3 .method public hidebysig instance void Test4() cil managed { .custom instance void TestAttribute::.ctor(class [mscorlib] System.Type) = {type(class 'System.Int32[,*], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')} // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Program::Test4 } // end of class Program .class public auto ansi beforefieldinit TestAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class [mscorlib]System.Type val) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: nop IL_0008: ret } // end of method TestAttribute::.ctor } // end of class TestAttribute "; var source = @" using System; using System.Linq; class C { static void Main() { System.Console.WriteLine(GetTypeFromAttribute(""Test1"")); System.Console.WriteLine(GetTypeFromAttribute(""Test2"")); try { GetTypeFromAttribute(""Test3""); } catch { System.Console.WriteLine(""Throws""); } try { GetTypeFromAttribute(""Test4""); } catch { System.Console.WriteLine(""Throws""); } } private static Type GetTypeFromAttribute(string target) { return (System.Type)typeof(Program).GetMember(target)[0].GetCustomAttributesData().ElementAt(0).ConstructorArguments[0].Value; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource, references: new[] { SystemCoreRef }, options: TestOptions.ReleaseExe); var p = compilation.GetTypeByMetadataName("Program"); var a1 = (IArrayTypeSymbol)p.GetMember<MethodSymbol>("Test1").GetAttributes().Single().ConstructorArguments.Single().Value; Assert.Equal("System.Int32[]", a1.ToTestDisplayString()); Assert.Equal(1, a1.Rank); Assert.True(a1.IsSZArray); var a2 = (IArrayTypeSymbol)p.GetMember<MethodSymbol>("Test2").GetAttributes().Single().ConstructorArguments.Single().Value; Assert.Equal("System.Int32[*]", a2.ToTestDisplayString()); Assert.Equal(1, a2.Rank); Assert.False(a2.IsSZArray); Assert.True(((ITypeSymbol)p.GetMember<MethodSymbol>("Test3").GetAttributes().Single().ConstructorArguments.Single().Value).IsErrorType()); Assert.True(((ITypeSymbol)p.GetMember<MethodSymbol>("Test4").GetAttributes().Single().ConstructorArguments.Single().Value).IsErrorType()); CompileAndVerify(compilation, expectedOutput: @"System.Int32[] System.Int32[*] Throws Throws"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class MultiDimensionalArrayTests : SemanticModelTestBase { [Fact] public void TestMultiDimensionalArray() { // Verify that operations on multidimensional arrays work and cause side effects only once. string source = @" using System; class P { static int M(ref int x) { int y = x; x = 456; return y; } static int counter; static int[,] A(int[,] a) { Console.Write('A'); Console.Write(counter); ++counter; return a; } static int B(int b) { Console.Write('B'); Console.Write(counter); ++counter; return b; } static int C(int c) { Console.Write('C'); Console.Write(counter); ++counter; return c; } static void Main() { int x = 4; int y = 5; int[,] a = new int[x,y]; V((A(a)[B(3),C(4)] = 123) == 123); V(M(ref A(a)[B(1),C(2)]) == 0); V(A(a)[B(1),C(2)] == 456); V(A(a)[B(3),C(4)] == 123); V(A(a)[B(0),C(0)] == 0); V(A(a)[B(0),C(0)]++ == 0); V(A(a)[B(0),C(0)] == 1); V(++A(a)[B(0),C(0)] == 2); V(A(a)[B(0),C(0)] == 2); V((A(a)[B(1),C(1)] += 3) == 3); V((A(a)[B(1),C(1)] -= 2) == 1); } static void V(bool b) { Console.WriteLine(b ? 't' : 'f'); } }"; string expected = @"A0B1C2t A3B4C5t A6B7C8t A9B10C11t A12B13C14t A15B16C17t A18B19C20t A21B22C23t A24B25C26t A27B28C29t A30B31C32t"; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [Fact] public void TestMultiDimensionalArrayInitializers() { // Verify that operations on multidimensional arrays work and cause side effects only once. string source = @" using System; class P { static void Main() { byte[,,] b = new byte[,,]{ { { 1, 2, 3 }, { 4, 5, 6 } }, { { 7, 8, 9 }, { 10, 11, 12 } } }; int x = 999; int y = 888; int[,,] i = new int[,,]{ { { 1, 2, 3 }, { 4, 5, y } }, { { x, 8, 9 }, { 10, 11, 12 } } }; double[,,] d = new double[,,]{ { { y, y, y }, { x, x, x } }, { { x, y, x }, { 10, 11, 12 } } }; for (int j = 0 ; j < 2; ++j) for (int k = 0; k < 2; ++k) for (int l = 0; l < 3; ++l) Console.Write(b[j,k,l]); Console.WriteLine(); for (int j = 0 ; j < 2; ++j) for (int k = 0; k < 2; ++k) for (int l = 0; l < 3; ++l) Console.Write(i[j,k,l]); Console.WriteLine(); for (int j = 0 ; j < 2; ++j) for (int k = 0; k < 2; ++k) for (int l = 0; l < 3; ++l) Console.Write(d[j,k,l]); } }"; string expected = @"123456789101112 1234588899989101112 888888888999999999999888999101112"; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [Fact] public void TestMultiDimensionalArrayForEach() { string source = @" public class C { public static void Main() { int y = 50; foreach (var x in new int[2, 3] {{10, 20, 30}, {40, y, 60}}) { System.Console.Write(x); } } }"; string expected = @"102030405060"; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [WorkItem(544081, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544081")] [Fact()] public void MultiDimArrayGenericTypeWiderThanArrayType() { string source = @" class Program { public static void Ref<T>(T[,] array) { array[0, 0].GetType(); } static void Main(string[] args) { Ref<object>(new string[,] { { System.String.Empty } }); } }"; string expected = @""; var verifier = CompileAndVerify(source: source, expectedOutput: expected); } [WorkItem(544364, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544364")] [Fact] public void MissingNestedArrayInitializerWithNullConst() { var text = @"class Program { static void Main(string[] args) { int?[ , ] ar1 = { null }; } }"; CreateCompilation(text).VerifyDiagnostics( // (5,27): error CS0846: A nested array initializer is expected // int?[ , ] ar1 = { null }; Diagnostic(ErrorCode.ERR_ArrayInitializerExpected, "null") ); } private static readonly string s_arraysOfRank1IlSource = @" .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Test1::.ctor .method public hidebysig newslot virtual instance float64[0...] Test1() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test1"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) ldc.i4.0 ldc.i4.1 newobj instance void float64[...]::.ctor(int32, int32) dup ldc.i4.0 ldc.r8 -100 call instance void float64[...]::Set(int32, float64) IL_000a: ret } // end of method Test::Test1 .method public hidebysig newslot virtual instance float64 Test2(float64[0...] x) cil managed { // Code size 11 (0xb) .maxstack 2 IL_0000: ldstr ""Test2"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) ldarg.1 ldc.i4.0 call instance float64 float64[...]::Get(int32) IL_000a: ret } // end of method Test::Test2 .method public hidebysig newslot virtual instance void Test3(float64[0...] x) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .maxstack 2 IL_000a: ret } // end of method Test::Test3 .method public hidebysig static void M1<T>(!!T[0...] a) cil managed { // Code size 18 (0x12) .maxstack 8 IL_0000: nop IL_0001: ldtoken !!T IL_0006: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_000b: call void [mscorlib]System.Console::WriteLine(object) IL_0010: nop IL_0011: ret } // end of method M1 .method public hidebysig static void M2<T>(!!T[] a, !!T[0...] b) cil managed { // Code size 18 (0x12) .maxstack 8 IL_0000: nop IL_0001: ldtoken !!T IL_0006: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_000b: call void [mscorlib]System.Console::WriteLine(object) IL_0010: nop IL_0011: ret } // end of method M2 } // end of class Test "; [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_GetElement() { var source = @"class C { static void Main() { var t = new Test(); System.Console.WriteLine(t.Test1()[0]); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 -100"); verifier.VerifyIL("C.Main", @" { // Code size 22 (0x16) .maxstack 2 IL_0000: newobj ""Test..ctor()"" IL_0005: callvirt ""double[*] Test.Test1()"" IL_000a: ldc.i4.0 IL_000b: call ""double[*].Get"" IL_0010: call ""void System.Console.WriteLine(double)"" IL_0015: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_SetElement() { var source = @"class C { static void Main() { var t = new Test(); var a = t.Test1(); a[0] = 123; System.Console.WriteLine(t.Test2(a)); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 Test2 123"); verifier.VerifyIL("C.Main", @" { // Code size 40 (0x28) .maxstack 4 .locals init (double[*] V_0) //a IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: callvirt ""double[*] Test.Test1()"" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: ldc.i4.0 IL_000e: ldc.r8 123 IL_0017: call ""double[*].Set"" IL_001c: ldloc.0 IL_001d: callvirt ""double Test.Test2(double[*])"" IL_0022: call ""void System.Console.WriteLine(double)"" IL_0027: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_ElementAddress() { var source = @"class C { static void Main() { var t = new Test(); var a = t.Test1(); TestRef(ref a[0]); System.Console.WriteLine(t.Test2(a)); } static void TestRef(ref double val) { val = 123; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 Test2 123"); verifier.VerifyIL("C.Main", @" { // Code size 36 (0x24) .maxstack 3 .locals init (double[*] V_0) //a IL_0000: newobj ""Test..ctor()"" IL_0005: dup IL_0006: callvirt ""double[*] Test.Test1()"" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: ldc.i4.0 IL_000e: call ""double[*].Address"" IL_0013: call ""void C.TestRef(ref double)"" IL_0018: ldloc.0 IL_0019: callvirt ""double Test.Test2(double[*])"" IL_001e: call ""void System.Console.WriteLine(double)"" IL_0023: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_Overriding01() { var source = @"class C : Test { public override double[] Test1() { return null; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (3,30): error CS0508: 'C.Test1()': return type must be 'double[*]' to match overridden member 'Test.Test1()' // public override double[] Test1() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "Test1").WithArguments("C.Test1()", "Test.Test1()", "double[*]").WithLocation(3, 30) ); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_Overriding02() { var source = @"class C : Test { public override double Test2(double[] x) { return x[0]; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (3,28): error CS0115: 'C.Test2(double[])': no suitable method found to override // public override double Test2(double[] x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Test2").WithArguments("C.Test2(double[])").WithLocation(3, 28) ); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_Conversions() { var source = @"class C { static void Main() { var t = new Test(); double[] a1 = t.Test1(); double[] a2 = (double[])t.Test1(); System.Collections.Generic.IList<double> a3 = t.Test1(); double [] a4 = null; t.Test2(a4); var a5 = (System.Collections.Generic.IList<double>)t.Test1(); System.Collections.Generic.IList<double> ilist = new double [] {}; var mdarray = t.Test1(); mdarray = ilist; mdarray = t.Test1(); mdarray = new [] { 3.0d }; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics( // (6,23): error CS0029: Cannot implicitly convert type 'double[*]' to 'double[]' // double[] a1 = t.Test1(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "t.Test1()").WithArguments("double[*]", "double[]").WithLocation(6, 23), // (7,23): error CS0030: Cannot convert type 'double[*]' to 'double[]' // double[] a2 = (double[])t.Test1(); Diagnostic(ErrorCode.ERR_NoExplicitConv, "(double[])t.Test1()").WithArguments("double[*]", "double[]").WithLocation(7, 23), // (8,55): error CS0029: Cannot implicitly convert type 'double[*]' to 'System.Collections.Generic.IList<double>' // System.Collections.Generic.IList<double> a3 = t.Test1(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "t.Test1()").WithArguments("double[*]", "System.Collections.Generic.IList<double>").WithLocation(8, 55), // (10,17): error CS1503: Argument 1: cannot convert from 'double[]' to 'double[*]' // t.Test2(a4); Diagnostic(ErrorCode.ERR_BadArgType, "a4").WithArguments("1", "double[]", "double[*]").WithLocation(10, 17), // (11,18): error CS0030: Cannot convert type 'double[*]' to 'System.Collections.Generic.IList<double>' // var a5 = (System.Collections.Generic.IList<double>)t.Test1(); Diagnostic(ErrorCode.ERR_NoExplicitConv, "(System.Collections.Generic.IList<double>)t.Test1()").WithArguments("double[*]", "System.Collections.Generic.IList<double>").WithLocation(11, 18), // (14,19): error CS0029: Cannot implicitly convert type 'System.Collections.Generic.IList<double>' to 'double[*]' // mdarray = ilist; Diagnostic(ErrorCode.ERR_NoImplicitConv, "ilist").WithArguments("System.Collections.Generic.IList<double>", "double[*]").WithLocation(14, 19), // (16,19): error CS0029: Cannot implicitly convert type 'double[]' to 'double[*]' // mdarray = new [] { 3.0d }; Diagnostic(ErrorCode.ERR_NoImplicitConv, "new [] { 3.0d }").WithArguments("double[]", "double[*]").WithLocation(16, 19) ); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_TypeArgumentInference01() { var source = @"class C { static void Main() { var t = new Test(); var md = t.Test1(); var sz = new double [] {}; M1(sz); M1(md); M2(sz, sz); M2(md, md); M2(sz, md); M2(md, sz); M3(sz); M3(md); Test.M1(sz); Test.M1(md); Test.M2(sz, sz); Test.M2(md, md); Test.M2(sz, md); Test.M2(md, sz); } static void M1<T>(T [] a){} static void M2<T>(T a, T b){} static void M3<T>(System.Collections.Generic.IList<T> a){} }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var m2 = compilation.GetTypeByMetadataName("Test").GetMember<MethodSymbol>("M2"); var szArray = (ArrayTypeSymbol)m2.Parameters.First().Type; Assert.Equal("T[]", szArray.ToTestDisplayString()); Assert.True(szArray.IsSZArray); Assert.Equal(1, szArray.Rank); Assert.True(szArray.Sizes.IsEmpty); Assert.True(szArray.LowerBounds.IsDefault); var mdArray = (ArrayTypeSymbol)m2.Parameters.Last().Type; Assert.Equal("T[*]", mdArray.ToTestDisplayString()); Assert.False(mdArray.IsSZArray); Assert.Equal(1, mdArray.Rank); Assert.True(mdArray.Sizes.IsEmpty); Assert.True(mdArray.LowerBounds.IsDefault); compilation.VerifyDiagnostics( // (10,9): error CS0411: The type arguments for method 'C.M1<T>(T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M1(md); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("C.M1<T>(T[])").WithLocation(10, 9), // (13,9): error CS0411: The type arguments for method 'C.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M2(sz, md); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("C.M2<T>(T, T)").WithLocation(13, 9), // (14,9): error CS0411: The type arguments for method 'C.M2<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M2(md, sz); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("C.M2<T>(T, T)").WithLocation(14, 9), // (16,9): error CS0411: The type arguments for method 'C.M3<T>(IList<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(md); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("C.M3<T>(System.Collections.Generic.IList<T>)").WithLocation(16, 9), // (18,14): error CS0411: The type arguments for method 'Test.M1<T>(T[*])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test.M1(sz); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Test.M1<T>(T[*])").WithLocation(18, 14), // (20,21): error CS1503: Argument 2: cannot convert from 'double[]' to 'double[*]' // Test.M2(sz, sz); Diagnostic(ErrorCode.ERR_BadArgType, "sz").WithArguments("2", "double[]", "double[*]").WithLocation(20, 21), // (21,17): error CS1503: Argument 1: cannot convert from 'double[*]' to 'double[]' // Test.M2(md, md); Diagnostic(ErrorCode.ERR_BadArgType, "md").WithArguments("1", "double[*]", "double[]").WithLocation(21, 17), // (23,14): error CS0411: The type arguments for method 'Test.M2<T>(T[], T[*])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Test.M2(md, sz); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M2").WithArguments("Test.M2<T>(T[], T[*])").WithLocation(23, 14) ); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_TypeArgumentInference02() { var source = @"class C { static void Main() { var t = new Test(); var md = t.Test1(); var sz = new double [] {}; M2(md, md); Test.M1(md); Test.M2(sz, md); } static void M2<T>(T a, T b) { System.Console.WriteLine(typeof(T)); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @"Test1 System.Double[*] System.Double System.Double "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_ForEach() { var source = @"class C { static void Main() { var t = new Test(); foreach (var d in t.Test1()) { System.Console.WriteLine(d); } } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 -100"); verifier.VerifyIL("C.Main", @" { // Code size 50 (0x32) .maxstack 2 .locals init (double[*] V_0, int V_1, int V_2) IL_0000: newobj ""Test..ctor()"" IL_0005: callvirt ""double[*] Test.Test1()"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldc.i4.0 IL_000d: callvirt ""int System.Array.GetUpperBound(int)"" IL_0012: stloc.1 IL_0013: ldloc.0 IL_0014: ldc.i4.0 IL_0015: callvirt ""int System.Array.GetLowerBound(int)"" IL_001a: stloc.2 IL_001b: br.s IL_002d IL_001d: ldloc.0 IL_001e: ldloc.2 IL_001f: call ""double[*].Get"" IL_0024: call ""void System.Console.WriteLine(double)"" IL_0029: ldloc.2 IL_002a: ldc.i4.1 IL_002b: add IL_002c: stloc.2 IL_002d: ldloc.2 IL_002e: ldloc.1 IL_002f: ble.s IL_001d IL_0031: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_Length() { var source = @"class C { static void Main() { var t = new Test(); System.Console.WriteLine(t.Test1().Length); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 1"); verifier.VerifyIL("C.Main", @" { // Code size 21 (0x15) .maxstack 1 IL_0000: newobj ""Test..ctor()"" IL_0005: callvirt ""double[*] Test.Test1()"" IL_000a: callvirt ""int System.Array.Length.get"" IL_000f: call ""void System.Console.WriteLine(int)"" IL_0014: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void ArraysOfRank1_LongLength() { var source = @"class C { static void Main() { var t = new Test(); System.Console.WriteLine(t.Test1().LongLength); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 1"); verifier.VerifyIL("C.Main", @" { // Code size 21 (0x15) .maxstack 1 IL_0000: newobj ""Test..ctor()"" IL_0005: callvirt ""double[*] Test.Test1()"" IL_000a: callvirt ""long System.Array.LongLength.get"" IL_000f: call ""void System.Console.WriteLine(long)"" IL_0014: ret } "); } [WorkItem(126766, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/126766"), WorkItem(4924, "https://github.com/dotnet/roslyn/issues/4924")] [Fact] public void ArraysOfRank1_ParamArray() { var source = @"class C { static void Main() { var t = new Test(); double d = 1.2; t.Test3(d); t.Test3(new double [] {d}); } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, s_arraysOfRank1IlSource, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (7,17): error CS1503: Argument 1: cannot convert from 'double' to 'params double[*]' // t.Test3(d); Diagnostic(ErrorCode.ERR_BadArgType, "d").WithArguments("1", "double", "params double[*]").WithLocation(7, 17), // (8,17): error CS1503: Argument 1: cannot convert from 'double[]' to 'params double[*]' // t.Test3(new double [] {d}); Diagnostic(ErrorCode.ERR_BadArgType, "new double [] {d}").WithArguments("1", "double[]", "params double[*]").WithLocation(8, 17) ); } [WorkItem(4954, "https://github.com/dotnet/roslyn/issues/4954")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void SizesAndLowerBounds_01() { var ilSource = @" .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Test1::.ctor .method public hidebysig newslot virtual instance float64[,] Test1() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test1"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[...,] Test2() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test2"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[...,...] Test3() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test3"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,] Test4() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test4"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,...] Test5() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test5"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,5] Test6() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test6"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,2...] Test7() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test7"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[5,2...8] Test8() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test8"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,] Test9() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test9"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,...] Test10() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test10"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,5] Test11() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test11"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,2...] Test12() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test12"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5,2...8] Test13() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test13"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...,] Test14() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test14"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...,...] Test15() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test15"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...,2...] Test16() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test16"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } .method public hidebysig newslot virtual instance float64[1...5] Test17() cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test17"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_0007: ldnull IL_000a: ret } } // end of class Test "; var source = @"class C : Test { static void Main() { double[,] a; var t = new Test(); a = t.Test1(); a = t.Test2(); a = t.Test3(); a = t.Test4(); a = t.Test5(); a = t.Test6(); a = t.Test7(); a = t.Test8(); a = t.Test9(); a = t.Test10(); a = t.Test11(); a = t.Test12(); a = t.Test13(); a = t.Test14(); a = t.Test15(); a = t.Test16(); t = new C(); a = t.Test1(); a = t.Test2(); a = t.Test3(); a = t.Test4(); a = t.Test5(); a = t.Test6(); a = t.Test7(); a = t.Test8(); a = t.Test9(); a = t.Test10(); a = t.Test11(); a = t.Test12(); a = t.Test13(); a = t.Test14(); a = t.Test15(); a = t.Test16(); } public override double[,] Test1() { System.Console.WriteLine(""Overridden 1""); return null; } public override double[,] Test2() { System.Console.WriteLine(""Overridden 2""); return null; } public override double[,] Test3() { System.Console.WriteLine(""Overridden 3""); return null; } public override double[,] Test4() { System.Console.WriteLine(""Overridden 4""); return null; } public override double[,] Test5() { System.Console.WriteLine(""Overridden 5""); return null; } public override double[,] Test6() { System.Console.WriteLine(""Overridden 6""); return null; } public override double[,] Test7() { System.Console.WriteLine(""Overridden 7""); return null; } public override double[,] Test8() { System.Console.WriteLine(""Overridden 8""); return null; } public override double[,] Test9() { System.Console.WriteLine(""Overridden 9""); return null; } public override double[,] Test10() { System.Console.WriteLine(""Overridden 10""); return null; } public override double[,] Test11() { System.Console.WriteLine(""Overridden 11""); return null; } public override double[,] Test12() { System.Console.WriteLine(""Overridden 12""); return null; } public override double[,] Test13() { System.Console.WriteLine(""Overridden 13""); return null; } public override double[,] Test14() { System.Console.WriteLine(""Overridden 14""); return null; } public override double[,] Test15() { System.Console.WriteLine(""Overridden 15""); return null; } public override double[,] Test16() { System.Console.WriteLine(""Overridden 16""); return null; } } "; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource, options: TestOptions.ReleaseExe); var test = compilation.GetTypeByMetadataName("Test"); var array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test1").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.True(array.LowerBounds.IsEmpty); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test2").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.True(array.LowerBounds.IsEmpty); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test3").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.True(array.LowerBounds.IsEmpty); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test4").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 0 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test5").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 0 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test6").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5, 5 }, array.Sizes); Assert.True(array.LowerBounds.IsDefault); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test7").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 0, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test8").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5, 7 }, array.Sizes); Assert.Equal(new[] { 0, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test9").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 1 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test10").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 1 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test11").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5, 5 }, array.Sizes); Assert.Equal(new[] { 1, 0 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test12").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 1, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test13").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.Equal(new[] { 5, 7 }, array.Sizes); Assert.Equal(new[] { 1, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test14").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.Equal(new[] { 1 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test15").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.Equal(new[] { 1 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test16").ReturnType; Assert.Equal("System.Double[,]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(2, array.Rank); Assert.True(array.Sizes.IsEmpty); Assert.Equal(new[] { 1, 2 }, array.LowerBounds); array = (ArrayTypeSymbol)test.GetMember<MethodSymbol>("Test17").ReturnType; Assert.Equal("System.Double[*]", array.ToTestDisplayString()); Assert.False(array.IsSZArray); Assert.Equal(1, array.Rank); Assert.Equal(new[] { 5 }, array.Sizes); Assert.Equal(new[] { 1 }, array.LowerBounds); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 Test2 Test3 Test4 Test5 Test6 Test7 Test8 Test9 Test10 Test11 Test12 Test13 Test14 Test15 Test16 Overridden 1 Overridden 2 Overridden 3 Overridden 4 Overridden 5 Overridden 6 Overridden 7 Overridden 8 Overridden 9 Overridden 10 Overridden 11 Overridden 12 Overridden 13 Overridden 14 Overridden 15 Overridden 16 "); } [WorkItem(4954, "https://github.com/dotnet/roslyn/issues/4954")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void SizesAndLowerBounds_02() { var ilSource = @" .class public auto ansi beforefieldinit Test extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Test1::.ctor .method public hidebysig newslot virtual instance void Test1(float64[,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test1"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test2(float64[...,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test2"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test3(float64[...,...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test3"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test4(float64[5,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test4"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test5(float64[5,...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test5"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test6(float64[5,5] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test6"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test7(float64[5,2...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test7"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test8(float64[5,2...8] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test8"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test9(float64[1...5,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test9"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test10(float64[1...5,...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test10"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test11(float64[1...5,5] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test11"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test12(float64[1...5,2...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test12"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test13(float64[1...5,2...8] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test13"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test14(float64[1...,] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test14"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test15(float64[1...,...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test15"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig newslot virtual instance void Test16(float64[1...,2...] x) cil managed { // Code size 11 (0xb) .maxstack 4 IL_0000: ldstr ""Test16"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } } // end of class Test "; var source = @"class C : Test { static void Main() { double[,] a = new double [,] {}; var t = new Test(); t.Test1(a); t.Test2(a); t.Test3(a); t.Test4(a); t.Test5(a); t.Test6(a); t.Test7(a); t.Test8(a); t.Test9(a); t.Test10(a); t.Test11(a); t.Test12(a); t.Test13(a); t.Test14(a); t.Test15(a); t.Test16(a); t = new C(); t.Test1(a); t.Test2(a); t.Test3(a); t.Test4(a); t.Test5(a); t.Test6(a); t.Test7(a); t.Test8(a); t.Test9(a); t.Test10(a); t.Test11(a); t.Test12(a); t.Test13(a); t.Test14(a); t.Test15(a); t.Test16(a); } public override void Test1(double[,] x) { System.Console.WriteLine(""Overridden 1""); } public override void Test2(double[,] x) { System.Console.WriteLine(""Overridden 2""); } public override void Test3(double[,] x) { System.Console.WriteLine(""Overridden 3""); } public override void Test4(double[,] x) { System.Console.WriteLine(""Overridden 4""); } public override void Test5(double[,] x) { System.Console.WriteLine(""Overridden 5""); } public override void Test6(double[,] x) { System.Console.WriteLine(""Overridden 6""); } public override void Test7(double[,] x) { System.Console.WriteLine(""Overridden 7""); } public override void Test8(double[,] x) { System.Console.WriteLine(""Overridden 8""); } public override void Test9(double[,] x) { System.Console.WriteLine(""Overridden 9""); } public override void Test10(double[,] x) { System.Console.WriteLine(""Overridden 10""); } public override void Test11(double[,] x) { System.Console.WriteLine(""Overridden 11""); } public override void Test12(double[,] x) { System.Console.WriteLine(""Overridden 12""); } public override void Test13(double[,] x) { System.Console.WriteLine(""Overridden 13""); } public override void Test14(double[,] x) { System.Console.WriteLine(""Overridden 14""); } public override void Test15(double[,] x) { System.Console.WriteLine(""Overridden 15""); } public override void Test16(double[,] x) { System.Console.WriteLine(""Overridden 16""); } } "; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(compilation, expectedOutput: @"Test1 Test2 Test3 Test4 Test5 Test6 Test7 Test8 Test9 Test10 Test11 Test12 Test13 Test14 Test15 Test16 Overridden 1 Overridden 2 Overridden 3 Overridden 4 Overridden 5 Overridden 6 Overridden 7 Overridden 8 Overridden 9 Overridden 10 Overridden 11 Overridden 12 Overridden 13 Overridden 14 Overridden 15 Overridden 16 "); } [ClrOnlyFact(ClrOnlyReason.Ilasm)] [WorkItem(4958, "https://github.com/dotnet/roslyn/issues/4958")] public void ArraysOfRank1_InAttributes() { var ilSource = @" .class public auto ansi beforefieldinit Program extends [mscorlib]System.Object { .method public hidebysig instance void Test1() cil managed { .custom instance void TestAttribute::.ctor(class [mscorlib] System.Type) = {type(class 'System.Int32[], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')} // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Program::Test1 .method public hidebysig instance void Test2() cil managed { .custom instance void TestAttribute::.ctor(class [mscorlib] System.Type) = {type(class 'System.Int32[*], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')} // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Program::Test2 .method public hidebysig instance void Test3() cil managed { .custom instance void TestAttribute::.ctor(class [mscorlib] System.Type) = {type(class 'System.Int32[*,*], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')} // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Program::Test3 .method public hidebysig instance void Test4() cil managed { .custom instance void TestAttribute::.ctor(class [mscorlib] System.Type) = {type(class 'System.Int32[,*], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089')} // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Program::Test4 } // end of class Program .class public auto ansi beforefieldinit TestAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class [mscorlib]System.Type val) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: nop IL_0008: ret } // end of method TestAttribute::.ctor } // end of class TestAttribute "; var source = @" using System; using System.Linq; class C { static void Main() { System.Console.WriteLine(GetTypeFromAttribute(""Test1"")); System.Console.WriteLine(GetTypeFromAttribute(""Test2"")); try { GetTypeFromAttribute(""Test3""); } catch { System.Console.WriteLine(""Throws""); } try { GetTypeFromAttribute(""Test4""); } catch { System.Console.WriteLine(""Throws""); } } private static Type GetTypeFromAttribute(string target) { return (System.Type)typeof(Program).GetMember(target)[0].GetCustomAttributesData().ElementAt(0).ConstructorArguments[0].Value; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource, references: new[] { SystemCoreRef }, options: TestOptions.ReleaseExe); var p = compilation.GetTypeByMetadataName("Program"); var a1 = (IArrayTypeSymbol)p.GetMember<MethodSymbol>("Test1").GetAttributes().Single().ConstructorArguments.Single().Value; Assert.Equal("System.Int32[]", a1.ToTestDisplayString()); Assert.Equal(1, a1.Rank); Assert.True(a1.IsSZArray); var a2 = (IArrayTypeSymbol)p.GetMember<MethodSymbol>("Test2").GetAttributes().Single().ConstructorArguments.Single().Value; Assert.Equal("System.Int32[*]", a2.ToTestDisplayString()); Assert.Equal(1, a2.Rank); Assert.False(a2.IsSZArray); Assert.True(((ITypeSymbol)p.GetMember<MethodSymbol>("Test3").GetAttributes().Single().ConstructorArguments.Single().Value).IsErrorType()); Assert.True(((ITypeSymbol)p.GetMember<MethodSymbol>("Test4").GetAttributes().Single().ConstructorArguments.Single().Value).IsErrorType()); CompileAndVerify(compilation, expectedOutput: @"System.Int32[] System.Int32[*] Throws Throws"); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/VisualStudio/CSharp/Impl/ProjectSystemShim/Interop/ICSharpVenusProjectSite.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop { /// <summary> /// Implemented to support project-to-project references. Despite its name, it's used for things other than Venus. /// </summary> [ComImport] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [Guid("97604d5d-7935-47fd-91c6-2747a5523855")] internal interface ICSharpVenusProjectSite { /// <summary> /// This function should not be used by any new code; it is now superseded by AddReferenceToCodeDirectoryEx. The /// function has not been removed due to the hard-dependency on this particular signature in Venus' templates. /// </summary> [Obsolete] void AddReferenceToCodeDirectory([MarshalAs(UnmanagedType.LPWStr)] string assemblyFileName, ICSharpProjectRoot project); /// <summary> /// Called by the venus project system to tell the project site to remove a live reference to an existing C# /// code directory. /// </summary> void RemoveReferenceToCodeDirectory([MarshalAs(UnmanagedType.LPWStr)] string assemblyFileName, ICSharpProjectRoot project); /// <summary> NOTE: This is not called by any project system in Dev11 according /// to http://bang/. Remove? /// /// [Optional] Called by the Venus Project system when a file of the Project /// site has been updated outside the editor. This is a workaround to allow /// the Venus project system implement a FileSystemWatcher for C#, since /// the C# language service doesn't support this yet. /// Not calling this when a file is updated on disk means code sense /// will not be up to date wrt to the changes on disk. /// </summary> void OnDiskFileUpdated([MarshalAs(UnmanagedType.LPWStr)] string filename, ref System.Runtime.InteropServices.ComTypes.FILETIME pFT); /// <summary>Called when aliases for an import are changed</summary> /// <param name="project">the project whose aliases we are changing</param> /// <param name="previousAliasesCount">number of elements in the previousAliases array</param> /// <param name="currentAliasesCount">number of elements in the currentAliases array</param> /// <param name="currentAliases">the previous aliases for this import</param> /// <param name="previousAliases">the current aliases for this import</param> void OnCodeDirectoryAliasesChanged(ICSharpProjectRoot project, int previousAliasesCount, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1)] string[] previousAliases, int currentAliasesCount, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 3)] string[] currentAliases); /// <summary> /// Called by the project system to tell the project site to create a live reference to an existing C# code /// directory. /// </summary> /// <param name="assemblyFileName">The assembly file specified by "assemblyFileName" doesn't need to physically /// exist on disk for CodeSense to work, but calling "Build" on the project will fail if the file doesn't exist /// at that point.</param> /// <param name="project">The project site for "project" must exist (i.e. BindToProject(project) must have been /// called prior to this call)</param> /// <param name="optionID">Indicates whether the reference is a regular reference or one that needs to be /// embedded into the target assembly (as indicated to the compiler through /link compiler option).</param> void AddReferenceToCodeDirectoryEx([MarshalAs(UnmanagedType.LPWStr)] string assemblyFileName, ICSharpProjectRoot project, CompilerOptions optionID); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop { /// <summary> /// Implemented to support project-to-project references. Despite its name, it's used for things other than Venus. /// </summary> [ComImport] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [Guid("97604d5d-7935-47fd-91c6-2747a5523855")] internal interface ICSharpVenusProjectSite { /// <summary> /// This function should not be used by any new code; it is now superseded by AddReferenceToCodeDirectoryEx. The /// function has not been removed due to the hard-dependency on this particular signature in Venus' templates. /// </summary> [Obsolete] void AddReferenceToCodeDirectory([MarshalAs(UnmanagedType.LPWStr)] string assemblyFileName, ICSharpProjectRoot project); /// <summary> /// Called by the venus project system to tell the project site to remove a live reference to an existing C# /// code directory. /// </summary> void RemoveReferenceToCodeDirectory([MarshalAs(UnmanagedType.LPWStr)] string assemblyFileName, ICSharpProjectRoot project); /// <summary> NOTE: This is not called by any project system in Dev11 according /// to http://bang/. Remove? /// /// [Optional] Called by the Venus Project system when a file of the Project /// site has been updated outside the editor. This is a workaround to allow /// the Venus project system implement a FileSystemWatcher for C#, since /// the C# language service doesn't support this yet. /// Not calling this when a file is updated on disk means code sense /// will not be up to date wrt to the changes on disk. /// </summary> void OnDiskFileUpdated([MarshalAs(UnmanagedType.LPWStr)] string filename, ref System.Runtime.InteropServices.ComTypes.FILETIME pFT); /// <summary>Called when aliases for an import are changed</summary> /// <param name="project">the project whose aliases we are changing</param> /// <param name="previousAliasesCount">number of elements in the previousAliases array</param> /// <param name="currentAliasesCount">number of elements in the currentAliases array</param> /// <param name="currentAliases">the previous aliases for this import</param> /// <param name="previousAliases">the current aliases for this import</param> void OnCodeDirectoryAliasesChanged(ICSharpProjectRoot project, int previousAliasesCount, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1)] string[] previousAliases, int currentAliasesCount, [In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 3)] string[] currentAliases); /// <summary> /// Called by the project system to tell the project site to create a live reference to an existing C# code /// directory. /// </summary> /// <param name="assemblyFileName">The assembly file specified by "assemblyFileName" doesn't need to physically /// exist on disk for CodeSense to work, but calling "Build" on the project will fail if the file doesn't exist /// at that point.</param> /// <param name="project">The project site for "project" must exist (i.e. BindToProject(project) must have been /// called prior to this call)</param> /// <param name="optionID">Indicates whether the reference is a regular reference or one that needs to be /// embedded into the target assembly (as indicated to the compiler through /link compiler option).</param> void AddReferenceToCodeDirectoryEx([MarshalAs(UnmanagedType.LPWStr)] string assemblyFileName, ICSharpProjectRoot project, CompilerOptions optionID); } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Features/Core/Portable/MoveToNamespace/AbstractMoveToNamespaceCodeAction.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeActions.WorkspaceServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MoveToNamespace { internal abstract partial class AbstractMoveToNamespaceCodeAction : CodeActionWithOptions { private readonly IMoveToNamespaceService _moveToNamespaceService; private readonly MoveToNamespaceAnalysisResult _moveToNamespaceAnalysisResult; public AbstractMoveToNamespaceCodeAction(IMoveToNamespaceService moveToNamespaceService, MoveToNamespaceAnalysisResult analysisResult) { _moveToNamespaceService = moveToNamespaceService; _moveToNamespaceAnalysisResult = analysisResult; } public override object GetOptions(CancellationToken cancellationToken) { return _moveToNamespaceService.GetChangeNamespaceOptions( _moveToNamespaceAnalysisResult.Document, _moveToNamespaceAnalysisResult.OriginalNamespace, _moveToNamespaceAnalysisResult.Namespaces); } protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken) { // We won't get an empty target namespace from VS, but still should handle it w/o crashing. if (options is MoveToNamespaceOptionsResult moveToNamespaceOptions && !moveToNamespaceOptions.IsCancelled && !string.IsNullOrEmpty(moveToNamespaceOptions.Namespace)) { var moveToNamespaceResult = await _moveToNamespaceService.MoveToNamespaceAsync( _moveToNamespaceAnalysisResult, moveToNamespaceOptions.Namespace, cancellationToken).ConfigureAwait(false); if (moveToNamespaceResult.Succeeded) { return CreateRenameOperations(moveToNamespaceResult); } } return SpecializedCollections.EmptyEnumerable<CodeActionOperation>(); } private static ImmutableArray<CodeActionOperation> CreateRenameOperations(MoveToNamespaceResult moveToNamespaceResult) { Debug.Assert(moveToNamespaceResult.Succeeded); using var _ = PooledObjects.ArrayBuilder<CodeActionOperation>.GetInstance(out var operations); operations.Add(new ApplyChangesOperation(moveToNamespaceResult.UpdatedSolution)); var symbolRenameCodeActionOperationFactory = moveToNamespaceResult.UpdatedSolution.Workspace.Services.GetService<ISymbolRenamedCodeActionOperationFactoryWorkspaceService>(); // It's possible we're not in a host context providing this service, in which case // just provide a code action that won't notify of the symbol rename. // Without the symbol rename operation, code generators (like WPF) may not // know to regenerate code correctly. if (symbolRenameCodeActionOperationFactory != null) { foreach (var (newName, symbol) in moveToNamespaceResult.NewNameOriginalSymbolMapping) { operations.Add(symbolRenameCodeActionOperationFactory.CreateSymbolRenamedOperation( symbol, newName, moveToNamespaceResult.OriginalSolution, moveToNamespaceResult.UpdatedSolution)); } } return operations.ToImmutable(); } public static AbstractMoveToNamespaceCodeAction Generate(IMoveToNamespaceService changeNamespaceService, MoveToNamespaceAnalysisResult analysisResult) => analysisResult.Container switch { MoveToNamespaceAnalysisResult.ContainerType.NamedType => new MoveTypeToNamespaceCodeAction(changeNamespaceService, analysisResult), MoveToNamespaceAnalysisResult.ContainerType.Namespace => new MoveItemsToNamespaceCodeAction(changeNamespaceService, analysisResult), _ => throw ExceptionUtilities.UnexpectedValue(analysisResult.Container) }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeActions.WorkspaceServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MoveToNamespace { internal abstract partial class AbstractMoveToNamespaceCodeAction : CodeActionWithOptions { private readonly IMoveToNamespaceService _moveToNamespaceService; private readonly MoveToNamespaceAnalysisResult _moveToNamespaceAnalysisResult; public AbstractMoveToNamespaceCodeAction(IMoveToNamespaceService moveToNamespaceService, MoveToNamespaceAnalysisResult analysisResult) { _moveToNamespaceService = moveToNamespaceService; _moveToNamespaceAnalysisResult = analysisResult; } public override object GetOptions(CancellationToken cancellationToken) { return _moveToNamespaceService.GetChangeNamespaceOptions( _moveToNamespaceAnalysisResult.Document, _moveToNamespaceAnalysisResult.OriginalNamespace, _moveToNamespaceAnalysisResult.Namespaces); } protected override async Task<IEnumerable<CodeActionOperation>> ComputeOperationsAsync(object options, CancellationToken cancellationToken) { // We won't get an empty target namespace from VS, but still should handle it w/o crashing. if (options is MoveToNamespaceOptionsResult moveToNamespaceOptions && !moveToNamespaceOptions.IsCancelled && !string.IsNullOrEmpty(moveToNamespaceOptions.Namespace)) { var moveToNamespaceResult = await _moveToNamespaceService.MoveToNamespaceAsync( _moveToNamespaceAnalysisResult, moveToNamespaceOptions.Namespace, cancellationToken).ConfigureAwait(false); if (moveToNamespaceResult.Succeeded) { return CreateRenameOperations(moveToNamespaceResult); } } return SpecializedCollections.EmptyEnumerable<CodeActionOperation>(); } private static ImmutableArray<CodeActionOperation> CreateRenameOperations(MoveToNamespaceResult moveToNamespaceResult) { Debug.Assert(moveToNamespaceResult.Succeeded); using var _ = PooledObjects.ArrayBuilder<CodeActionOperation>.GetInstance(out var operations); operations.Add(new ApplyChangesOperation(moveToNamespaceResult.UpdatedSolution)); var symbolRenameCodeActionOperationFactory = moveToNamespaceResult.UpdatedSolution.Workspace.Services.GetService<ISymbolRenamedCodeActionOperationFactoryWorkspaceService>(); // It's possible we're not in a host context providing this service, in which case // just provide a code action that won't notify of the symbol rename. // Without the symbol rename operation, code generators (like WPF) may not // know to regenerate code correctly. if (symbolRenameCodeActionOperationFactory != null) { foreach (var (newName, symbol) in moveToNamespaceResult.NewNameOriginalSymbolMapping) { operations.Add(symbolRenameCodeActionOperationFactory.CreateSymbolRenamedOperation( symbol, newName, moveToNamespaceResult.OriginalSolution, moveToNamespaceResult.UpdatedSolution)); } } return operations.ToImmutable(); } public static AbstractMoveToNamespaceCodeAction Generate(IMoveToNamespaceService changeNamespaceService, MoveToNamespaceAnalysisResult analysisResult) => analysisResult.Container switch { MoveToNamespaceAnalysisResult.ContainerType.NamedType => new MoveTypeToNamespaceCodeAction(changeNamespaceService, analysisResult), MoveToNamespaceAnalysisResult.ContainerType.Namespace => new MoveItemsToNamespaceCodeAction(changeNamespaceService, analysisResult), _ => throw ExceptionUtilities.UnexpectedValue(analysisResult.Container) }; } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/EditorFeatures/TestUtilities/NavigateTo/NavigateToTestAggregator.Callback.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.VisualStudio.Language.NavigateTo.Interfaces; using Roslyn.Utilities; namespace Roslyn.Test.EditorUtilities.NavigateTo { public sealed partial class NavigateToTestAggregator { private sealed class Callback : INavigateToCallback { private readonly List<NavigateToItem> _itemsReceived = new(); private readonly TaskCompletionSource<IEnumerable<NavigateToItem>> _taskCompletionSource = new TaskCompletionSource<IEnumerable<NavigateToItem>>(); public Callback(INavigateToOptions options) { Contract.ThrowIfNull(options); Options = options; } public void AddItem(NavigateToItem item) { lock (_itemsReceived) _itemsReceived.Add(item); } public void Done() => _taskCompletionSource.SetResult(_itemsReceived); public void Invalidate() => throw new InvalidOperationException("Unexpected call to Invalidate."); public Task<IEnumerable<NavigateToItem>> GetItemsAsync() => _taskCompletionSource.Task; public INavigateToOptions Options { get; } public void ReportProgress(int current, int maximum) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.VisualStudio.Language.NavigateTo.Interfaces; using Roslyn.Utilities; namespace Roslyn.Test.EditorUtilities.NavigateTo { public sealed partial class NavigateToTestAggregator { private sealed class Callback : INavigateToCallback { private readonly List<NavigateToItem> _itemsReceived = new(); private readonly TaskCompletionSource<IEnumerable<NavigateToItem>> _taskCompletionSource = new TaskCompletionSource<IEnumerable<NavigateToItem>>(); public Callback(INavigateToOptions options) { Contract.ThrowIfNull(options); Options = options; } public void AddItem(NavigateToItem item) { lock (_itemsReceived) _itemsReceived.Add(item); } public void Done() => _taskCompletionSource.SetResult(_itemsReceived); public void Invalidate() => throw new InvalidOperationException("Unexpected call to Invalidate."); public Task<IEnumerable<NavigateToItem>> GetItemsAsync() => _taskCompletionSource.Task; public INavigateToOptions Options { get; } public void ReportProgress(int current, int maximum) { } } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/VisualStudio/Core/Def/Implementation/Progression/GraphQueries/OverridesGraphQuery.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.GraphModel; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed class OverridesGraphQuery : IGraphQuery { public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.GraphQuery_Overrides, KeyValueLogMessage.Create(LogType.UserAction), cancellationToken)) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { var symbol = graphBuilder.GetSymbol(node, cancellationToken); if (symbol is IMethodSymbol or IPropertySymbol or IEventSymbol) { var overrides = await SymbolFinder.FindOverridesAsync(symbol, solution, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var o in overrides) { var symbolNode = await graphBuilder.AddNodeAsync(o, relatedNode: node, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(symbolNode, RoslynGraphCategories.Overrides, node, cancellationToken); } } } return graphBuilder; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.VisualStudio.GraphModel; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed class OverridesGraphQuery : IGraphQuery { public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.GraphQuery_Overrides, KeyValueLogMessage.Create(LogType.UserAction), cancellationToken)) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { var symbol = graphBuilder.GetSymbol(node, cancellationToken); if (symbol is IMethodSymbol or IPropertySymbol or IEventSymbol) { var overrides = await SymbolFinder.FindOverridesAsync(symbol, solution, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var o in overrides) { var symbolNode = await graphBuilder.AddNodeAsync(o, relatedNode: node, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(symbolNode, RoslynGraphCategories.Overrides, node, cancellationToken); } } } return graphBuilder; } } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Tools/IdeCoreBenchmarks/FindReferencesBenchmarks.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using AnalyzerRunner; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Diagnosers; using Microsoft.Build.Locator; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.CodeAnalysis.Storage; namespace IdeCoreBenchmarks { [MemoryDiagnoser] public class FindReferencesBenchmarks { [Benchmark] public async Task RunFindReferences() { try { // QueryVisualStudioInstances returns Visual Studio installations on .NET Framework, and .NET Core SDK // installations on .NET Core. We use the one with the most recent version. var msBuildInstance = MSBuildLocator.QueryVisualStudioInstances().OrderByDescending(x => x.Version).First(); MSBuildLocator.RegisterInstance(msBuildInstance); var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName); var solutionPath = Path.Combine(roslynRoot, @"C:\github\roslyn\Compilers.sln"); if (!File.Exists(solutionPath)) throw new ArgumentException("Couldn't find Compilers.sln"); Console.Write("Found Compilers.sln: " + Process.GetCurrentProcess().Id); var assemblies = MSBuildMefHostServices.DefaultAssemblies .Add(typeof(AnalyzerRunnerHelper).Assembly) .Add(typeof(FindReferencesBenchmarks).Assembly); var services = MefHostServices.Create(assemblies); var workspace = MSBuildWorkspace.Create(new Dictionary<string, string> { // Use the latest language version to force the full set of available analyzers to run on the project. { "LangVersion", "9.0" }, }, services); if (workspace == null) throw new ArgumentException("Couldn't create workspace"); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(StorageOptions.Database, StorageDatabase.SQLite))); Console.WriteLine("Opening roslyn. Attach to: " + Process.GetCurrentProcess().Id); var start = DateTime.Now; var solution = workspace.OpenSolutionAsync(solutionPath, progress: null, CancellationToken.None).Result; Console.WriteLine("Finished opening roslyn: " + (DateTime.Now - start)); // Force a storage instance to be created. This makes it simple to go examine it prior to any operations we // perform, including seeing how big the initial string table is. var storageService = workspace.Services.GetService<IPersistentStorageService>(); if (storageService == null) throw new ArgumentException("Couldn't get storage service"); using (var storage = await storageService.GetStorageAsync(workspace.CurrentSolution, CancellationToken.None)) { Console.WriteLine(); } // There might be multiple projects with this name. That's ok. FAR goes and finds all the linked-projects // anyways to perform the search on all the equivalent symbols from them. So the end perf cost is the // same. var project = solution.Projects.First(p => p.AssemblyName == "Microsoft.CodeAnalysis"); start = DateTime.Now; var compilation = await project.GetCompilationAsync(); Console.WriteLine("Time to get first compilation: " + (DateTime.Now - start)); var type = compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.SyntaxToken"); if (type == null) throw new Exception("Couldn't find type"); Console.WriteLine("Starting find-refs"); start = DateTime.Now; var references = await SymbolFinder.FindReferencesAsync(type, solution); Console.WriteLine("Time to find-refs: " + (DateTime.Now - start)); var refList = references.ToList(); Console.WriteLine($"References count: {refList.Count}"); var locations = refList.SelectMany(r => r.Locations).ToList(); Console.WriteLine($"Locations count: {locations.Count}"); } catch (ReflectionTypeLoadException ex) { foreach (var ex2 in ex.LoaderExceptions) Console.WriteLine(ex2); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using AnalyzerRunner; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Diagnosers; using Microsoft.Build.Locator; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.MSBuild; using Microsoft.CodeAnalysis.Storage; namespace IdeCoreBenchmarks { [MemoryDiagnoser] public class FindReferencesBenchmarks { [Benchmark] public async Task RunFindReferences() { try { // QueryVisualStudioInstances returns Visual Studio installations on .NET Framework, and .NET Core SDK // installations on .NET Core. We use the one with the most recent version. var msBuildInstance = MSBuildLocator.QueryVisualStudioInstances().OrderByDescending(x => x.Version).First(); MSBuildLocator.RegisterInstance(msBuildInstance); var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName); var solutionPath = Path.Combine(roslynRoot, @"C:\github\roslyn\Compilers.sln"); if (!File.Exists(solutionPath)) throw new ArgumentException("Couldn't find Compilers.sln"); Console.Write("Found Compilers.sln: " + Process.GetCurrentProcess().Id); var assemblies = MSBuildMefHostServices.DefaultAssemblies .Add(typeof(AnalyzerRunnerHelper).Assembly) .Add(typeof(FindReferencesBenchmarks).Assembly); var services = MefHostServices.Create(assemblies); var workspace = MSBuildWorkspace.Create(new Dictionary<string, string> { // Use the latest language version to force the full set of available analyzers to run on the project. { "LangVersion", "9.0" }, }, services); if (workspace == null) throw new ArgumentException("Couldn't create workspace"); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options .WithChangedOption(StorageOptions.Database, StorageDatabase.SQLite))); Console.WriteLine("Opening roslyn. Attach to: " + Process.GetCurrentProcess().Id); var start = DateTime.Now; var solution = workspace.OpenSolutionAsync(solutionPath, progress: null, CancellationToken.None).Result; Console.WriteLine("Finished opening roslyn: " + (DateTime.Now - start)); // Force a storage instance to be created. This makes it simple to go examine it prior to any operations we // perform, including seeing how big the initial string table is. var storageService = workspace.Services.GetService<IPersistentStorageService>(); if (storageService == null) throw new ArgumentException("Couldn't get storage service"); using (var storage = await storageService.GetStorageAsync(workspace.CurrentSolution, CancellationToken.None)) { Console.WriteLine(); } // There might be multiple projects with this name. That's ok. FAR goes and finds all the linked-projects // anyways to perform the search on all the equivalent symbols from them. So the end perf cost is the // same. var project = solution.Projects.First(p => p.AssemblyName == "Microsoft.CodeAnalysis"); start = DateTime.Now; var compilation = await project.GetCompilationAsync(); Console.WriteLine("Time to get first compilation: " + (DateTime.Now - start)); var type = compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.SyntaxToken"); if (type == null) throw new Exception("Couldn't find type"); Console.WriteLine("Starting find-refs"); start = DateTime.Now; var references = await SymbolFinder.FindReferencesAsync(type, solution); Console.WriteLine("Time to find-refs: " + (DateTime.Now - start)); var refList = references.ToList(); Console.WriteLine($"References count: {refList.Count}"); var locations = refList.SelectMany(r => r.Locations).ToList(); Console.WriteLine($"Locations count: {locations.Count}"); } catch (ReflectionTypeLoadException ex) { foreach (var ex2 in ex.LoaderExceptions) Console.WriteLine(ex2); } } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/Core/CodeAnalysisTest/Collections/ImmutableArrayExtensionsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Collections.ObjectModel; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public class ImmutableArrayExtensionsTests { [Fact] public void CreateFrom() { ImmutableArray<int> a; a = ImmutableArray.Create<int>(2); Assert.Equal(1, a.Length); Assert.Equal(2, a[0]); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange<int>((IEnumerable<int>)null)); a = ImmutableArray.CreateRange<int>(Enumerable.Range(1, 2)); Assert.Equal(2, a.Length); Assert.Equal(1, a[0]); Assert.Equal(2, a[1]); } [Fact] public void ReadOnlyArraysBroken() { var b = new ArrayBuilder<String>(); b.Add("hello"); b.Add("world"); Assert.Equal("hello", b[0]); var a = b.AsImmutable(); Assert.Equal("hello", a[0]); var e = (IEnumerable<string>)a; Assert.Equal("hello", e.First()); var aa = e.ToArray(); Assert.Equal("hello", aa[0]); var first = b.FirstOrDefault((x) => true); Assert.Equal("hello", first); ImmutableArray<int> nullOrEmpty = default(ImmutableArray<int>); Assert.True(nullOrEmpty.IsDefault); Assert.True(nullOrEmpty.IsDefaultOrEmpty); Assert.Throws<NullReferenceException>(() => nullOrEmpty.IsEmpty); nullOrEmpty = ImmutableArray.Create<int>(); Assert.True(nullOrEmpty.IsEmpty); } [Fact] public void InsertAt() { var builder = new ArrayBuilder<String>(); builder.Insert(0, "candy"); builder.Insert(0, "apple"); builder.Insert(2, "elephant"); builder.Insert(2, "drum"); builder.Insert(1, "banana"); builder.Insert(0, "$$$"); Assert.Equal("$$$", builder[0]); Assert.Equal("apple", builder[1]); Assert.Equal("banana", builder[2]); Assert.Equal("candy", builder[3]); Assert.Equal("drum", builder[4]); Assert.Equal("elephant", builder[5]); } [Fact] public void SetEquals() { var nul = default(ImmutableArray<int>); var empty = ImmutableArray.Create<int>(); var original = new int[] { 1, 2, 3, }.AsImmutableOrNull(); var notEqualSubset = new int[] { 1, 2, }.AsImmutableOrNull(); var notEqualSuperset = new int[] { 1, 2, 3, 4, }.AsImmutableOrNull(); var equalOrder = new int[] { 2, 1, 3, }.AsImmutableOrNull(); var equalElements = new int[] { -1, -2, -3 }.AsImmutableOrNull(); var equalDuplicate = new int[] { 1, 2, 3, 3, -3 }.AsImmutableOrNull(); IEqualityComparer<int> comparer = new AbsoluteValueComparer(); Assert.True(nul.SetEquals(nul, comparer)); Assert.True(empty.SetEquals(empty, comparer)); Assert.True(original.SetEquals(original, comparer)); Assert.True(original.SetEquals(equalOrder, comparer)); Assert.True(original.SetEquals(equalElements, comparer)); Assert.True(original.SetEquals(equalDuplicate, comparer)); Assert.False(nul.SetEquals(empty, comparer)); Assert.False(nul.SetEquals(original, comparer)); Assert.False(empty.SetEquals(nul, comparer)); Assert.False(empty.SetEquals(original, comparer)); Assert.False(original.SetEquals(nul, comparer)); Assert.False(original.SetEquals(empty, comparer)); Assert.False(original.SetEquals(notEqualSubset, comparer)); Assert.False(original.SetEquals(notEqualSuperset, comparer)); //there's a special case for this in the impl, so cover it specially var singleton1 = ImmutableArray.Create<int>(1); var singleton2 = ImmutableArray.Create<int>(2); Assert.True(singleton1.SetEquals(singleton1, comparer)); Assert.False(singleton1.SetEquals(singleton2, comparer)); } private class AbsoluteValueComparer : IEqualityComparer<int> { #region IEqualityComparer<int> Members bool IEqualityComparer<int>.Equals(int x, int y) { return Math.Abs(x) == Math.Abs(y); } int IEqualityComparer<int>.GetHashCode(int x) { return Math.Abs(x); } #endregion } [Fact] public void Single() { Assert.Throws<NullReferenceException>(() => default(ImmutableArray<int>).Single()); Assert.Throws<InvalidOperationException>(() => ImmutableArray.Create<int>().Single()); Assert.Equal(1, ImmutableArray.Create<int>(1).Single()); Assert.Throws<InvalidOperationException>(() => ImmutableArray.Create<int>(1, 2).Single()); Func<int, bool> isOdd = x => x % 2 == 1; // BUG:753260 Should this be ArgumentNullException for consistency? Assert.Throws<NullReferenceException>(() => default(ImmutableArray<int>).Single(isOdd)); Assert.Throws<InvalidOperationException>(() => ImmutableArray.Create<int>().Single(isOdd)); Assert.Equal(1, ImmutableArray.Create<int>(1, 2).Single(isOdd)); Assert.Throws<InvalidOperationException>(() => ImmutableArray.Create<int>(1, 2, 3).Single(isOdd)); } [Fact] public void IndexOf() { var roa = new int[] { 1, 2, 3 }.AsImmutableOrNull(); Assert.Equal(1, roa.IndexOf(2)); } [Fact] public void CompareToNull() { var roaNull = default(ImmutableArray<int>); Assert.True(roaNull == null); Assert.False(roaNull != null); Assert.True(null == roaNull); Assert.False(null != roaNull); var copy = roaNull; Assert.True(copy == roaNull); Assert.False(copy != roaNull); var notnull = ImmutableArray.Create<int>(); Assert.False(notnull == null); Assert.True(notnull != null); Assert.False(null == notnull); Assert.True(null != notnull); } [Fact] public void CopyTo() { var roa = new int?[] { 1, null, 3 }.AsImmutableOrNull(); var roaCopy = new int?[4]; roa.CopyTo(roaCopy, 1); Assert.False(roaCopy[0].HasValue); Assert.Equal(1, roaCopy[1].Value); Assert.False(roaCopy[2].HasValue); Assert.Equal(3, roaCopy[3].Value); } [Fact] public void ElementAt() { var roa = new int?[] { 1, null, 3 }.AsImmutableOrNull(); Assert.Equal(1, roa.ElementAt(0).Value); Assert.False(roa.ElementAt(1).HasValue); Assert.Equal(3, roa.ElementAt(2).Value); } [Fact] public void ElementAtOrDefault() { var roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull(); Assert.False(roa.ElementAtOrDefault(-1).HasValue); Assert.Equal(1, roa.ElementAtOrDefault(0).Value); Assert.Equal(2, roa.ElementAtOrDefault(1).Value); Assert.Equal(3, roa.ElementAtOrDefault(2).Value); Assert.False(roa.ElementAtOrDefault(10).HasValue); } [Fact] public void Last() { var roa = new int?[] { }.AsImmutableOrNull(); Assert.Throws<InvalidOperationException>(() => roa.Last()); roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull(); Assert.Throws<InvalidOperationException>(() => roa.Last(i => i < 1)); Assert.Equal(3, roa.Last(i => i > 1)); } [Fact] public void LastOrDefault() { var roa = new int?[] { }.AsImmutableOrNull(); Assert.False(roa.LastOrDefault().HasValue); roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull(); Assert.False(roa.LastOrDefault(i => i < 1).HasValue); Assert.Equal(3, roa.LastOrDefault(i => i > 1)); } [Fact] public void SingleOrDefault() { var roa = new int?[] { }.AsImmutableOrNull(); Assert.False(roa.SingleOrDefault().HasValue); roa = new int?[] { 1 }.AsImmutableOrNull(); Assert.Equal(1, roa.SingleOrDefault()); roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull(); Assert.Throws<InvalidOperationException>(() => roa.SingleOrDefault()); roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull(); Assert.Equal(2, roa.SingleOrDefault(i => i == 2)); } [Fact] public void Concat() { var empty = ImmutableArray.Create<int>(); var a = ImmutableArray.Create<int>(0, 2, 4); Assert.Equal(empty, empty.Concat(empty)); Assert.Equal(a, a.Concat(empty)); Assert.Equal(a, empty.Concat(a)); Assert.True(a.Concat(a).SequenceEqual(ImmutableArray.Create<int>(0, 2, 4, 0, 2, 4))); } [Fact] public void AddRange() { var empty = ImmutableArray.Create<int>(); var a = ImmutableArray.Create<int>(0, 2, 4); Assert.Equal(empty, empty.AddRange(empty)); Assert.Equal(a, a.AddRange(empty)); Assert.Equal(a, empty.AddRange(a)); Assert.True(a.AddRange(a).SequenceEqual(ImmutableArray.Create<int>(0, 2, 4, 0, 2, 4))); Assert.Equal(empty, empty.AddRange((IEnumerable<int>)empty)); Assert.Equal(a, a.AddRange((IEnumerable<int>)empty)); Assert.True(a.SequenceEqual(empty.AddRange((IEnumerable<int>)a))); Assert.True(a.AddRange((IEnumerable<int>)a).SequenceEqual(ImmutableArray.Create<int>(0, 2, 4, 0, 2, 4))); } [Fact] public void InsertRange() { var empty = ImmutableArray.Create<int>(); var a = ImmutableArray.Create<int>(0, 2, 4); Assert.Equal(empty, empty.InsertRange(0, empty)); Assert.Equal(a, a.InsertRange(0, empty)); Assert.Equal(a, a.InsertRange(2, empty)); Assert.True(a.SequenceEqual(empty.InsertRange(0, a))); Assert.True(a.InsertRange(2, a).SequenceEqual(ImmutableArray.Create<int>(0, 2, 0, 2, 4, 4))); } [Fact] public void ToDictionary() { var roa = new string[] { "one:1", "two:2", "three:3" }.AsImmutableOrNull(); // Call extension method directly to resolve the ambiguity with EnumerableExtensions.ToDictionary var dict = System.Linq.ImmutableArrayExtensions.ToDictionary(roa, s => s.Split(':').First()); Assert.Equal("one:1", dict["one"]); Assert.Equal("two:2", dict["two"]); Assert.Equal("three:3", dict["three"]); Assert.Throws<KeyNotFoundException>(() => dict["One"]); dict = System.Linq.ImmutableArrayExtensions.ToDictionary(roa, s => s.Split(':').First(), StringComparer.OrdinalIgnoreCase); Assert.Equal("one:1", dict["one"]); Assert.Equal("two:2", dict["Two"]); Assert.Equal("three:3", dict["THREE"]); Assert.Throws<KeyNotFoundException>(() => dict[""]); dict = System.Linq.ImmutableArrayExtensions.ToDictionary(roa, s => s.Split(':').First(), s => s.Split(':').Last()); Assert.Equal("1", dict["one"]); Assert.Equal("2", dict["two"]); Assert.Equal("3", dict["three"]); Assert.Throws<KeyNotFoundException>(() => dict["THREE"]); dict = System.Linq.ImmutableArrayExtensions.ToDictionary(roa, s => s.Split(':').First(), s => s.Split(':').Last(), StringComparer.OrdinalIgnoreCase); Assert.Equal("1", dict["onE"]); Assert.Equal("2", dict["Two"]); Assert.Equal("3", dict["three"]); Assert.Throws<KeyNotFoundException>(() => dict["four"]); } [Fact] public void SequenceEqual() { var a = ImmutableArray.Create<string>("A", "B", "C"); var b = ImmutableArray.Create<string>("A", "b", "c"); var c = ImmutableArray.Create<string>("A", "b"); Assert.False(a.SequenceEqual(b)); Assert.True(a.SequenceEqual(b, StringComparer.OrdinalIgnoreCase)); Assert.False(a.SequenceEqual(c)); Assert.False(a.SequenceEqual(c, StringComparer.OrdinalIgnoreCase)); Assert.False(c.SequenceEqual(a)); var r = ImmutableArray.Create<int>(1, 2, 3); Assert.True(r.SequenceEqual(Enumerable.Range(1, 3))); Assert.False(r.SequenceEqual(Enumerable.Range(1, 2))); Assert.False(r.SequenceEqual(Enumerable.Range(1, 4))); var s = ImmutableArray.Create<int>(10, 20, 30); Assert.True(r.SequenceEqual(s, (x, y) => 10 * x == y)); } [Fact] public void SelectAsArray() { var empty = ImmutableArray.Create<object>(); Assert.True(empty.SequenceEqual(empty.SelectAsArray(item => item))); Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, arg) => item, 1))); Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, arg) => arg, 2))); Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, index, arg) => item, 1))); Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, index, arg) => arg, 2))); Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, index, arg) => index, 3))); var a = ImmutableArray.Create<int>(3, 2, 1, 0); var b = ImmutableArray.Create<int>(0, 1, 2, 3); var c = ImmutableArray.Create<int>(2, 2, 2, 2); Assert.True(a.SequenceEqual(a.SelectAsArray(item => item))); Assert.True(a.SequenceEqual(a.SelectAsArray((item, arg) => item, 1))); Assert.True(c.SequenceEqual(a.SelectAsArray((item, arg) => arg, 2))); Assert.True(a.SequenceEqual(a.SelectAsArray((item, index, arg) => item, 1))); Assert.True(c.SequenceEqual(a.SelectAsArray((item, index, arg) => arg, 2))); Assert.True(b.SequenceEqual(a.SelectAsArray((item, index, arg) => index, 3))); AssertEx.Equal(new[] { 10 }, ImmutableArray.Create(1).SelectAsArray(i => 10 * i)); AssertEx.Equal(new[] { 10, 20 }, ImmutableArray.Create(1, 2).SelectAsArray(i => 10 * i)); AssertEx.Equal(new[] { 10, 20, 30 }, ImmutableArray.Create(1, 2, 3).SelectAsArray(i => 10 * i)); AssertEx.Equal(new[] { 10, 20, 30, 40 }, ImmutableArray.Create(1, 2, 3, 4).SelectAsArray(i => 10 * i)); AssertEx.Equal(new[] { 10, 20, 30, 40, 50 }, ImmutableArray.Create(1, 2, 3, 4, 5).SelectAsArray(i => 10 * i)); } [Fact] public void SelectAsArrayWithPredicate() { Assert.Empty(ImmutableArray<object>.Empty.SelectAsArray<object, int>(item => throw null, item => throw null)); var array = ImmutableArray.Create(1, 2, 3, 4, 5); AssertEx.Equal(new[] { 2, 3, 4, 5, 6 }, array.SelectAsArray(item => true, item => item + 1)); AssertEx.Equal(new[] { 3, 5 }, array.SelectAsArray(item => item % 2 == 0, item => item + 1)); Assert.Empty(array.SelectAsArray<int, int>(item => item < 0, item => throw null)); } [Fact] public void ZipAsArray() { var empty = ImmutableArray.Create<object>(); Assert.True(empty.SequenceEqual(empty.ZipAsArray(empty, (item1, item2) => item1))); var single1 = ImmutableArray.Create(1); var single2 = ImmutableArray.Create(10); var single3 = ImmutableArray.Create(11); Assert.True(single3.SequenceEqual(single1.ZipAsArray(single2, (item1, item2) => item1 + item2))); var pair1 = ImmutableArray.Create(1, 2); var pair2 = ImmutableArray.Create(10, 11); var pair3 = ImmutableArray.Create(11, 13); Assert.True(pair3.SequenceEqual(pair1.ZipAsArray(pair2, (item1, item2) => item1 + item2))); var triple1 = ImmutableArray.Create(1, 2, 3); var triple2 = ImmutableArray.Create(10, 11, 12); var triple3 = ImmutableArray.Create(11, 13, 15); Assert.True(triple3.SequenceEqual(triple1.ZipAsArray(triple2, (item1, item2) => item1 + item2))); var quad1 = ImmutableArray.Create(1, 2, 3, 4); var quad2 = ImmutableArray.Create(10, 11, 12, 13); var quad3 = ImmutableArray.Create(11, 13, 15, 17); Assert.True(quad3.SequenceEqual(quad1.ZipAsArray(quad2, (item1, item2) => item1 + item2))); var quin1 = ImmutableArray.Create(1, 2, 3, 4, 5); var quin2 = ImmutableArray.Create(10, 11, 12, 13, 14); var quin3 = ImmutableArray.Create(11, 13, 15, 17, 19); Assert.True(quin3.SequenceEqual(quin1.ZipAsArray(quin2, (item1, item2) => item1 + item2))); } [Fact] public void ZipAsArrayWithIndex() { var empty = ImmutableArray.Create<object>(); Assert.True(empty.SequenceEqual(empty.ZipAsArray(empty, (item1, item2) => item1))); var single1 = ImmutableArray.Create(1); var single2 = ImmutableArray.Create(10); var single3 = ImmutableArray.Create(13); Assert.True(single3.SequenceEqual(single1.ZipAsArray(single2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg))); var pair1 = ImmutableArray.Create(1, 2); var pair2 = ImmutableArray.Create(10, 11); var pair3 = ImmutableArray.Create(13, 16); Assert.True(pair3.SequenceEqual(pair1.ZipAsArray(pair2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg))); var triple1 = ImmutableArray.Create(1, 2, 3); var triple2 = ImmutableArray.Create(10, 11, 12); var triple3 = ImmutableArray.Create(13, 16, 19); Assert.True(triple3.SequenceEqual(triple1.ZipAsArray(triple2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg))); var quad1 = ImmutableArray.Create(1, 2, 3, 4); var quad2 = ImmutableArray.Create(10, 11, 12, 13); var quad3 = ImmutableArray.Create(13, 16, 19, 22); Assert.True(quad3.SequenceEqual(quad1.ZipAsArray(quad2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg))); var quin1 = ImmutableArray.Create(1, 2, 3, 4, 5); var quin2 = ImmutableArray.Create(10, 11, 12, 13, 14); var quin3 = ImmutableArray.Create(13, 16, 19, 22, 25); Assert.True(quin3.SequenceEqual(quin1.ZipAsArray(quin2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg))); } [Fact] public void WhereAsArray() { var empty = ImmutableArray.Create<object>(); // All. Assert.Equal(empty, empty.WhereAsArray(o => true)); // None. Assert.Equal(empty, empty.WhereAsArray(o => false)); var a = ImmutableArray.Create<int>(0, 1, 2, 3, 4, 5); // All. Assert.Equal(a, a.WhereAsArray(i => true)); // None. Assert.True(a.WhereAsArray(i => false).SequenceEqual(ImmutableArray.Create<int>())); // All but the first. Assert.True(a.WhereAsArray(i => i > 0).SequenceEqual(ImmutableArray.Create<int>(1, 2, 3, 4, 5))); // All but the last. Assert.True(a.WhereAsArray(i => i < 5).SequenceEqual(ImmutableArray.Create<int>(0, 1, 2, 3, 4))); // First only. Assert.True(a.WhereAsArray(i => i == 0).SequenceEqual(ImmutableArray.Create<int>(0))); // Last only. Assert.True(a.WhereAsArray(i => i == 5).SequenceEqual(ImmutableArray.Create<int>(5))); // First half. Assert.True(a.WhereAsArray(i => i < 3).SequenceEqual(ImmutableArray.Create<int>(0, 1, 2))); // Second half. Assert.True(a.WhereAsArray(i => i > 2).SequenceEqual(ImmutableArray.Create<int>(3, 4, 5))); // Even. Assert.True(a.WhereAsArray(i => i % 2 == 0).SequenceEqual(ImmutableArray.Create<int>(0, 2, 4))); // Odd. Assert.True(a.WhereAsArray(i => i % 2 == 1).SequenceEqual(ImmutableArray.Create<int>(1, 3, 5))); } [Fact] public void WhereAsArray_WithArg() { var x = new C(); Assert.Same(x, ImmutableArray.Create<object>(x).WhereAsArray((o, arg) => o == arg, x)[0]); var a = ImmutableArray.Create(0, 1, 2, 3, 4, 5); AssertEx.Equal(new[] { 3, 4, 5 }, a.WhereAsArray((i, j) => i > j, 2)); } private class C { } private class D : C { } [Fact] public void Casting() { var arrayOfD = new D[] { new D() }.AsImmutableOrNull(); var arrayOfC = arrayOfD.Cast<D, C>(); var arrayOfD2 = arrayOfC.As<D>(); // the underlying arrays are the same: //Assert.True(arrayOfD.Equals(arrayOfC)); Assert.True(arrayOfD2.Equals(arrayOfD)); // Trying to cast from base to derived. "As" should return null (default) Assert.True(new C[] { new C() }.AsImmutableOrNull().As<D>().IsDefault); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Collections.ObjectModel; using System.Linq; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public class ImmutableArrayExtensionsTests { [Fact] public void CreateFrom() { ImmutableArray<int> a; a = ImmutableArray.Create<int>(2); Assert.Equal(1, a.Length); Assert.Equal(2, a[0]); Assert.Throws<ArgumentNullException>(() => ImmutableArray.CreateRange<int>((IEnumerable<int>)null)); a = ImmutableArray.CreateRange<int>(Enumerable.Range(1, 2)); Assert.Equal(2, a.Length); Assert.Equal(1, a[0]); Assert.Equal(2, a[1]); } [Fact] public void ReadOnlyArraysBroken() { var b = new ArrayBuilder<String>(); b.Add("hello"); b.Add("world"); Assert.Equal("hello", b[0]); var a = b.AsImmutable(); Assert.Equal("hello", a[0]); var e = (IEnumerable<string>)a; Assert.Equal("hello", e.First()); var aa = e.ToArray(); Assert.Equal("hello", aa[0]); var first = b.FirstOrDefault((x) => true); Assert.Equal("hello", first); ImmutableArray<int> nullOrEmpty = default(ImmutableArray<int>); Assert.True(nullOrEmpty.IsDefault); Assert.True(nullOrEmpty.IsDefaultOrEmpty); Assert.Throws<NullReferenceException>(() => nullOrEmpty.IsEmpty); nullOrEmpty = ImmutableArray.Create<int>(); Assert.True(nullOrEmpty.IsEmpty); } [Fact] public void InsertAt() { var builder = new ArrayBuilder<String>(); builder.Insert(0, "candy"); builder.Insert(0, "apple"); builder.Insert(2, "elephant"); builder.Insert(2, "drum"); builder.Insert(1, "banana"); builder.Insert(0, "$$$"); Assert.Equal("$$$", builder[0]); Assert.Equal("apple", builder[1]); Assert.Equal("banana", builder[2]); Assert.Equal("candy", builder[3]); Assert.Equal("drum", builder[4]); Assert.Equal("elephant", builder[5]); } [Fact] public void SetEquals() { var nul = default(ImmutableArray<int>); var empty = ImmutableArray.Create<int>(); var original = new int[] { 1, 2, 3, }.AsImmutableOrNull(); var notEqualSubset = new int[] { 1, 2, }.AsImmutableOrNull(); var notEqualSuperset = new int[] { 1, 2, 3, 4, }.AsImmutableOrNull(); var equalOrder = new int[] { 2, 1, 3, }.AsImmutableOrNull(); var equalElements = new int[] { -1, -2, -3 }.AsImmutableOrNull(); var equalDuplicate = new int[] { 1, 2, 3, 3, -3 }.AsImmutableOrNull(); IEqualityComparer<int> comparer = new AbsoluteValueComparer(); Assert.True(nul.SetEquals(nul, comparer)); Assert.True(empty.SetEquals(empty, comparer)); Assert.True(original.SetEquals(original, comparer)); Assert.True(original.SetEquals(equalOrder, comparer)); Assert.True(original.SetEquals(equalElements, comparer)); Assert.True(original.SetEquals(equalDuplicate, comparer)); Assert.False(nul.SetEquals(empty, comparer)); Assert.False(nul.SetEquals(original, comparer)); Assert.False(empty.SetEquals(nul, comparer)); Assert.False(empty.SetEquals(original, comparer)); Assert.False(original.SetEquals(nul, comparer)); Assert.False(original.SetEquals(empty, comparer)); Assert.False(original.SetEquals(notEqualSubset, comparer)); Assert.False(original.SetEquals(notEqualSuperset, comparer)); //there's a special case for this in the impl, so cover it specially var singleton1 = ImmutableArray.Create<int>(1); var singleton2 = ImmutableArray.Create<int>(2); Assert.True(singleton1.SetEquals(singleton1, comparer)); Assert.False(singleton1.SetEquals(singleton2, comparer)); } private class AbsoluteValueComparer : IEqualityComparer<int> { #region IEqualityComparer<int> Members bool IEqualityComparer<int>.Equals(int x, int y) { return Math.Abs(x) == Math.Abs(y); } int IEqualityComparer<int>.GetHashCode(int x) { return Math.Abs(x); } #endregion } [Fact] public void Single() { Assert.Throws<NullReferenceException>(() => default(ImmutableArray<int>).Single()); Assert.Throws<InvalidOperationException>(() => ImmutableArray.Create<int>().Single()); Assert.Equal(1, ImmutableArray.Create<int>(1).Single()); Assert.Throws<InvalidOperationException>(() => ImmutableArray.Create<int>(1, 2).Single()); Func<int, bool> isOdd = x => x % 2 == 1; // BUG:753260 Should this be ArgumentNullException for consistency? Assert.Throws<NullReferenceException>(() => default(ImmutableArray<int>).Single(isOdd)); Assert.Throws<InvalidOperationException>(() => ImmutableArray.Create<int>().Single(isOdd)); Assert.Equal(1, ImmutableArray.Create<int>(1, 2).Single(isOdd)); Assert.Throws<InvalidOperationException>(() => ImmutableArray.Create<int>(1, 2, 3).Single(isOdd)); } [Fact] public void IndexOf() { var roa = new int[] { 1, 2, 3 }.AsImmutableOrNull(); Assert.Equal(1, roa.IndexOf(2)); } [Fact] public void CompareToNull() { var roaNull = default(ImmutableArray<int>); Assert.True(roaNull == null); Assert.False(roaNull != null); Assert.True(null == roaNull); Assert.False(null != roaNull); var copy = roaNull; Assert.True(copy == roaNull); Assert.False(copy != roaNull); var notnull = ImmutableArray.Create<int>(); Assert.False(notnull == null); Assert.True(notnull != null); Assert.False(null == notnull); Assert.True(null != notnull); } [Fact] public void CopyTo() { var roa = new int?[] { 1, null, 3 }.AsImmutableOrNull(); var roaCopy = new int?[4]; roa.CopyTo(roaCopy, 1); Assert.False(roaCopy[0].HasValue); Assert.Equal(1, roaCopy[1].Value); Assert.False(roaCopy[2].HasValue); Assert.Equal(3, roaCopy[3].Value); } [Fact] public void ElementAt() { var roa = new int?[] { 1, null, 3 }.AsImmutableOrNull(); Assert.Equal(1, roa.ElementAt(0).Value); Assert.False(roa.ElementAt(1).HasValue); Assert.Equal(3, roa.ElementAt(2).Value); } [Fact] public void ElementAtOrDefault() { var roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull(); Assert.False(roa.ElementAtOrDefault(-1).HasValue); Assert.Equal(1, roa.ElementAtOrDefault(0).Value); Assert.Equal(2, roa.ElementAtOrDefault(1).Value); Assert.Equal(3, roa.ElementAtOrDefault(2).Value); Assert.False(roa.ElementAtOrDefault(10).HasValue); } [Fact] public void Last() { var roa = new int?[] { }.AsImmutableOrNull(); Assert.Throws<InvalidOperationException>(() => roa.Last()); roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull(); Assert.Throws<InvalidOperationException>(() => roa.Last(i => i < 1)); Assert.Equal(3, roa.Last(i => i > 1)); } [Fact] public void LastOrDefault() { var roa = new int?[] { }.AsImmutableOrNull(); Assert.False(roa.LastOrDefault().HasValue); roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull(); Assert.False(roa.LastOrDefault(i => i < 1).HasValue); Assert.Equal(3, roa.LastOrDefault(i => i > 1)); } [Fact] public void SingleOrDefault() { var roa = new int?[] { }.AsImmutableOrNull(); Assert.False(roa.SingleOrDefault().HasValue); roa = new int?[] { 1 }.AsImmutableOrNull(); Assert.Equal(1, roa.SingleOrDefault()); roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull(); Assert.Throws<InvalidOperationException>(() => roa.SingleOrDefault()); roa = new int?[] { 1, 2, 3 }.AsImmutableOrNull(); Assert.Equal(2, roa.SingleOrDefault(i => i == 2)); } [Fact] public void Concat() { var empty = ImmutableArray.Create<int>(); var a = ImmutableArray.Create<int>(0, 2, 4); Assert.Equal(empty, empty.Concat(empty)); Assert.Equal(a, a.Concat(empty)); Assert.Equal(a, empty.Concat(a)); Assert.True(a.Concat(a).SequenceEqual(ImmutableArray.Create<int>(0, 2, 4, 0, 2, 4))); } [Fact] public void AddRange() { var empty = ImmutableArray.Create<int>(); var a = ImmutableArray.Create<int>(0, 2, 4); Assert.Equal(empty, empty.AddRange(empty)); Assert.Equal(a, a.AddRange(empty)); Assert.Equal(a, empty.AddRange(a)); Assert.True(a.AddRange(a).SequenceEqual(ImmutableArray.Create<int>(0, 2, 4, 0, 2, 4))); Assert.Equal(empty, empty.AddRange((IEnumerable<int>)empty)); Assert.Equal(a, a.AddRange((IEnumerable<int>)empty)); Assert.True(a.SequenceEqual(empty.AddRange((IEnumerable<int>)a))); Assert.True(a.AddRange((IEnumerable<int>)a).SequenceEqual(ImmutableArray.Create<int>(0, 2, 4, 0, 2, 4))); } [Fact] public void InsertRange() { var empty = ImmutableArray.Create<int>(); var a = ImmutableArray.Create<int>(0, 2, 4); Assert.Equal(empty, empty.InsertRange(0, empty)); Assert.Equal(a, a.InsertRange(0, empty)); Assert.Equal(a, a.InsertRange(2, empty)); Assert.True(a.SequenceEqual(empty.InsertRange(0, a))); Assert.True(a.InsertRange(2, a).SequenceEqual(ImmutableArray.Create<int>(0, 2, 0, 2, 4, 4))); } [Fact] public void ToDictionary() { var roa = new string[] { "one:1", "two:2", "three:3" }.AsImmutableOrNull(); // Call extension method directly to resolve the ambiguity with EnumerableExtensions.ToDictionary var dict = System.Linq.ImmutableArrayExtensions.ToDictionary(roa, s => s.Split(':').First()); Assert.Equal("one:1", dict["one"]); Assert.Equal("two:2", dict["two"]); Assert.Equal("three:3", dict["three"]); Assert.Throws<KeyNotFoundException>(() => dict["One"]); dict = System.Linq.ImmutableArrayExtensions.ToDictionary(roa, s => s.Split(':').First(), StringComparer.OrdinalIgnoreCase); Assert.Equal("one:1", dict["one"]); Assert.Equal("two:2", dict["Two"]); Assert.Equal("three:3", dict["THREE"]); Assert.Throws<KeyNotFoundException>(() => dict[""]); dict = System.Linq.ImmutableArrayExtensions.ToDictionary(roa, s => s.Split(':').First(), s => s.Split(':').Last()); Assert.Equal("1", dict["one"]); Assert.Equal("2", dict["two"]); Assert.Equal("3", dict["three"]); Assert.Throws<KeyNotFoundException>(() => dict["THREE"]); dict = System.Linq.ImmutableArrayExtensions.ToDictionary(roa, s => s.Split(':').First(), s => s.Split(':').Last(), StringComparer.OrdinalIgnoreCase); Assert.Equal("1", dict["onE"]); Assert.Equal("2", dict["Two"]); Assert.Equal("3", dict["three"]); Assert.Throws<KeyNotFoundException>(() => dict["four"]); } [Fact] public void SequenceEqual() { var a = ImmutableArray.Create<string>("A", "B", "C"); var b = ImmutableArray.Create<string>("A", "b", "c"); var c = ImmutableArray.Create<string>("A", "b"); Assert.False(a.SequenceEqual(b)); Assert.True(a.SequenceEqual(b, StringComparer.OrdinalIgnoreCase)); Assert.False(a.SequenceEqual(c)); Assert.False(a.SequenceEqual(c, StringComparer.OrdinalIgnoreCase)); Assert.False(c.SequenceEqual(a)); var r = ImmutableArray.Create<int>(1, 2, 3); Assert.True(r.SequenceEqual(Enumerable.Range(1, 3))); Assert.False(r.SequenceEqual(Enumerable.Range(1, 2))); Assert.False(r.SequenceEqual(Enumerable.Range(1, 4))); var s = ImmutableArray.Create<int>(10, 20, 30); Assert.True(r.SequenceEqual(s, (x, y) => 10 * x == y)); } [Fact] public void SelectAsArray() { var empty = ImmutableArray.Create<object>(); Assert.True(empty.SequenceEqual(empty.SelectAsArray(item => item))); Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, arg) => item, 1))); Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, arg) => arg, 2))); Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, index, arg) => item, 1))); Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, index, arg) => arg, 2))); Assert.True(empty.SequenceEqual(empty.SelectAsArray((item, index, arg) => index, 3))); var a = ImmutableArray.Create<int>(3, 2, 1, 0); var b = ImmutableArray.Create<int>(0, 1, 2, 3); var c = ImmutableArray.Create<int>(2, 2, 2, 2); Assert.True(a.SequenceEqual(a.SelectAsArray(item => item))); Assert.True(a.SequenceEqual(a.SelectAsArray((item, arg) => item, 1))); Assert.True(c.SequenceEqual(a.SelectAsArray((item, arg) => arg, 2))); Assert.True(a.SequenceEqual(a.SelectAsArray((item, index, arg) => item, 1))); Assert.True(c.SequenceEqual(a.SelectAsArray((item, index, arg) => arg, 2))); Assert.True(b.SequenceEqual(a.SelectAsArray((item, index, arg) => index, 3))); AssertEx.Equal(new[] { 10 }, ImmutableArray.Create(1).SelectAsArray(i => 10 * i)); AssertEx.Equal(new[] { 10, 20 }, ImmutableArray.Create(1, 2).SelectAsArray(i => 10 * i)); AssertEx.Equal(new[] { 10, 20, 30 }, ImmutableArray.Create(1, 2, 3).SelectAsArray(i => 10 * i)); AssertEx.Equal(new[] { 10, 20, 30, 40 }, ImmutableArray.Create(1, 2, 3, 4).SelectAsArray(i => 10 * i)); AssertEx.Equal(new[] { 10, 20, 30, 40, 50 }, ImmutableArray.Create(1, 2, 3, 4, 5).SelectAsArray(i => 10 * i)); } [Fact] public void SelectAsArrayWithPredicate() { Assert.Empty(ImmutableArray<object>.Empty.SelectAsArray<object, int>(item => throw null, item => throw null)); var array = ImmutableArray.Create(1, 2, 3, 4, 5); AssertEx.Equal(new[] { 2, 3, 4, 5, 6 }, array.SelectAsArray(item => true, item => item + 1)); AssertEx.Equal(new[] { 3, 5 }, array.SelectAsArray(item => item % 2 == 0, item => item + 1)); Assert.Empty(array.SelectAsArray<int, int>(item => item < 0, item => throw null)); } [Fact] public void ZipAsArray() { var empty = ImmutableArray.Create<object>(); Assert.True(empty.SequenceEqual(empty.ZipAsArray(empty, (item1, item2) => item1))); var single1 = ImmutableArray.Create(1); var single2 = ImmutableArray.Create(10); var single3 = ImmutableArray.Create(11); Assert.True(single3.SequenceEqual(single1.ZipAsArray(single2, (item1, item2) => item1 + item2))); var pair1 = ImmutableArray.Create(1, 2); var pair2 = ImmutableArray.Create(10, 11); var pair3 = ImmutableArray.Create(11, 13); Assert.True(pair3.SequenceEqual(pair1.ZipAsArray(pair2, (item1, item2) => item1 + item2))); var triple1 = ImmutableArray.Create(1, 2, 3); var triple2 = ImmutableArray.Create(10, 11, 12); var triple3 = ImmutableArray.Create(11, 13, 15); Assert.True(triple3.SequenceEqual(triple1.ZipAsArray(triple2, (item1, item2) => item1 + item2))); var quad1 = ImmutableArray.Create(1, 2, 3, 4); var quad2 = ImmutableArray.Create(10, 11, 12, 13); var quad3 = ImmutableArray.Create(11, 13, 15, 17); Assert.True(quad3.SequenceEqual(quad1.ZipAsArray(quad2, (item1, item2) => item1 + item2))); var quin1 = ImmutableArray.Create(1, 2, 3, 4, 5); var quin2 = ImmutableArray.Create(10, 11, 12, 13, 14); var quin3 = ImmutableArray.Create(11, 13, 15, 17, 19); Assert.True(quin3.SequenceEqual(quin1.ZipAsArray(quin2, (item1, item2) => item1 + item2))); } [Fact] public void ZipAsArrayWithIndex() { var empty = ImmutableArray.Create<object>(); Assert.True(empty.SequenceEqual(empty.ZipAsArray(empty, (item1, item2) => item1))); var single1 = ImmutableArray.Create(1); var single2 = ImmutableArray.Create(10); var single3 = ImmutableArray.Create(13); Assert.True(single3.SequenceEqual(single1.ZipAsArray(single2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg))); var pair1 = ImmutableArray.Create(1, 2); var pair2 = ImmutableArray.Create(10, 11); var pair3 = ImmutableArray.Create(13, 16); Assert.True(pair3.SequenceEqual(pair1.ZipAsArray(pair2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg))); var triple1 = ImmutableArray.Create(1, 2, 3); var triple2 = ImmutableArray.Create(10, 11, 12); var triple3 = ImmutableArray.Create(13, 16, 19); Assert.True(triple3.SequenceEqual(triple1.ZipAsArray(triple2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg))); var quad1 = ImmutableArray.Create(1, 2, 3, 4); var quad2 = ImmutableArray.Create(10, 11, 12, 13); var quad3 = ImmutableArray.Create(13, 16, 19, 22); Assert.True(quad3.SequenceEqual(quad1.ZipAsArray(quad2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg))); var quin1 = ImmutableArray.Create(1, 2, 3, 4, 5); var quin2 = ImmutableArray.Create(10, 11, 12, 13, 14); var quin3 = ImmutableArray.Create(13, 16, 19, 22, 25); Assert.True(quin3.SequenceEqual(quin1.ZipAsArray(quin2, 2, (item1, item2, i, arg) => item1 + item2 + i + arg))); } [Fact] public void WhereAsArray() { var empty = ImmutableArray.Create<object>(); // All. Assert.Equal(empty, empty.WhereAsArray(o => true)); // None. Assert.Equal(empty, empty.WhereAsArray(o => false)); var a = ImmutableArray.Create<int>(0, 1, 2, 3, 4, 5); // All. Assert.Equal(a, a.WhereAsArray(i => true)); // None. Assert.True(a.WhereAsArray(i => false).SequenceEqual(ImmutableArray.Create<int>())); // All but the first. Assert.True(a.WhereAsArray(i => i > 0).SequenceEqual(ImmutableArray.Create<int>(1, 2, 3, 4, 5))); // All but the last. Assert.True(a.WhereAsArray(i => i < 5).SequenceEqual(ImmutableArray.Create<int>(0, 1, 2, 3, 4))); // First only. Assert.True(a.WhereAsArray(i => i == 0).SequenceEqual(ImmutableArray.Create<int>(0))); // Last only. Assert.True(a.WhereAsArray(i => i == 5).SequenceEqual(ImmutableArray.Create<int>(5))); // First half. Assert.True(a.WhereAsArray(i => i < 3).SequenceEqual(ImmutableArray.Create<int>(0, 1, 2))); // Second half. Assert.True(a.WhereAsArray(i => i > 2).SequenceEqual(ImmutableArray.Create<int>(3, 4, 5))); // Even. Assert.True(a.WhereAsArray(i => i % 2 == 0).SequenceEqual(ImmutableArray.Create<int>(0, 2, 4))); // Odd. Assert.True(a.WhereAsArray(i => i % 2 == 1).SequenceEqual(ImmutableArray.Create<int>(1, 3, 5))); } [Fact] public void WhereAsArray_WithArg() { var x = new C(); Assert.Same(x, ImmutableArray.Create<object>(x).WhereAsArray((o, arg) => o == arg, x)[0]); var a = ImmutableArray.Create(0, 1, 2, 3, 4, 5); AssertEx.Equal(new[] { 3, 4, 5 }, a.WhereAsArray((i, j) => i > j, 2)); } private class C { } private class D : C { } [Fact] public void Casting() { var arrayOfD = new D[] { new D() }.AsImmutableOrNull(); var arrayOfC = arrayOfD.Cast<D, C>(); var arrayOfD2 = arrayOfC.As<D>(); // the underlying arrays are the same: //Assert.True(arrayOfD.Equals(arrayOfC)); Assert.True(arrayOfD2.Equals(arrayOfD)); // Trying to cast from base to derived. "As" should return null (default) Assert.True(new C[] { new C() }.AsImmutableOrNull().As<D>().IsDefault); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/CSharp/Test/Symbol/DocumentationComments/DocumentationModeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DocumentationModeTests : CSharpTestBase { [Fact] public void XmlSyntaxError_Inline() { var xml = @"<unclosed>"; var expectedText = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""T:Partial"" --> <!-- Badly formed XML comment ignored for member ""T:Parse"" --> <!-- Badly formed XML comment ignored for member ""T:Diagnose"" --> </members> </doc> ".Trim(); TestInline(xml, expectedText, // Diagnose.cs(4,1): warning CS1570: XML comment has badly formed XML -- 'Expected an end tag for element 'unclosed'.' // */ Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("unclosed"), // Diagnose.cs(9,1): warning CS1570: XML comment has badly formed XML -- 'Expected an end tag for element 'unclosed'.' // */ Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("unclosed")); } [ClrOnlyFact(ClrOnlyReason.DocumentationComment, Skip = "https://github.com/dotnet/roslyn/issues/8807")] public void XmlSyntaxError_Included() { var xml = @"<unclosed>"; var xpath = "*"; var expectedTextTemplate = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:Partial""> Parse: <!-- Badly formed XML file ""{0}"" cannot be included --> Diagnose: <!-- Badly formed XML file ""{0}"" cannot be included --> </member> <member name=""T:Parse""> <!-- Badly formed XML file ""{0}"" cannot be included --> </member> <member name=""T:Diagnose""> <!-- Badly formed XML file ""{0}"" cannot be included --> </member> </members> </doc> ".Trim(); // Diagnostics are from types Diagnose and Partial. TestIncluded(xml, xpath, expectedTextTemplate, /*fallbackToErrorCodeOnlyForNonEnglish*/ true, // ff1abe1df1d7.xml(1,11): warning CS1592: Badly formed XML in included comments file -- 'Unexpected end of file has occurred. The following elements are not closed: unclosed.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("Unexpected end of file has occurred. The following elements are not closed: unclosed."), // ff1abe1df1d7.xml(1,11): warning CS1592: Badly formed XML in included comments file -- 'Unexpected end of file has occurred. The following elements are not closed: unclosed.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("Unexpected end of file has occurred. The following elements are not closed: unclosed.")); } [Fact] public void CrefSyntaxError_Inline() { var xml = @"<see cref='#' />"; var expectedText = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:Partial""> Parse <see cref='!:#' /> Diagnose <see cref='!:#' /> </member> <member name=""T:Parse""> <see cref='!:#' /> </member> <member name=""T:Diagnose""> <see cref='!:#' /> </member> </members> </doc> ".Trim(); TestInline(xml, expectedText, // Diagnose.cs(3,12): warning CS1584: XML comment has syntactically incorrect cref attribute '#' // <see cref='#' /> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "#").WithArguments("#"), // Diagnose.cs(3,12): warning CS1658: Identifier expected. See also error CS1001. // <see cref='#' /> Diagnostic(ErrorCode.WRN_ErrorOverride, "#").WithArguments("Identifier expected", "1001"), // Diagnose.cs(3,12): warning CS1658: Unexpected character '#'. See also error CS1056. // <see cref='#' /> Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '#'", "1056"), // Diagnose.cs(9,12): warning CS1584: XML comment has syntactically incorrect cref attribute '#' // <see cref='#' /> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "#").WithArguments("#"), // Diagnose.cs(9,12): warning CS1658: Identifier expected. See also error CS1001. // <see cref='#' /> Diagnostic(ErrorCode.WRN_ErrorOverride, "#").WithArguments("Identifier expected", "1001"), // Diagnose.cs(9,12): warning CS1658: Unexpected character '#'. See also error CS1056. // <see cref='#' /> Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '#'", "1056")); } [Fact] public void CrefSyntaxError_Included() { var xml = @"<see cref='#' />"; var xpath = "see"; var expectedTextTemplate = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:Partial""> Parse: <see cref=""!:#"" /> Diagnose: <see cref=""!:#"" /> </member> <member name=""T:Parse""> <see cref=""!:#"" /> </member> <member name=""T:Diagnose""> <see cref=""!:#"" /> </member> </members> </doc> ".Trim(); TestIncluded(xml, xpath, expectedTextTemplate, includeElement => new[] { // ExpandIncludes.cs(2,5): warning CS1584: XML comment has syntactically incorrect cref attribute '#' // /// <include file='d6f61c210f5e.xml' path='see' /> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, includeElement).WithArguments("#"), // ExpandIncludes.cs(2,5): warning CS1658: Identifier expected. See also error CS1001. // /// <include file='d6f61c210f5e.xml' path='see' /> Diagnostic(ErrorCode.WRN_ErrorOverride, includeElement).WithArguments("Identifier expected", "1001"), // ExpandIncludes.cs(2,5): warning CS1658: Unexpected character '#'. See also error CS1056. // /// <include file='d6f61c210f5e.xml' path='see' /> Diagnostic(ErrorCode.WRN_ErrorOverride, includeElement).WithArguments("Unexpected character '#'", "1056"), // ExpandIncludes.cs(5,21): warning CS1584: XML comment has syntactically incorrect cref attribute '#' // /// ExpandIncludes: <include file='d6f61c210f5e.xml' path='see' /> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, includeElement).WithArguments("#"), // ExpandIncludes.cs(5,21): warning CS1658: Identifier expected. See also error CS1001. // /// ExpandIncludes: <include file='d6f61c210f5e.xml' path='see' /> Diagnostic(ErrorCode.WRN_ErrorOverride, includeElement).WithArguments("Identifier expected", "1001"), // ExpandIncludes.cs(5,21): warning CS1658: Unexpected character '#'. See also error CS1056. // /// ExpandIncludes: <include file='d6f61c210f5e.xml' path='see' /> Diagnostic(ErrorCode.WRN_ErrorOverride, includeElement).WithArguments("Unexpected character '#'", "1056") }); } [Fact] public void CrefSemanticError_Inline() { var xml = @"<see cref='NotFound' />"; var expectedText = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:Partial""> Parse <see cref='!:NotFound' /> Diagnose <see cref='!:NotFound' /> </member> <member name=""T:Parse""> <see cref='!:NotFound' /> </member> <member name=""T:Diagnose""> <see cref='!:NotFound' /> </member> </members> </doc> ".Trim(); TestInline(xml, expectedText, // Diagnose.cs(9,12): warning CS1574: XML comment has cref attribute 'NotFound' that could not be resolved // <see cref='NotFound' /> Diagnostic(ErrorCode.WRN_BadXMLRef, "NotFound").WithArguments("NotFound"), // ExpandIncludes.cs(9,12): warning CS1574: XML comment has cref attribute 'NotFound' that could not be resolved // <see cref='NotFound' /> Diagnostic(ErrorCode.WRN_BadXMLRef, "NotFound").WithArguments("NotFound")); } [Fact] public void CrefSemanticError_Included() { var xml = @"<see cref='NotFound' />"; var xpath = "see"; var expectedTextTemplate = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:Partial""> Parse: <see cref=""!:NotFound"" /> Diagnose: <see cref=""!:NotFound"" /> </member> <member name=""T:Parse""> <see cref=""!:NotFound"" /> </member> <member name=""T:Diagnose""> <see cref=""!:NotFound"" /> </member> </members> </doc> ".Trim(); TestIncluded(xml, xpath, expectedTextTemplate, includeElement => new[] { // ExpandIncludes.cs(2,5): warning CS1574: XML comment has cref attribute 'NotFound' that could not be resolved // /// <include file='5127bff2acf3.xml' path='see' /> Diagnostic(ErrorCode.WRN_BadXMLRef, includeElement).WithArguments("NotFound"), // ExpandIncludes.cs(5,21): warning CS1574: XML comment has cref attribute 'NotFound' that could not be resolved // /// ExpandIncludes: <include file='5127bff2acf3.xml' path='see' /> Diagnostic(ErrorCode.WRN_BadXMLRef, includeElement).WithArguments("NotFound") }); } [Fact] public void NameSemanticError_Inline() { var xml = @"<typeparam name='NotFound' />"; var expectedText = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:Partial""> Parse <typeparam name='NotFound' /> Diagnose <typeparam name='NotFound' /> </member> <member name=""T:Parse""> <typeparam name='NotFound' /> </member> <member name=""T:Diagnose""> <typeparam name='NotFound' /> </member> </members> </doc> ".Trim(); TestInline(xml, expectedText, // Diagnose.cs(3,18): warning CS1711: XML comment has a typeparam tag for 'NotFound', but there is no type parameter by that name // <typeparam name='NotFound' /> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "NotFound").WithArguments("NotFound"), // Diagnose.cs(9,18): warning CS1711: XML comment has a typeparam tag for 'NotFound', but there is no type parameter by that name // <typeparam name='NotFound' /> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "NotFound").WithArguments("NotFound")); } [Fact] public void NameSemanticError_Included() { var xml = @"<typeparam name='NotFound' />"; var xpath = "typeparam"; var expectedTextTemplate = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:Partial""> Parse: <typeparam name=""NotFound"" /> Diagnose: <typeparam name=""NotFound"" /> </member> <member name=""T:Parse""> <typeparam name=""NotFound"" /> </member> <member name=""T:Diagnose""> <typeparam name=""NotFound"" /> </member> </members> </doc> ".Trim(); TestIncluded(xml, xpath, expectedTextTemplate, includeElement => new[] { // ExpandIncludes.cs(5,21): warning CS1711: XML comment has a typeparam tag for 'NotFound', but there is no type parameter by that name // /// ExpandIncludes: <include file='3590e97bd224.xml' path='typeparam' /> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("NotFound"), // ExpandIncludes.cs(2,5): warning CS1711: XML comment has a typeparam tag for 'NotFound', but there is no type parameter by that name // /// <include file='3590e97bd224.xml' path='typeparam' /> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("NotFound") }); } private static void TestInline(string xml, string expectedText, params DiagnosticDescription[] expectedDiagnostics) { var sourceTemplate = @" /** {0} */ class {1} {{ }} /** {1} {0} */ partial class Partial {{ }} "; var trees = AllModes.Select(mode => Parse(string.Format(sourceTemplate, xml, mode), string.Format("{0}.cs", mode), GetOptions(mode))); var comp = CreateCompilation(trees.ToArray(), assemblyName: "Test"); comp.VerifyDiagnostics(expectedDiagnostics); var actualText = GetDocumentationCommentText(comp, expectedDiagnostics: null); Assert.Equal(expectedText, actualText); } private void TestIncluded(string xml, string xpath, string expectedTextTemplate, bool fallbackToErrorCodeOnlyForNonEnglish, params DiagnosticDescription[] expectedDiagnostics) { TestIncluded(xml, xpath, expectedTextTemplate, unused => expectedDiagnostics, fallbackToErrorCodeOnlyForNonEnglish); } private void TestIncluded(string xml, string xpath, string expectedTextTemplate, Func<string, DiagnosticDescription[]> makeExpectedDiagnostics, bool fallbackToErrorCodeOnlyForNonEnglish = false) { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var xmlFilePath = xmlFile.Path; string includeElement = string.Format(@"<include file='{0}' path='{1}' />", xmlFilePath, xpath); var sourceTemplate = @" /// {0} class {1} {{ }} /// {1}: {0} partial class Partial {{ }} "; var trees = AllModes.Select(mode => Parse(string.Format(sourceTemplate, includeElement, mode), string.Format("{0}.cs", mode), GetOptions(mode))); var comp = CreateCompilation( trees.ToArray(), options: TestOptions.ReleaseDll.WithXmlReferenceResolver(XmlFileResolver.Default), assemblyName: "Test"); comp.GetDiagnostics().Verify(fallbackToErrorCodeOnlyForNonEnglish: fallbackToErrorCodeOnlyForNonEnglish, expected: makeExpectedDiagnostics(includeElement)); var actualText = GetDocumentationCommentText(comp, expectedDiagnostics: null); var expectedText = string.Format(expectedTextTemplate, TestHelpers.AsXmlCommentText(xmlFilePath)); Assert.Equal(expectedText, actualText); } private static CSharpParseOptions GetOptions(DocumentationMode mode) { return TestOptions.Regular.WithDocumentationMode(mode); } private static IEnumerable<DocumentationMode> AllModes { get { var modes = Enumerable.Range((int)DocumentationMode.None, DocumentationMode.Diagnose - DocumentationMode.None + 1).Select(i => (DocumentationMode)i); AssertEx.All(modes, mode => mode.IsValid()); return modes; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DocumentationModeTests : CSharpTestBase { [Fact] public void XmlSyntaxError_Inline() { var xml = @"<unclosed>"; var expectedText = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <!-- Badly formed XML comment ignored for member ""T:Partial"" --> <!-- Badly formed XML comment ignored for member ""T:Parse"" --> <!-- Badly formed XML comment ignored for member ""T:Diagnose"" --> </members> </doc> ".Trim(); TestInline(xml, expectedText, // Diagnose.cs(4,1): warning CS1570: XML comment has badly formed XML -- 'Expected an end tag for element 'unclosed'.' // */ Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("unclosed"), // Diagnose.cs(9,1): warning CS1570: XML comment has badly formed XML -- 'Expected an end tag for element 'unclosed'.' // */ Diagnostic(ErrorCode.WRN_XMLParseError, "").WithArguments("unclosed")); } [ClrOnlyFact(ClrOnlyReason.DocumentationComment, Skip = "https://github.com/dotnet/roslyn/issues/8807")] public void XmlSyntaxError_Included() { var xml = @"<unclosed>"; var xpath = "*"; var expectedTextTemplate = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:Partial""> Parse: <!-- Badly formed XML file ""{0}"" cannot be included --> Diagnose: <!-- Badly formed XML file ""{0}"" cannot be included --> </member> <member name=""T:Parse""> <!-- Badly formed XML file ""{0}"" cannot be included --> </member> <member name=""T:Diagnose""> <!-- Badly formed XML file ""{0}"" cannot be included --> </member> </members> </doc> ".Trim(); // Diagnostics are from types Diagnose and Partial. TestIncluded(xml, xpath, expectedTextTemplate, /*fallbackToErrorCodeOnlyForNonEnglish*/ true, // ff1abe1df1d7.xml(1,11): warning CS1592: Badly formed XML in included comments file -- 'Unexpected end of file has occurred. The following elements are not closed: unclosed.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("Unexpected end of file has occurred. The following elements are not closed: unclosed."), // ff1abe1df1d7.xml(1,11): warning CS1592: Badly formed XML in included comments file -- 'Unexpected end of file has occurred. The following elements are not closed: unclosed.' Diagnostic(ErrorCode.WRN_XMLParseIncludeError).WithArguments("Unexpected end of file has occurred. The following elements are not closed: unclosed.")); } [Fact] public void CrefSyntaxError_Inline() { var xml = @"<see cref='#' />"; var expectedText = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:Partial""> Parse <see cref='!:#' /> Diagnose <see cref='!:#' /> </member> <member name=""T:Parse""> <see cref='!:#' /> </member> <member name=""T:Diagnose""> <see cref='!:#' /> </member> </members> </doc> ".Trim(); TestInline(xml, expectedText, // Diagnose.cs(3,12): warning CS1584: XML comment has syntactically incorrect cref attribute '#' // <see cref='#' /> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "#").WithArguments("#"), // Diagnose.cs(3,12): warning CS1658: Identifier expected. See also error CS1001. // <see cref='#' /> Diagnostic(ErrorCode.WRN_ErrorOverride, "#").WithArguments("Identifier expected", "1001"), // Diagnose.cs(3,12): warning CS1658: Unexpected character '#'. See also error CS1056. // <see cref='#' /> Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '#'", "1056"), // Diagnose.cs(9,12): warning CS1584: XML comment has syntactically incorrect cref attribute '#' // <see cref='#' /> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, "#").WithArguments("#"), // Diagnose.cs(9,12): warning CS1658: Identifier expected. See also error CS1001. // <see cref='#' /> Diagnostic(ErrorCode.WRN_ErrorOverride, "#").WithArguments("Identifier expected", "1001"), // Diagnose.cs(9,12): warning CS1658: Unexpected character '#'. See also error CS1056. // <see cref='#' /> Diagnostic(ErrorCode.WRN_ErrorOverride, "").WithArguments("Unexpected character '#'", "1056")); } [Fact] public void CrefSyntaxError_Included() { var xml = @"<see cref='#' />"; var xpath = "see"; var expectedTextTemplate = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:Partial""> Parse: <see cref=""!:#"" /> Diagnose: <see cref=""!:#"" /> </member> <member name=""T:Parse""> <see cref=""!:#"" /> </member> <member name=""T:Diagnose""> <see cref=""!:#"" /> </member> </members> </doc> ".Trim(); TestIncluded(xml, xpath, expectedTextTemplate, includeElement => new[] { // ExpandIncludes.cs(2,5): warning CS1584: XML comment has syntactically incorrect cref attribute '#' // /// <include file='d6f61c210f5e.xml' path='see' /> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, includeElement).WithArguments("#"), // ExpandIncludes.cs(2,5): warning CS1658: Identifier expected. See also error CS1001. // /// <include file='d6f61c210f5e.xml' path='see' /> Diagnostic(ErrorCode.WRN_ErrorOverride, includeElement).WithArguments("Identifier expected", "1001"), // ExpandIncludes.cs(2,5): warning CS1658: Unexpected character '#'. See also error CS1056. // /// <include file='d6f61c210f5e.xml' path='see' /> Diagnostic(ErrorCode.WRN_ErrorOverride, includeElement).WithArguments("Unexpected character '#'", "1056"), // ExpandIncludes.cs(5,21): warning CS1584: XML comment has syntactically incorrect cref attribute '#' // /// ExpandIncludes: <include file='d6f61c210f5e.xml' path='see' /> Diagnostic(ErrorCode.WRN_BadXMLRefSyntax, includeElement).WithArguments("#"), // ExpandIncludes.cs(5,21): warning CS1658: Identifier expected. See also error CS1001. // /// ExpandIncludes: <include file='d6f61c210f5e.xml' path='see' /> Diagnostic(ErrorCode.WRN_ErrorOverride, includeElement).WithArguments("Identifier expected", "1001"), // ExpandIncludes.cs(5,21): warning CS1658: Unexpected character '#'. See also error CS1056. // /// ExpandIncludes: <include file='d6f61c210f5e.xml' path='see' /> Diagnostic(ErrorCode.WRN_ErrorOverride, includeElement).WithArguments("Unexpected character '#'", "1056") }); } [Fact] public void CrefSemanticError_Inline() { var xml = @"<see cref='NotFound' />"; var expectedText = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:Partial""> Parse <see cref='!:NotFound' /> Diagnose <see cref='!:NotFound' /> </member> <member name=""T:Parse""> <see cref='!:NotFound' /> </member> <member name=""T:Diagnose""> <see cref='!:NotFound' /> </member> </members> </doc> ".Trim(); TestInline(xml, expectedText, // Diagnose.cs(9,12): warning CS1574: XML comment has cref attribute 'NotFound' that could not be resolved // <see cref='NotFound' /> Diagnostic(ErrorCode.WRN_BadXMLRef, "NotFound").WithArguments("NotFound"), // ExpandIncludes.cs(9,12): warning CS1574: XML comment has cref attribute 'NotFound' that could not be resolved // <see cref='NotFound' /> Diagnostic(ErrorCode.WRN_BadXMLRef, "NotFound").WithArguments("NotFound")); } [Fact] public void CrefSemanticError_Included() { var xml = @"<see cref='NotFound' />"; var xpath = "see"; var expectedTextTemplate = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:Partial""> Parse: <see cref=""!:NotFound"" /> Diagnose: <see cref=""!:NotFound"" /> </member> <member name=""T:Parse""> <see cref=""!:NotFound"" /> </member> <member name=""T:Diagnose""> <see cref=""!:NotFound"" /> </member> </members> </doc> ".Trim(); TestIncluded(xml, xpath, expectedTextTemplate, includeElement => new[] { // ExpandIncludes.cs(2,5): warning CS1574: XML comment has cref attribute 'NotFound' that could not be resolved // /// <include file='5127bff2acf3.xml' path='see' /> Diagnostic(ErrorCode.WRN_BadXMLRef, includeElement).WithArguments("NotFound"), // ExpandIncludes.cs(5,21): warning CS1574: XML comment has cref attribute 'NotFound' that could not be resolved // /// ExpandIncludes: <include file='5127bff2acf3.xml' path='see' /> Diagnostic(ErrorCode.WRN_BadXMLRef, includeElement).WithArguments("NotFound") }); } [Fact] public void NameSemanticError_Inline() { var xml = @"<typeparam name='NotFound' />"; var expectedText = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:Partial""> Parse <typeparam name='NotFound' /> Diagnose <typeparam name='NotFound' /> </member> <member name=""T:Parse""> <typeparam name='NotFound' /> </member> <member name=""T:Diagnose""> <typeparam name='NotFound' /> </member> </members> </doc> ".Trim(); TestInline(xml, expectedText, // Diagnose.cs(3,18): warning CS1711: XML comment has a typeparam tag for 'NotFound', but there is no type parameter by that name // <typeparam name='NotFound' /> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "NotFound").WithArguments("NotFound"), // Diagnose.cs(9,18): warning CS1711: XML comment has a typeparam tag for 'NotFound', but there is no type parameter by that name // <typeparam name='NotFound' /> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, "NotFound").WithArguments("NotFound")); } [Fact] public void NameSemanticError_Included() { var xml = @"<typeparam name='NotFound' />"; var xpath = "typeparam"; var expectedTextTemplate = @" <?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:Partial""> Parse: <typeparam name=""NotFound"" /> Diagnose: <typeparam name=""NotFound"" /> </member> <member name=""T:Parse""> <typeparam name=""NotFound"" /> </member> <member name=""T:Diagnose""> <typeparam name=""NotFound"" /> </member> </members> </doc> ".Trim(); TestIncluded(xml, xpath, expectedTextTemplate, includeElement => new[] { // ExpandIncludes.cs(5,21): warning CS1711: XML comment has a typeparam tag for 'NotFound', but there is no type parameter by that name // /// ExpandIncludes: <include file='3590e97bd224.xml' path='typeparam' /> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("NotFound"), // ExpandIncludes.cs(2,5): warning CS1711: XML comment has a typeparam tag for 'NotFound', but there is no type parameter by that name // /// <include file='3590e97bd224.xml' path='typeparam' /> Diagnostic(ErrorCode.WRN_UnmatchedTypeParamTag, includeElement).WithArguments("NotFound") }); } private static void TestInline(string xml, string expectedText, params DiagnosticDescription[] expectedDiagnostics) { var sourceTemplate = @" /** {0} */ class {1} {{ }} /** {1} {0} */ partial class Partial {{ }} "; var trees = AllModes.Select(mode => Parse(string.Format(sourceTemplate, xml, mode), string.Format("{0}.cs", mode), GetOptions(mode))); var comp = CreateCompilation(trees.ToArray(), assemblyName: "Test"); comp.VerifyDiagnostics(expectedDiagnostics); var actualText = GetDocumentationCommentText(comp, expectedDiagnostics: null); Assert.Equal(expectedText, actualText); } private void TestIncluded(string xml, string xpath, string expectedTextTemplate, bool fallbackToErrorCodeOnlyForNonEnglish, params DiagnosticDescription[] expectedDiagnostics) { TestIncluded(xml, xpath, expectedTextTemplate, unused => expectedDiagnostics, fallbackToErrorCodeOnlyForNonEnglish); } private void TestIncluded(string xml, string xpath, string expectedTextTemplate, Func<string, DiagnosticDescription[]> makeExpectedDiagnostics, bool fallbackToErrorCodeOnlyForNonEnglish = false) { var xmlFile = Temp.CreateFile(extension: ".xml").WriteAllText(xml); var xmlFilePath = xmlFile.Path; string includeElement = string.Format(@"<include file='{0}' path='{1}' />", xmlFilePath, xpath); var sourceTemplate = @" /// {0} class {1} {{ }} /// {1}: {0} partial class Partial {{ }} "; var trees = AllModes.Select(mode => Parse(string.Format(sourceTemplate, includeElement, mode), string.Format("{0}.cs", mode), GetOptions(mode))); var comp = CreateCompilation( trees.ToArray(), options: TestOptions.ReleaseDll.WithXmlReferenceResolver(XmlFileResolver.Default), assemblyName: "Test"); comp.GetDiagnostics().Verify(fallbackToErrorCodeOnlyForNonEnglish: fallbackToErrorCodeOnlyForNonEnglish, expected: makeExpectedDiagnostics(includeElement)); var actualText = GetDocumentationCommentText(comp, expectedDiagnostics: null); var expectedText = string.Format(expectedTextTemplate, TestHelpers.AsXmlCommentText(xmlFilePath)); Assert.Equal(expectedText, actualText); } private static CSharpParseOptions GetOptions(DocumentationMode mode) { return TestOptions.Regular.WithDocumentationMode(mode); } private static IEnumerable<DocumentationMode> AllModes { get { var modes = Enumerable.Range((int)DocumentationMode.None, DocumentationMode.Diagnose - DocumentationMode.None + 1).Select(i => (DocumentationMode)i); AssertEx.All(modes, mode => mode.IsValid()); return modes; } } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Rename/Annotations/RenameTokenSimplificationAnnotation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Text; namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { internal class RenameTokenSimplificationAnnotation : RenameAnnotation { public TextSpan OriginalTextSpan { 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 Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Rename.ConflictEngine { internal class RenameTokenSimplificationAnnotation : RenameAnnotation { public TextSpan OriginalTextSpan { get; set; } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/Core/Portable/ReferenceManager/AssemblyData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis { internal partial class CommonReferenceManager<TCompilation, TAssemblySymbol> { /// <summary> /// Information about an assembly, used as an input for the Binder class. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal abstract class AssemblyData { /// <summary> /// Identity of the assembly. /// </summary> public abstract AssemblyIdentity Identity { get; } /// <summary> /// Identity of assemblies referenced by this assembly. /// References should always be returned in the same order. /// </summary> public abstract ImmutableArray<AssemblyIdentity> AssemblyReferences { get; } /// <summary> /// The sequence of AssemblySymbols the Binder can choose from. /// </summary> public abstract IEnumerable<TAssemblySymbol> AvailableSymbols { get; } /// <summary> /// Check if provided AssemblySymbol is created for assembly described by this instance. /// This method is expected to return true for every AssemblySymbol returned by /// AvailableSymbols property. /// </summary> /// <param name="assembly"> /// The AssemblySymbol to check. /// </param> /// <returns>Boolean.</returns> public abstract bool IsMatchingAssembly(TAssemblySymbol? assembly); /// <summary> /// Resolve assembly references against assemblies described by provided AssemblyData objects. /// In other words, match assembly identities returned by AssemblyReferences property against /// assemblies described by provided AssemblyData objects. /// </summary> /// <param name="assemblies">An array of AssemblyData objects to match against.</param> /// <param name="assemblyIdentityComparer">Used to compare assembly identities.</param> /// <returns> /// For each assembly referenced by this assembly (<see cref="AssemblyReferences"/>) /// a description of how it binds to one of the input assemblies. /// </returns> public abstract AssemblyReferenceBinding[] BindAssemblyReferences(ImmutableArray<AssemblyData> assemblies, AssemblyIdentityComparer assemblyIdentityComparer); public abstract bool ContainsNoPiaLocalTypes { get; } public abstract bool IsLinked { get; } public abstract bool DeclaresTheObjectClass { get; } /// <summary> /// Get the source compilation backing this assembly, if one exists. /// Returns null otherwise. /// </summary> public abstract Compilation? SourceCompilation { get; } private string GetDebuggerDisplay() => $"{GetType().Name}: [{Identity.GetDisplayName()}]"; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis { internal partial class CommonReferenceManager<TCompilation, TAssemblySymbol> { /// <summary> /// Information about an assembly, used as an input for the Binder class. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal abstract class AssemblyData { /// <summary> /// Identity of the assembly. /// </summary> public abstract AssemblyIdentity Identity { get; } /// <summary> /// Identity of assemblies referenced by this assembly. /// References should always be returned in the same order. /// </summary> public abstract ImmutableArray<AssemblyIdentity> AssemblyReferences { get; } /// <summary> /// The sequence of AssemblySymbols the Binder can choose from. /// </summary> public abstract IEnumerable<TAssemblySymbol> AvailableSymbols { get; } /// <summary> /// Check if provided AssemblySymbol is created for assembly described by this instance. /// This method is expected to return true for every AssemblySymbol returned by /// AvailableSymbols property. /// </summary> /// <param name="assembly"> /// The AssemblySymbol to check. /// </param> /// <returns>Boolean.</returns> public abstract bool IsMatchingAssembly(TAssemblySymbol? assembly); /// <summary> /// Resolve assembly references against assemblies described by provided AssemblyData objects. /// In other words, match assembly identities returned by AssemblyReferences property against /// assemblies described by provided AssemblyData objects. /// </summary> /// <param name="assemblies">An array of AssemblyData objects to match against.</param> /// <param name="assemblyIdentityComparer">Used to compare assembly identities.</param> /// <returns> /// For each assembly referenced by this assembly (<see cref="AssemblyReferences"/>) /// a description of how it binds to one of the input assemblies. /// </returns> public abstract AssemblyReferenceBinding[] BindAssemblyReferences(ImmutableArray<AssemblyData> assemblies, AssemblyIdentityComparer assemblyIdentityComparer); public abstract bool ContainsNoPiaLocalTypes { get; } public abstract bool IsLinked { get; } public abstract bool DeclaresTheObjectClass { get; } /// <summary> /// Get the source compilation backing this assembly, if one exists. /// Returns null otherwise. /// </summary> public abstract Compilation? SourceCompilation { get; } private string GetDebuggerDisplay() => $"{GetType().Name}: [{Identity.GetDisplayName()}]"; } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Features/Core/Portable/Completion/CompletionItemRules.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Completion { public enum CompletionItemSelectionBehavior { Default, /// <summary> /// If no text has been typed, the item should be soft selected. This is appropriate for /// completion providers that want to provide suggestions that shouldn't interfere with /// typing. For example a provider that comes up on space might offer items that are soft /// selected so that an additional space (or other puntuation character) will not then /// commit that item. /// </summary> SoftSelection, /// <summary> /// If no text has been typed, the item should be hard selected. This is appropriate for /// completion providers that are providing suggestions the user is nearly certain to /// select. Because the item is hard selected, any commit characters typed after it will /// cause it to be committed. /// </summary> HardSelection, } /// <summary> /// Rules for how the individual items are handled. /// </summary> public sealed class CompletionItemRules { /// <summary> /// The rule used when no rule is specified when constructing a <see cref="CompletionItem"/>. /// </summary> public static CompletionItemRules Default = new( filterCharacterRules: default, commitCharacterRules: default, enterKeyRule: EnterKeyRule.Default, formatOnCommit: false, matchPriority: Completion.MatchPriority.Default, selectionBehavior: CompletionItemSelectionBehavior.Default); /// <summary> /// Rules that modify the set of characters that can be typed to filter the list of completion items. /// </summary> public ImmutableArray<CharacterSetModificationRule> FilterCharacterRules { get; } /// <summary> /// Rules that modify the set of characters that can be typed to cause the selected item to be committed. /// </summary> public ImmutableArray<CharacterSetModificationRule> CommitCharacterRules { get; } /// <summary> /// A rule about whether the enter key is passed through to the editor after the selected item has been committed. /// </summary> public EnterKeyRule EnterKeyRule { get; } /// <summary> /// True if the modified text should be formatted automatically. /// </summary> public bool FormatOnCommit { get; } /// <summary> /// True if the related completion item should be initially selected. /// </summary> public int MatchPriority { get; } /// <summary> /// How this item should be selected when the completion list first appears and /// before the user has typed any characters. /// </summary> public CompletionItemSelectionBehavior SelectionBehavior { get; } private CompletionItemRules( ImmutableArray<CharacterSetModificationRule> filterCharacterRules, ImmutableArray<CharacterSetModificationRule> commitCharacterRules, EnterKeyRule enterKeyRule, bool formatOnCommit, int matchPriority, CompletionItemSelectionBehavior selectionBehavior) { FilterCharacterRules = filterCharacterRules.NullToEmpty(); CommitCharacterRules = commitCharacterRules.NullToEmpty(); EnterKeyRule = enterKeyRule; FormatOnCommit = formatOnCommit; MatchPriority = matchPriority; SelectionBehavior = selectionBehavior; } /// <summary> /// Creates a new <see cref="CompletionItemRules"/> instance. /// </summary> /// <param name="filterCharacterRules">Rules about which keys typed are used to filter the list of completion items.</param> /// <param name="commitCharacterRules">Rules about which keys typed caused the completion item to be committed.</param> /// <param name="enterKeyRule">Rule about whether the enter key is passed through to the editor after the selected item has been committed.</param> /// <param name="formatOnCommit">True if the modified text should be formatted automatically.</param> /// <param name="matchPriority">True if the related completion item should be initially selected.</param> /// <returns></returns> public static CompletionItemRules Create( ImmutableArray<CharacterSetModificationRule> filterCharacterRules, ImmutableArray<CharacterSetModificationRule> commitCharacterRules, EnterKeyRule enterKeyRule, bool formatOnCommit, int? matchPriority) { return Create( filterCharacterRules, commitCharacterRules, enterKeyRule, formatOnCommit, matchPriority, selectionBehavior: CompletionItemSelectionBehavior.Default); } /// <summary> /// Creates a new <see cref="CompletionItemRules"/> instance. /// </summary> /// <param name="filterCharacterRules">Rules about which keys typed are used to filter the list of completion items.</param> /// <param name="commitCharacterRules">Rules about which keys typed caused the completion item to be committed.</param> /// <param name="enterKeyRule">Rule about whether the enter key is passed through to the editor after the selected item has been committed.</param> /// <param name="formatOnCommit">True if the modified text should be formatted automatically.</param> /// <param name="matchPriority">True if the related completion item should be initially selected.</param> /// <param name="selectionBehavior">How this item should be selected if no text has been typed after the completion list is brought up.</param> /// <returns></returns> public static CompletionItemRules Create( ImmutableArray<CharacterSetModificationRule> filterCharacterRules = default, ImmutableArray<CharacterSetModificationRule> commitCharacterRules = default, EnterKeyRule enterKeyRule = EnterKeyRule.Default, bool formatOnCommit = false, int? matchPriority = null, CompletionItemSelectionBehavior selectionBehavior = CompletionItemSelectionBehavior.Default) { if (filterCharacterRules.IsDefaultOrEmpty && commitCharacterRules.IsDefaultOrEmpty && enterKeyRule == Default.EnterKeyRule && formatOnCommit == Default.FormatOnCommit && matchPriority.GetValueOrDefault() == Default.MatchPriority && selectionBehavior == Default.SelectionBehavior) { return Default; } else { return new CompletionItemRules( filterCharacterRules, commitCharacterRules, enterKeyRule, formatOnCommit, matchPriority.GetValueOrDefault(), selectionBehavior); } } /// <summary> /// Creates a new <see cref="CompletionItemRules"/> instance--internal for TypeScript. /// </summary> /// <param name="filterCharacterRules">Rules about which keys typed are used to filter the list of completion items.</param> /// <param name="commitCharacterRules">Rules about which keys typed caused the completion item to be committed.</param> /// <param name="enterKeyRule">Rule about whether the enter key is passed through to the editor after the selected item has been committed.</param> /// <param name="formatOnCommit">True if the modified text should be formatted automatically.</param> /// <param name="preselect">True if the related completion item should be initially selected.</param> /// <returns></returns> internal static CompletionItemRules Create( ImmutableArray<CharacterSetModificationRule> filterCharacterRules, ImmutableArray<CharacterSetModificationRule> commitCharacterRules, EnterKeyRule enterKeyRule, bool formatOnCommit, bool preselect) { var matchPriority = preselect ? Completion.MatchPriority.Preselect : Completion.MatchPriority.Default; return CompletionItemRules.Create(filterCharacterRules, commitCharacterRules, enterKeyRule, formatOnCommit, matchPriority); } private CompletionItemRules With( Optional<ImmutableArray<CharacterSetModificationRule>> filterRules = default, Optional<ImmutableArray<CharacterSetModificationRule>> commitRules = default, Optional<EnterKeyRule> enterKeyRule = default, Optional<bool> formatOnCommit = default, Optional<int> matchPriority = default, Optional<CompletionItemSelectionBehavior> selectionBehavior = default) { var newFilterRules = filterRules.HasValue ? filterRules.Value : FilterCharacterRules; var newCommitRules = commitRules.HasValue ? commitRules.Value : CommitCharacterRules; var newEnterKeyRule = enterKeyRule.HasValue ? enterKeyRule.Value : EnterKeyRule; var newFormatOnCommit = formatOnCommit.HasValue ? formatOnCommit.Value : FormatOnCommit; var newMatchPriority = matchPriority.HasValue ? matchPriority.Value : MatchPriority; var newSelectionBehavior = selectionBehavior.HasValue ? selectionBehavior.Value : SelectionBehavior; if (newFilterRules == FilterCharacterRules && newCommitRules == CommitCharacterRules && newEnterKeyRule == EnterKeyRule && newFormatOnCommit == FormatOnCommit && newMatchPriority == MatchPriority && newSelectionBehavior == SelectionBehavior) { return this; } else { return Create( newFilterRules, newCommitRules, newEnterKeyRule, newFormatOnCommit, newMatchPriority, newSelectionBehavior); } } /// <summary> /// Creates a copy of this <see cref="CompletionItemRules"/> with the <see cref="FilterCharacterRules"/> property changed. /// </summary> public CompletionItemRules WithFilterCharacterRules(ImmutableArray<CharacterSetModificationRule> filterCharacterRules) => With(filterRules: filterCharacterRules); internal CompletionItemRules WithFilterCharacterRule(CharacterSetModificationRule rule) => With(filterRules: ImmutableArray.Create(rule)); internal CompletionItemRules WithCommitCharacterRule(CharacterSetModificationRule rule) => With(commitRules: ImmutableArray.Create(rule)); /// <summary> /// Creates a copy of this <see cref="CompletionItemRules"/> with the <see cref="CommitCharacterRules"/> property changed. /// </summary> public CompletionItemRules WithCommitCharacterRules(ImmutableArray<CharacterSetModificationRule> commitCharacterRules) => With(commitRules: commitCharacterRules); /// <summary> /// Creates a copy of this <see cref="CompletionItemRules"/> with the <see cref="EnterKeyRule"/> property changed. /// </summary> public CompletionItemRules WithEnterKeyRule(EnterKeyRule enterKeyRule) => With(enterKeyRule: enterKeyRule); /// <summary> /// Creates a copy of this <see cref="CompletionItemRules"/> with the <see cref="FormatOnCommit"/> property changed. /// </summary> public CompletionItemRules WithFormatOnCommit(bool formatOnCommit) => With(formatOnCommit: formatOnCommit); /// <summary> /// Creates a copy of this <see cref="CompletionItemRules"/> with the <see cref="MatchPriority"/> property changed. /// </summary> public CompletionItemRules WithMatchPriority(int matchPriority) => With(matchPriority: matchPriority); /// <summary> /// Creates a copy of this <see cref="CompletionItemRules"/> with the <see cref="SelectionBehavior"/> property changed. /// </summary> public CompletionItemRules WithSelectionBehavior(CompletionItemSelectionBehavior selectionBehavior) => With(selectionBehavior: selectionBehavior); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.Completion { public enum CompletionItemSelectionBehavior { Default, /// <summary> /// If no text has been typed, the item should be soft selected. This is appropriate for /// completion providers that want to provide suggestions that shouldn't interfere with /// typing. For example a provider that comes up on space might offer items that are soft /// selected so that an additional space (or other puntuation character) will not then /// commit that item. /// </summary> SoftSelection, /// <summary> /// If no text has been typed, the item should be hard selected. This is appropriate for /// completion providers that are providing suggestions the user is nearly certain to /// select. Because the item is hard selected, any commit characters typed after it will /// cause it to be committed. /// </summary> HardSelection, } /// <summary> /// Rules for how the individual items are handled. /// </summary> public sealed class CompletionItemRules { /// <summary> /// The rule used when no rule is specified when constructing a <see cref="CompletionItem"/>. /// </summary> public static CompletionItemRules Default = new( filterCharacterRules: default, commitCharacterRules: default, enterKeyRule: EnterKeyRule.Default, formatOnCommit: false, matchPriority: Completion.MatchPriority.Default, selectionBehavior: CompletionItemSelectionBehavior.Default); /// <summary> /// Rules that modify the set of characters that can be typed to filter the list of completion items. /// </summary> public ImmutableArray<CharacterSetModificationRule> FilterCharacterRules { get; } /// <summary> /// Rules that modify the set of characters that can be typed to cause the selected item to be committed. /// </summary> public ImmutableArray<CharacterSetModificationRule> CommitCharacterRules { get; } /// <summary> /// A rule about whether the enter key is passed through to the editor after the selected item has been committed. /// </summary> public EnterKeyRule EnterKeyRule { get; } /// <summary> /// True if the modified text should be formatted automatically. /// </summary> public bool FormatOnCommit { get; } /// <summary> /// True if the related completion item should be initially selected. /// </summary> public int MatchPriority { get; } /// <summary> /// How this item should be selected when the completion list first appears and /// before the user has typed any characters. /// </summary> public CompletionItemSelectionBehavior SelectionBehavior { get; } private CompletionItemRules( ImmutableArray<CharacterSetModificationRule> filterCharacterRules, ImmutableArray<CharacterSetModificationRule> commitCharacterRules, EnterKeyRule enterKeyRule, bool formatOnCommit, int matchPriority, CompletionItemSelectionBehavior selectionBehavior) { FilterCharacterRules = filterCharacterRules.NullToEmpty(); CommitCharacterRules = commitCharacterRules.NullToEmpty(); EnterKeyRule = enterKeyRule; FormatOnCommit = formatOnCommit; MatchPriority = matchPriority; SelectionBehavior = selectionBehavior; } /// <summary> /// Creates a new <see cref="CompletionItemRules"/> instance. /// </summary> /// <param name="filterCharacterRules">Rules about which keys typed are used to filter the list of completion items.</param> /// <param name="commitCharacterRules">Rules about which keys typed caused the completion item to be committed.</param> /// <param name="enterKeyRule">Rule about whether the enter key is passed through to the editor after the selected item has been committed.</param> /// <param name="formatOnCommit">True if the modified text should be formatted automatically.</param> /// <param name="matchPriority">True if the related completion item should be initially selected.</param> /// <returns></returns> public static CompletionItemRules Create( ImmutableArray<CharacterSetModificationRule> filterCharacterRules, ImmutableArray<CharacterSetModificationRule> commitCharacterRules, EnterKeyRule enterKeyRule, bool formatOnCommit, int? matchPriority) { return Create( filterCharacterRules, commitCharacterRules, enterKeyRule, formatOnCommit, matchPriority, selectionBehavior: CompletionItemSelectionBehavior.Default); } /// <summary> /// Creates a new <see cref="CompletionItemRules"/> instance. /// </summary> /// <param name="filterCharacterRules">Rules about which keys typed are used to filter the list of completion items.</param> /// <param name="commitCharacterRules">Rules about which keys typed caused the completion item to be committed.</param> /// <param name="enterKeyRule">Rule about whether the enter key is passed through to the editor after the selected item has been committed.</param> /// <param name="formatOnCommit">True if the modified text should be formatted automatically.</param> /// <param name="matchPriority">True if the related completion item should be initially selected.</param> /// <param name="selectionBehavior">How this item should be selected if no text has been typed after the completion list is brought up.</param> /// <returns></returns> public static CompletionItemRules Create( ImmutableArray<CharacterSetModificationRule> filterCharacterRules = default, ImmutableArray<CharacterSetModificationRule> commitCharacterRules = default, EnterKeyRule enterKeyRule = EnterKeyRule.Default, bool formatOnCommit = false, int? matchPriority = null, CompletionItemSelectionBehavior selectionBehavior = CompletionItemSelectionBehavior.Default) { if (filterCharacterRules.IsDefaultOrEmpty && commitCharacterRules.IsDefaultOrEmpty && enterKeyRule == Default.EnterKeyRule && formatOnCommit == Default.FormatOnCommit && matchPriority.GetValueOrDefault() == Default.MatchPriority && selectionBehavior == Default.SelectionBehavior) { return Default; } else { return new CompletionItemRules( filterCharacterRules, commitCharacterRules, enterKeyRule, formatOnCommit, matchPriority.GetValueOrDefault(), selectionBehavior); } } /// <summary> /// Creates a new <see cref="CompletionItemRules"/> instance--internal for TypeScript. /// </summary> /// <param name="filterCharacterRules">Rules about which keys typed are used to filter the list of completion items.</param> /// <param name="commitCharacterRules">Rules about which keys typed caused the completion item to be committed.</param> /// <param name="enterKeyRule">Rule about whether the enter key is passed through to the editor after the selected item has been committed.</param> /// <param name="formatOnCommit">True if the modified text should be formatted automatically.</param> /// <param name="preselect">True if the related completion item should be initially selected.</param> /// <returns></returns> internal static CompletionItemRules Create( ImmutableArray<CharacterSetModificationRule> filterCharacterRules, ImmutableArray<CharacterSetModificationRule> commitCharacterRules, EnterKeyRule enterKeyRule, bool formatOnCommit, bool preselect) { var matchPriority = preselect ? Completion.MatchPriority.Preselect : Completion.MatchPriority.Default; return CompletionItemRules.Create(filterCharacterRules, commitCharacterRules, enterKeyRule, formatOnCommit, matchPriority); } private CompletionItemRules With( Optional<ImmutableArray<CharacterSetModificationRule>> filterRules = default, Optional<ImmutableArray<CharacterSetModificationRule>> commitRules = default, Optional<EnterKeyRule> enterKeyRule = default, Optional<bool> formatOnCommit = default, Optional<int> matchPriority = default, Optional<CompletionItemSelectionBehavior> selectionBehavior = default) { var newFilterRules = filterRules.HasValue ? filterRules.Value : FilterCharacterRules; var newCommitRules = commitRules.HasValue ? commitRules.Value : CommitCharacterRules; var newEnterKeyRule = enterKeyRule.HasValue ? enterKeyRule.Value : EnterKeyRule; var newFormatOnCommit = formatOnCommit.HasValue ? formatOnCommit.Value : FormatOnCommit; var newMatchPriority = matchPriority.HasValue ? matchPriority.Value : MatchPriority; var newSelectionBehavior = selectionBehavior.HasValue ? selectionBehavior.Value : SelectionBehavior; if (newFilterRules == FilterCharacterRules && newCommitRules == CommitCharacterRules && newEnterKeyRule == EnterKeyRule && newFormatOnCommit == FormatOnCommit && newMatchPriority == MatchPriority && newSelectionBehavior == SelectionBehavior) { return this; } else { return Create( newFilterRules, newCommitRules, newEnterKeyRule, newFormatOnCommit, newMatchPriority, newSelectionBehavior); } } /// <summary> /// Creates a copy of this <see cref="CompletionItemRules"/> with the <see cref="FilterCharacterRules"/> property changed. /// </summary> public CompletionItemRules WithFilterCharacterRules(ImmutableArray<CharacterSetModificationRule> filterCharacterRules) => With(filterRules: filterCharacterRules); internal CompletionItemRules WithFilterCharacterRule(CharacterSetModificationRule rule) => With(filterRules: ImmutableArray.Create(rule)); internal CompletionItemRules WithCommitCharacterRule(CharacterSetModificationRule rule) => With(commitRules: ImmutableArray.Create(rule)); /// <summary> /// Creates a copy of this <see cref="CompletionItemRules"/> with the <see cref="CommitCharacterRules"/> property changed. /// </summary> public CompletionItemRules WithCommitCharacterRules(ImmutableArray<CharacterSetModificationRule> commitCharacterRules) => With(commitRules: commitCharacterRules); /// <summary> /// Creates a copy of this <see cref="CompletionItemRules"/> with the <see cref="EnterKeyRule"/> property changed. /// </summary> public CompletionItemRules WithEnterKeyRule(EnterKeyRule enterKeyRule) => With(enterKeyRule: enterKeyRule); /// <summary> /// Creates a copy of this <see cref="CompletionItemRules"/> with the <see cref="FormatOnCommit"/> property changed. /// </summary> public CompletionItemRules WithFormatOnCommit(bool formatOnCommit) => With(formatOnCommit: formatOnCommit); /// <summary> /// Creates a copy of this <see cref="CompletionItemRules"/> with the <see cref="MatchPriority"/> property changed. /// </summary> public CompletionItemRules WithMatchPriority(int matchPriority) => With(matchPriority: matchPriority); /// <summary> /// Creates a copy of this <see cref="CompletionItemRules"/> with the <see cref="SelectionBehavior"/> property changed. /// </summary> public CompletionItemRules WithSelectionBehavior(CompletionItemSelectionBehavior selectionBehavior) => With(selectionBehavior: selectionBehavior); } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/VisualStudio/Core/Def/Implementation/FindReferences/NameMetadata.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.FindUsages { internal class NameMetadata { public string? Name { get; } public NameMetadata(IDictionary<string, object> data) => this.Name = (string?)data.GetValueOrDefault(nameof(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. using System.Collections.Generic; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.FindUsages { internal class NameMetadata { public string? Name { get; } public NameMetadata(IDictionary<string, object> data) => this.Name = (string?)data.GetValueOrDefault(nameof(Name)); } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/CSharp/Test/Syntax/Syntax/StructuredTriviaTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class StructuredTriviaTests { [Fact] public void GetParentTrivia() { const string conditionName = "condition"; var trivia1 = SyntaxFactory.Trivia(SyntaxFactory.IfDirectiveTrivia(SyntaxFactory.IdentifierName(conditionName), false, false, false)); var structuredTrivia = trivia1.GetStructure() as IfDirectiveTriviaSyntax; Assert.NotNull(structuredTrivia); Assert.Equal(conditionName, ((IdentifierNameSyntax)structuredTrivia.Condition).Identifier.ValueText); var trivia2 = structuredTrivia.ParentTrivia; Assert.Equal(trivia1, trivia2); } [Fact] public void TestStructuredTrivia() { var spaceTrivia = SyntaxTriviaListBuilder.Create().Add(SyntaxFactory.Whitespace(" ")).ToList(); var emptyTrivia = SyntaxTriviaListBuilder.Create().ToList(); var name = "goo"; var xmlStartElement = SyntaxFactory.XmlElementStartTag( SyntaxFactory.Token(spaceTrivia, SyntaxKind.LessThanToken, default(SyntaxTriviaList)), SyntaxFactory.XmlName(null, SyntaxFactory.Identifier(name)), default(SyntaxList<XmlAttributeSyntax>), SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.GreaterThanToken, spaceTrivia)); var xmlEndElement = SyntaxFactory.XmlElementEndTag( SyntaxFactory.Token(SyntaxKind.LessThanSlashToken), SyntaxFactory.XmlName(null, SyntaxFactory.Identifier(name)), SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.GreaterThanToken, spaceTrivia)); var xmlElement = SyntaxFactory.XmlElement(xmlStartElement, default(SyntaxList<XmlNodeSyntax>), xmlEndElement); Assert.Equal(" <goo> </goo> ", xmlElement.ToFullString()); Assert.Equal("<goo> </goo>", xmlElement.ToString()); var docComment = SyntaxFactory.DocumentationCommentTrivia(SyntaxKind.SingleLineDocumentationCommentTrivia).WithContent(new SyntaxList<XmlNodeSyntax>(xmlElement)); Assert.Equal(" <goo> </goo> ", docComment.ToFullString()); // Assert.Equal("<goo> </goo>", docComment.GetText()); var child = (XmlElementSyntax)docComment.ChildNodesAndTokens()[0]; Assert.Equal(" <goo> </goo> ", child.ToFullString()); Assert.Equal("<goo> </goo>", child.ToString()); Assert.Equal(" <goo> ", child.StartTag.ToFullString()); Assert.Equal("<goo>", child.StartTag.ToString()); var sTrivia = SyntaxFactory.Trivia(docComment); Assert.NotEqual(default(SyntaxTrivia), sTrivia); var ident = SyntaxFactory.Identifier(SyntaxTriviaList.Create(sTrivia), "banana", spaceTrivia); Assert.Equal(" <goo> </goo> banana ", ident.ToFullString()); Assert.Equal("banana", ident.ToString()); Assert.Equal(" <goo> </goo> ", ident.LeadingTrivia[0].ToFullString()); // Assert.Equal("<goo> </goo>", ident.LeadingTrivia[0].GetText()); var identExpr = SyntaxFactory.IdentifierName(ident); // make sure FindLeaf digs into the structured trivia. var result = identExpr.FindToken(3, true); Assert.Equal(SyntaxKind.IdentifierToken, result.Kind()); Assert.Equal("goo", result.ToString()); var trResult = identExpr.FindTrivia(6, SyntaxTrivia.Any); Assert.Equal(SyntaxKind.WhitespaceTrivia, trResult.Kind()); Assert.Equal(" ", trResult.ToString()); var foundDocComment = result.Parent.Parent.Parent.Parent; Assert.Null(foundDocComment.Parent); var identTrivia = identExpr.GetLeadingTrivia()[0]; var foundTrivia = ((DocumentationCommentTriviaSyntax)foundDocComment).ParentTrivia; Assert.Equal(identTrivia, foundTrivia); // make sure FindLeafNodesOverlappingWithSpan does not dig into the structured trivia. var resultList = identExpr.DescendantTokens(t => t.FullSpan.OverlapsWith(new TextSpan(3, 18))); Assert.Equal(1, resultList.Count()); } [Fact] public void ReferenceDirectives1() { var tree = SyntaxFactory.ParseSyntaxTree(@" #r ""ref0"" #define Goo #r ""ref1"" #r ""ref2"" using Blah; #r ""ref3"" "); var compilationUnit = tree.GetCompilationUnitRoot(); var directives = compilationUnit.GetReferenceDirectives(); Assert.Equal(3, directives.Count); Assert.Equal("ref0", directives[0].File.Value); Assert.Equal("ref1", directives[1].File.Value); Assert.Equal("ref2", directives[2].File.Value); } [Fact] public void ReferenceDirectives2() { var tree = SyntaxFactory.ParseSyntaxTree(@" #r ""ref0"" "); var compilationUnit = tree.GetCompilationUnitRoot(); var directives = compilationUnit.GetReferenceDirectives(); Assert.Equal(1, directives.Count); Assert.Equal("ref0", directives[0].File.Value); } [Fact] public void ReferenceDirectives3() { var tree = SyntaxFactory.ParseSyntaxTree(@" "); var compilationUnit = tree.GetCompilationUnitRoot(); var directives = compilationUnit.GetReferenceDirectives(); Assert.Equal(0, directives.Count); } [Fact] public void ReferenceDirectives4() { var tree = SyntaxFactory.ParseSyntaxTree(@" #r #r "" #r ""a"" blah "); var compilationUnit = tree.GetCompilationUnitRoot(); var directives = compilationUnit.GetReferenceDirectives(); Assert.Equal(3, directives.Count); Assert.True(directives[0].File.IsMissing); Assert.False(directives[1].File.IsMissing); Assert.Equal("", directives[1].File.Value); Assert.Equal("a", directives[2].File.Value); } [WorkItem(546207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546207")] [Fact] public void DocumentationCommentsLocation_SingleLine() { var tree = SyntaxFactory.ParseSyntaxTree(@" class Program { /// <summary/> static void Main() { } } "); var trivia = tree.GetCompilationUnitRoot().DescendantTrivia().Single(t => t.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia); Assert.Equal(SyntaxKind.StaticKeyword, trivia.Token.Kind()); } [WorkItem(546207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546207")] [Fact] public void DocumentationCommentsLocation_MultiLine() { var tree = SyntaxFactory.ParseSyntaxTree(@" class Program { /** <summary/> */ static void Main() { } } "); var trivia = tree.GetCompilationUnitRoot().DescendantTrivia().Single(t => t.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia); Assert.Equal(SyntaxKind.StaticKeyword, trivia.Token.Kind()); } [Fact] public void TestTriviaList_getItemFailures() { var tree = SyntaxFactory.ParseSyntaxTree(" class goo {}"); var trivia = tree.GetCompilationUnitRoot().Members[0].GetLeadingTrivia(); var t1 = trivia[0]; Assert.Equal(1, trivia.Count); // Bounds checking exceptions Assert.Throws<System.ArgumentOutOfRangeException>(delegate { var t2 = trivia[1]; }); Assert.Throws<System.ArgumentOutOfRangeException>(delegate { var t3 = trivia[-1]; }); // Invalid Use create SyntaxTriviaList Assert.Throws<System.ArgumentOutOfRangeException>(delegate { var trl = new SyntaxTriviaList(); var t2 = trl[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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class StructuredTriviaTests { [Fact] public void GetParentTrivia() { const string conditionName = "condition"; var trivia1 = SyntaxFactory.Trivia(SyntaxFactory.IfDirectiveTrivia(SyntaxFactory.IdentifierName(conditionName), false, false, false)); var structuredTrivia = trivia1.GetStructure() as IfDirectiveTriviaSyntax; Assert.NotNull(structuredTrivia); Assert.Equal(conditionName, ((IdentifierNameSyntax)structuredTrivia.Condition).Identifier.ValueText); var trivia2 = structuredTrivia.ParentTrivia; Assert.Equal(trivia1, trivia2); } [Fact] public void TestStructuredTrivia() { var spaceTrivia = SyntaxTriviaListBuilder.Create().Add(SyntaxFactory.Whitespace(" ")).ToList(); var emptyTrivia = SyntaxTriviaListBuilder.Create().ToList(); var name = "goo"; var xmlStartElement = SyntaxFactory.XmlElementStartTag( SyntaxFactory.Token(spaceTrivia, SyntaxKind.LessThanToken, default(SyntaxTriviaList)), SyntaxFactory.XmlName(null, SyntaxFactory.Identifier(name)), default(SyntaxList<XmlAttributeSyntax>), SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.GreaterThanToken, spaceTrivia)); var xmlEndElement = SyntaxFactory.XmlElementEndTag( SyntaxFactory.Token(SyntaxKind.LessThanSlashToken), SyntaxFactory.XmlName(null, SyntaxFactory.Identifier(name)), SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.GreaterThanToken, spaceTrivia)); var xmlElement = SyntaxFactory.XmlElement(xmlStartElement, default(SyntaxList<XmlNodeSyntax>), xmlEndElement); Assert.Equal(" <goo> </goo> ", xmlElement.ToFullString()); Assert.Equal("<goo> </goo>", xmlElement.ToString()); var docComment = SyntaxFactory.DocumentationCommentTrivia(SyntaxKind.SingleLineDocumentationCommentTrivia).WithContent(new SyntaxList<XmlNodeSyntax>(xmlElement)); Assert.Equal(" <goo> </goo> ", docComment.ToFullString()); // Assert.Equal("<goo> </goo>", docComment.GetText()); var child = (XmlElementSyntax)docComment.ChildNodesAndTokens()[0]; Assert.Equal(" <goo> </goo> ", child.ToFullString()); Assert.Equal("<goo> </goo>", child.ToString()); Assert.Equal(" <goo> ", child.StartTag.ToFullString()); Assert.Equal("<goo>", child.StartTag.ToString()); var sTrivia = SyntaxFactory.Trivia(docComment); Assert.NotEqual(default(SyntaxTrivia), sTrivia); var ident = SyntaxFactory.Identifier(SyntaxTriviaList.Create(sTrivia), "banana", spaceTrivia); Assert.Equal(" <goo> </goo> banana ", ident.ToFullString()); Assert.Equal("banana", ident.ToString()); Assert.Equal(" <goo> </goo> ", ident.LeadingTrivia[0].ToFullString()); // Assert.Equal("<goo> </goo>", ident.LeadingTrivia[0].GetText()); var identExpr = SyntaxFactory.IdentifierName(ident); // make sure FindLeaf digs into the structured trivia. var result = identExpr.FindToken(3, true); Assert.Equal(SyntaxKind.IdentifierToken, result.Kind()); Assert.Equal("goo", result.ToString()); var trResult = identExpr.FindTrivia(6, SyntaxTrivia.Any); Assert.Equal(SyntaxKind.WhitespaceTrivia, trResult.Kind()); Assert.Equal(" ", trResult.ToString()); var foundDocComment = result.Parent.Parent.Parent.Parent; Assert.Null(foundDocComment.Parent); var identTrivia = identExpr.GetLeadingTrivia()[0]; var foundTrivia = ((DocumentationCommentTriviaSyntax)foundDocComment).ParentTrivia; Assert.Equal(identTrivia, foundTrivia); // make sure FindLeafNodesOverlappingWithSpan does not dig into the structured trivia. var resultList = identExpr.DescendantTokens(t => t.FullSpan.OverlapsWith(new TextSpan(3, 18))); Assert.Equal(1, resultList.Count()); } [Fact] public void ReferenceDirectives1() { var tree = SyntaxFactory.ParseSyntaxTree(@" #r ""ref0"" #define Goo #r ""ref1"" #r ""ref2"" using Blah; #r ""ref3"" "); var compilationUnit = tree.GetCompilationUnitRoot(); var directives = compilationUnit.GetReferenceDirectives(); Assert.Equal(3, directives.Count); Assert.Equal("ref0", directives[0].File.Value); Assert.Equal("ref1", directives[1].File.Value); Assert.Equal("ref2", directives[2].File.Value); } [Fact] public void ReferenceDirectives2() { var tree = SyntaxFactory.ParseSyntaxTree(@" #r ""ref0"" "); var compilationUnit = tree.GetCompilationUnitRoot(); var directives = compilationUnit.GetReferenceDirectives(); Assert.Equal(1, directives.Count); Assert.Equal("ref0", directives[0].File.Value); } [Fact] public void ReferenceDirectives3() { var tree = SyntaxFactory.ParseSyntaxTree(@" "); var compilationUnit = tree.GetCompilationUnitRoot(); var directives = compilationUnit.GetReferenceDirectives(); Assert.Equal(0, directives.Count); } [Fact] public void ReferenceDirectives4() { var tree = SyntaxFactory.ParseSyntaxTree(@" #r #r "" #r ""a"" blah "); var compilationUnit = tree.GetCompilationUnitRoot(); var directives = compilationUnit.GetReferenceDirectives(); Assert.Equal(3, directives.Count); Assert.True(directives[0].File.IsMissing); Assert.False(directives[1].File.IsMissing); Assert.Equal("", directives[1].File.Value); Assert.Equal("a", directives[2].File.Value); } [WorkItem(546207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546207")] [Fact] public void DocumentationCommentsLocation_SingleLine() { var tree = SyntaxFactory.ParseSyntaxTree(@" class Program { /// <summary/> static void Main() { } } "); var trivia = tree.GetCompilationUnitRoot().DescendantTrivia().Single(t => t.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia); Assert.Equal(SyntaxKind.StaticKeyword, trivia.Token.Kind()); } [WorkItem(546207, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546207")] [Fact] public void DocumentationCommentsLocation_MultiLine() { var tree = SyntaxFactory.ParseSyntaxTree(@" class Program { /** <summary/> */ static void Main() { } } "); var trivia = tree.GetCompilationUnitRoot().DescendantTrivia().Single(t => t.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia); Assert.Equal(SyntaxKind.StaticKeyword, trivia.Token.Kind()); } [Fact] public void TestTriviaList_getItemFailures() { var tree = SyntaxFactory.ParseSyntaxTree(" class goo {}"); var trivia = tree.GetCompilationUnitRoot().Members[0].GetLeadingTrivia(); var t1 = trivia[0]; Assert.Equal(1, trivia.Count); // Bounds checking exceptions Assert.Throws<System.ArgumentOutOfRangeException>(delegate { var t2 = trivia[1]; }); Assert.Throws<System.ArgumentOutOfRangeException>(delegate { var t3 = trivia[-1]; }); // Invalid Use create SyntaxTriviaList Assert.Throws<System.ArgumentOutOfRangeException>(delegate { var trl = new SyntaxTriviaList(); var t2 = trl[0]; }); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Features/Core/Portable/EditAndContinue/Remote/IRemoteEditAndContinueService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Diagnostics; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal interface IRemoteEditAndContinueService { internal interface ICallback { ValueTask<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask<ManagedEditAndContinueAvailability> GetAvailabilityAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken); ValueTask<ImmutableArray<string>> GetCapabilitiesAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask PrepareModuleForUpdateAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken); ValueTask<ImmutableArray<ActiveStatementSpan>> GetSpansAsync(RemoteServiceCallbackId callbackId, DocumentId? documentId, string filePath, CancellationToken cancellationToken); } ValueTask<ImmutableArray<DiagnosticData>> GetDocumentDiagnosticsAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken); ValueTask<bool> HasChangesAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, string? sourceFilePath, CancellationToken cancellationToken); ValueTask<EmitSolutionUpdateResults.Data> EmitSolutionUpdateAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, CancellationToken cancellationToken); /// <summary> /// Returns ids of documents for which diagnostics need to be refreshed in-proc. /// </summary> ValueTask<ImmutableArray<DocumentId>> CommitSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken); ValueTask DiscardSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken); ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken); /// <summary> /// Returns ids of documents for which diagnostics need to be refreshed in-proc. /// </summary> ValueTask<ImmutableArray<DocumentId>> BreakStateOrCapabilitiesChangedAsync(DebuggingSessionId sessionId, bool? isBreakState, CancellationToken cancellationToken); /// <summary> /// Returns ids of documents for which diagnostics need to be refreshed in-proc. /// </summary> ValueTask<ImmutableArray<DocumentId>> EndDebuggingSessionAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken); ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken); ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, DocumentId documentId, CancellationToken cancellationToken); ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken); ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken); ValueTask OnSourceFileUpdatedAsync(PinnedSolutionInfo solutionInfo, DocumentId documentId, 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.Diagnostics; using Microsoft.CodeAnalysis.Remote; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue; namespace Microsoft.CodeAnalysis.EditAndContinue { internal interface IRemoteEditAndContinueService { internal interface ICallback { ValueTask<ImmutableArray<ManagedActiveStatementDebugInfo>> GetActiveStatementsAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask<ManagedEditAndContinueAvailability> GetAvailabilityAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken); ValueTask<ImmutableArray<string>> GetCapabilitiesAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellationToken); ValueTask PrepareModuleForUpdateAsync(RemoteServiceCallbackId callbackId, Guid mvid, CancellationToken cancellationToken); ValueTask<ImmutableArray<ActiveStatementSpan>> GetSpansAsync(RemoteServiceCallbackId callbackId, DocumentId? documentId, string filePath, CancellationToken cancellationToken); } ValueTask<ImmutableArray<DiagnosticData>> GetDocumentDiagnosticsAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DocumentId documentId, CancellationToken cancellationToken); ValueTask<bool> HasChangesAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, string? sourceFilePath, CancellationToken cancellationToken); ValueTask<EmitSolutionUpdateResults.Data> EmitSolutionUpdateAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, CancellationToken cancellationToken); /// <summary> /// Returns ids of documents for which diagnostics need to be refreshed in-proc. /// </summary> ValueTask<ImmutableArray<DocumentId>> CommitSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken); ValueTask DiscardSolutionUpdateAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken); ValueTask<DebuggingSessionId> StartDebuggingSessionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, ImmutableArray<DocumentId> captureMatchingDocuments, bool captureAllMatchingDocuments, bool reportDiagnostics, CancellationToken cancellationToken); /// <summary> /// Returns ids of documents for which diagnostics need to be refreshed in-proc. /// </summary> ValueTask<ImmutableArray<DocumentId>> BreakStateOrCapabilitiesChangedAsync(DebuggingSessionId sessionId, bool? isBreakState, CancellationToken cancellationToken); /// <summary> /// Returns ids of documents for which diagnostics need to be refreshed in-proc. /// </summary> ValueTask<ImmutableArray<DocumentId>> EndDebuggingSessionAsync(DebuggingSessionId sessionId, CancellationToken cancellationToken); ValueTask<ImmutableArray<ImmutableArray<ActiveStatementSpan>>> GetBaseActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken); ValueTask<ImmutableArray<ActiveStatementSpan>> GetAdjustedActiveStatementSpansAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, DocumentId documentId, CancellationToken cancellationToken); ValueTask<bool?> IsActiveStatementInExceptionRegionAsync(PinnedSolutionInfo solutionInfo, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken); ValueTask<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(PinnedSolutionInfo solutionInfo, RemoteServiceCallbackId callbackId, DebuggingSessionId sessionId, ManagedInstructionId instructionId, CancellationToken cancellationToken); ValueTask OnSourceFileUpdatedAsync(PinnedSolutionInfo solutionInfo, DocumentId documentId, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Symbols/Metadata/PE/TupleTypeDecoder.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { /// <summary> /// In C#, tuples can be represented using tuple syntax and be given /// names. However, the underlying representation for tuples unifies /// to a single underlying tuple type, System.ValueTuple. Since the /// names aren't part of the underlying tuple type they have to be /// recorded somewhere else. /// /// Roslyn records tuple names in an attribute: the /// TupleElementNamesAttribute. The attribute contains a single string /// array which records the names of the tuple elements in a pre-order /// depth-first traversal. If the type contains nested parameters, /// they are also recorded in a pre-order depth-first traversal. /// <see cref="DecodeTupleTypesIfApplicable(TypeSymbol, EntityHandle, PEModuleSymbol)"/> /// can be used to extract tuple names and types from metadata and create /// a <see cref="NamedTypeSymbol"/> with attached names. /// /// <example> /// For instance, a method returning a tuple /// /// <code> /// (int x, int y) M() { ... } /// </code> /// /// will be encoded using an attribute on the return type as follows /// /// <code> /// [return: TupleElementNamesAttribute(new[] { "x", "y" })] /// System.ValueTuple&lt;int, int&gt; M() { ... } /// </code> /// </example> /// /// <example> /// For nested type parameters, we expand the tuple names in a pre-order /// traversal: /// /// <code> /// class C : BaseType&lt;((int e1, int e2) e3, int e4)&lt; { ... } /// </code> /// /// becomes /// /// <code> /// [TupleElementNamesAttribute(new[] { "e3", "e4", "e1", "e2" }); /// class C : BaseType&lt;System.ValueTuple&lt; /// System.ValueTuple&lt;int,int&gt;, int&gt; /// { ... } /// </code> /// </example> /// </summary> internal struct TupleTypeDecoder { private readonly ImmutableArray<string?> _elementNames; // Keep track of how many names we've "used" during decoding. Starts at // the back of the array and moves forward. private int _namesIndex; private bool _foundUsableErrorType; private bool _decodingFailed; private TupleTypeDecoder(ImmutableArray<string?> elementNames) { _elementNames = elementNames; _namesIndex = elementNames.IsDefault ? 0 : elementNames.Length; _decodingFailed = false; _foundUsableErrorType = false; } public static TypeSymbol DecodeTupleTypesIfApplicable( TypeSymbol metadataType, EntityHandle targetHandle, PEModuleSymbol containingModule) { ImmutableArray<string?> elementNames; var hasTupleElementNamesAttribute = containingModule .Module .HasTupleElementNamesAttribute(targetHandle, out elementNames); // If we have the TupleElementNamesAttribute, but no names, that's // bad metadata if (hasTupleElementNamesAttribute && elementNames.IsDefaultOrEmpty) { return new UnsupportedMetadataTypeSymbol(); } return DecodeTupleTypesInternal(metadataType, elementNames, hasTupleElementNamesAttribute); } public static TypeWithAnnotations DecodeTupleTypesIfApplicable( TypeWithAnnotations metadataType, EntityHandle targetHandle, PEModuleSymbol containingModule) { ImmutableArray<string?> elementNames; var hasTupleElementNamesAttribute = containingModule .Module .HasTupleElementNamesAttribute(targetHandle, out elementNames); // If we have the TupleElementNamesAttribute, but no names, that's // bad metadata if (hasTupleElementNamesAttribute && elementNames.IsDefaultOrEmpty) { return TypeWithAnnotations.Create(new UnsupportedMetadataTypeSymbol()); } TypeSymbol type = metadataType.Type; TypeSymbol decoded = DecodeTupleTypesInternal(type, elementNames, hasTupleElementNamesAttribute); return (object)decoded == (object)type ? metadataType : TypeWithAnnotations.Create(decoded, metadataType.NullableAnnotation, metadataType.CustomModifiers); } public static TypeSymbol DecodeTupleTypesIfApplicable( TypeSymbol metadataType, ImmutableArray<string?> elementNames) { return DecodeTupleTypesInternal(metadataType, elementNames, hasTupleElementNamesAttribute: !elementNames.IsDefaultOrEmpty); } private static TypeSymbol DecodeTupleTypesInternal(TypeSymbol metadataType, ImmutableArray<string?> elementNames, bool hasTupleElementNamesAttribute) { RoslynDebug.AssertNotNull(metadataType); var decoder = new TupleTypeDecoder(elementNames); var decoded = decoder.DecodeType(metadataType); if (!decoder._decodingFailed) { if (!hasTupleElementNamesAttribute || decoder._namesIndex == 0) { return decoded; } } // If not all of the names have been used, the metadata is bad if (decoder._foundUsableErrorType) { return metadataType; } // Bad metadata return new UnsupportedMetadataTypeSymbol(); } private TypeSymbol DecodeType(TypeSymbol type) { switch (type.Kind) { case SymbolKind.ErrorType: _foundUsableErrorType = true; return type; case SymbolKind.DynamicType: case SymbolKind.TypeParameter: return type; case SymbolKind.FunctionPointerType: return DecodeFunctionPointerType((FunctionPointerTypeSymbol)type); case SymbolKind.PointerType: return DecodePointerType((PointerTypeSymbol)type); case SymbolKind.NamedType: // We may have a tuple type from a substituted type symbol, // but it will be missing names from metadata, so we'll // need to re-create the type. // // Consider the declaration // // class C : BaseType<(int x, int y)> // // The process for decoding tuples in C looks at the BaseType, calls // DecodeOrThrow, then passes the decoded type to the TupleTypeDecoder. // However, DecodeOrThrow uses the AbstractTypeMap to construct a // SubstitutedTypeSymbol, which eagerly converts tuple-compatible // types to TupleTypeSymbols. Thus, by the time we get to the Decoder // all metadata instances of System.ValueTuple will have been // replaced with TupleTypeSymbols without names. // // Rather than fixing up after-the-fact it's possible that we could // flow up a SubstituteWith/Without tuple unification to the top level // of the type map and change DecodeOrThrow to call into the substitution // without unification instead. return DecodeNamedType((NamedTypeSymbol)type); case SymbolKind.ArrayType: return DecodeArrayType((ArrayTypeSymbol)type); default: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } } private PointerTypeSymbol DecodePointerType(PointerTypeSymbol type) { return type.WithPointedAtType(DecodeTypeInternal(type.PointedAtTypeWithAnnotations)); } private FunctionPointerTypeSymbol DecodeFunctionPointerType(FunctionPointerTypeSymbol type) { var parameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; var paramsModified = false; if (type.Signature.ParameterCount > 0) { var paramsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(type.Signature.ParameterCount); for (int i = type.Signature.ParameterCount - 1; i >= 0; i--) { var param = type.Signature.Parameters[i]; var decodedParam = DecodeTypeInternal(param.TypeWithAnnotations); paramsModified = paramsModified || !decodedParam.IsSameAs(param.TypeWithAnnotations); paramsBuilder.Add(decodedParam); } if (paramsModified) { paramsBuilder.ReverseContents(); parameterTypes = paramsBuilder.ToImmutableAndFree(); } else { parameterTypes = type.Signature.ParameterTypesWithAnnotations; paramsBuilder.Free(); } } var decodedReturnType = DecodeTypeInternal(type.Signature.ReturnTypeWithAnnotations); if (paramsModified || !decodedReturnType.IsSameAs(type.Signature.ReturnTypeWithAnnotations)) { return type.SubstituteTypeSymbol(decodedReturnType, parameterTypes, refCustomModifiers: default, paramRefCustomModifiers: default); } else { return type; } } private NamedTypeSymbol DecodeNamedType(NamedTypeSymbol type) { // First decode the type arguments var typeArgs = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var decodedArgs = DecodeTypeArguments(typeArgs); NamedTypeSymbol decodedType = type; // Now check the container NamedTypeSymbol containingType = type.ContainingType; NamedTypeSymbol? decodedContainingType; if (containingType is object && containingType.IsGenericType) { decodedContainingType = DecodeNamedType(containingType); Debug.Assert(decodedContainingType.IsGenericType); } else { decodedContainingType = containingType; } // Replace the type if necessary var containerChanged = !ReferenceEquals(decodedContainingType, containingType); var typeArgsChanged = typeArgs != decodedArgs; if (typeArgsChanged || containerChanged) { if (containerChanged) { decodedType = decodedType.OriginalDefinition.AsMember(decodedContainingType); // If the type is nested, e.g. Outer<T>.Inner<V>, then Inner is definitely // not a tuple, since we know all tuple-compatible types (System.ValueTuple) // are not nested types. Thus, it is safe to return without checking if // Inner is a tuple. return decodedType.ConstructIfGeneric(decodedArgs); } decodedType = type.ConstructedFrom.Construct(decodedArgs, unbound: false); } // Now decode into a tuple, if it is one if (decodedType.IsTupleType) { int tupleCardinality = decodedType.TupleElementTypesWithAnnotations.Length; if (tupleCardinality > 0) { var elementNames = EatElementNamesIfAvailable(tupleCardinality); Debug.Assert(elementNames.IsDefault || elementNames.Length == tupleCardinality); decodedType = NamedTypeSymbol.CreateTuple(decodedType, elementNames); } } return decodedType; } private ImmutableArray<TypeWithAnnotations> DecodeTypeArguments(ImmutableArray<TypeWithAnnotations> typeArgs) { if (typeArgs.IsEmpty) { return typeArgs; } var decodedArgs = ArrayBuilder<TypeWithAnnotations>.GetInstance(typeArgs.Length); var anyDecoded = false; // Visit the type arguments in reverse for (int i = typeArgs.Length - 1; i >= 0; i--) { TypeWithAnnotations typeArg = typeArgs[i]; TypeWithAnnotations decoded = DecodeTypeInternal(typeArg); anyDecoded |= !decoded.IsSameAs(typeArg); decodedArgs.Add(decoded); } if (!anyDecoded) { decodedArgs.Free(); return typeArgs; } decodedArgs.ReverseContents(); return decodedArgs.ToImmutableAndFree(); } private ArrayTypeSymbol DecodeArrayType(ArrayTypeSymbol type) { TypeWithAnnotations decodedElementType = DecodeTypeInternal(type.ElementTypeWithAnnotations); return type.WithElementType(decodedElementType); } private TypeWithAnnotations DecodeTypeInternal(TypeWithAnnotations typeWithAnnotations) { TypeSymbol type = typeWithAnnotations.Type; TypeSymbol decoded = DecodeType(type); return ReferenceEquals(decoded, type) ? typeWithAnnotations : TypeWithAnnotations.Create(decoded, typeWithAnnotations.NullableAnnotation, typeWithAnnotations.CustomModifiers); } private ImmutableArray<string?> EatElementNamesIfAvailable(int numberOfElements) { Debug.Assert(numberOfElements > 0); // If we don't have any element names there's nothing to eat if (_elementNames.IsDefault) { return _elementNames; } // We've gone past the end of the names -- bad metadata if (numberOfElements > _namesIndex) { // We'll want to continue decoding without consuming more names to see if there are any error types _namesIndex = 0; _decodingFailed = true; return default; } // Check to see if all the elements are null var start = _namesIndex - numberOfElements; _namesIndex = start; bool allNull = true; for (int i = 0; i < numberOfElements; i++) { if (_elementNames[start + i] != null) { allNull = false; break; } } if (allNull) { return default; } return ImmutableArray.Create(_elementNames, start, numberOfElements); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.PooledObjects; using Roslyn.Utilities; using System; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Metadata; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE { /// <summary> /// In C#, tuples can be represented using tuple syntax and be given /// names. However, the underlying representation for tuples unifies /// to a single underlying tuple type, System.ValueTuple. Since the /// names aren't part of the underlying tuple type they have to be /// recorded somewhere else. /// /// Roslyn records tuple names in an attribute: the /// TupleElementNamesAttribute. The attribute contains a single string /// array which records the names of the tuple elements in a pre-order /// depth-first traversal. If the type contains nested parameters, /// they are also recorded in a pre-order depth-first traversal. /// <see cref="DecodeTupleTypesIfApplicable(TypeSymbol, EntityHandle, PEModuleSymbol)"/> /// can be used to extract tuple names and types from metadata and create /// a <see cref="NamedTypeSymbol"/> with attached names. /// /// <example> /// For instance, a method returning a tuple /// /// <code> /// (int x, int y) M() { ... } /// </code> /// /// will be encoded using an attribute on the return type as follows /// /// <code> /// [return: TupleElementNamesAttribute(new[] { "x", "y" })] /// System.ValueTuple&lt;int, int&gt; M() { ... } /// </code> /// </example> /// /// <example> /// For nested type parameters, we expand the tuple names in a pre-order /// traversal: /// /// <code> /// class C : BaseType&lt;((int e1, int e2) e3, int e4)&lt; { ... } /// </code> /// /// becomes /// /// <code> /// [TupleElementNamesAttribute(new[] { "e3", "e4", "e1", "e2" }); /// class C : BaseType&lt;System.ValueTuple&lt; /// System.ValueTuple&lt;int,int&gt;, int&gt; /// { ... } /// </code> /// </example> /// </summary> internal struct TupleTypeDecoder { private readonly ImmutableArray<string?> _elementNames; // Keep track of how many names we've "used" during decoding. Starts at // the back of the array and moves forward. private int _namesIndex; private bool _foundUsableErrorType; private bool _decodingFailed; private TupleTypeDecoder(ImmutableArray<string?> elementNames) { _elementNames = elementNames; _namesIndex = elementNames.IsDefault ? 0 : elementNames.Length; _decodingFailed = false; _foundUsableErrorType = false; } public static TypeSymbol DecodeTupleTypesIfApplicable( TypeSymbol metadataType, EntityHandle targetHandle, PEModuleSymbol containingModule) { ImmutableArray<string?> elementNames; var hasTupleElementNamesAttribute = containingModule .Module .HasTupleElementNamesAttribute(targetHandle, out elementNames); // If we have the TupleElementNamesAttribute, but no names, that's // bad metadata if (hasTupleElementNamesAttribute && elementNames.IsDefaultOrEmpty) { return new UnsupportedMetadataTypeSymbol(); } return DecodeTupleTypesInternal(metadataType, elementNames, hasTupleElementNamesAttribute); } public static TypeWithAnnotations DecodeTupleTypesIfApplicable( TypeWithAnnotations metadataType, EntityHandle targetHandle, PEModuleSymbol containingModule) { ImmutableArray<string?> elementNames; var hasTupleElementNamesAttribute = containingModule .Module .HasTupleElementNamesAttribute(targetHandle, out elementNames); // If we have the TupleElementNamesAttribute, but no names, that's // bad metadata if (hasTupleElementNamesAttribute && elementNames.IsDefaultOrEmpty) { return TypeWithAnnotations.Create(new UnsupportedMetadataTypeSymbol()); } TypeSymbol type = metadataType.Type; TypeSymbol decoded = DecodeTupleTypesInternal(type, elementNames, hasTupleElementNamesAttribute); return (object)decoded == (object)type ? metadataType : TypeWithAnnotations.Create(decoded, metadataType.NullableAnnotation, metadataType.CustomModifiers); } public static TypeSymbol DecodeTupleTypesIfApplicable( TypeSymbol metadataType, ImmutableArray<string?> elementNames) { return DecodeTupleTypesInternal(metadataType, elementNames, hasTupleElementNamesAttribute: !elementNames.IsDefaultOrEmpty); } private static TypeSymbol DecodeTupleTypesInternal(TypeSymbol metadataType, ImmutableArray<string?> elementNames, bool hasTupleElementNamesAttribute) { RoslynDebug.AssertNotNull(metadataType); var decoder = new TupleTypeDecoder(elementNames); var decoded = decoder.DecodeType(metadataType); if (!decoder._decodingFailed) { if (!hasTupleElementNamesAttribute || decoder._namesIndex == 0) { return decoded; } } // If not all of the names have been used, the metadata is bad if (decoder._foundUsableErrorType) { return metadataType; } // Bad metadata return new UnsupportedMetadataTypeSymbol(); } private TypeSymbol DecodeType(TypeSymbol type) { switch (type.Kind) { case SymbolKind.ErrorType: _foundUsableErrorType = true; return type; case SymbolKind.DynamicType: case SymbolKind.TypeParameter: return type; case SymbolKind.FunctionPointerType: return DecodeFunctionPointerType((FunctionPointerTypeSymbol)type); case SymbolKind.PointerType: return DecodePointerType((PointerTypeSymbol)type); case SymbolKind.NamedType: // We may have a tuple type from a substituted type symbol, // but it will be missing names from metadata, so we'll // need to re-create the type. // // Consider the declaration // // class C : BaseType<(int x, int y)> // // The process for decoding tuples in C looks at the BaseType, calls // DecodeOrThrow, then passes the decoded type to the TupleTypeDecoder. // However, DecodeOrThrow uses the AbstractTypeMap to construct a // SubstitutedTypeSymbol, which eagerly converts tuple-compatible // types to TupleTypeSymbols. Thus, by the time we get to the Decoder // all metadata instances of System.ValueTuple will have been // replaced with TupleTypeSymbols without names. // // Rather than fixing up after-the-fact it's possible that we could // flow up a SubstituteWith/Without tuple unification to the top level // of the type map and change DecodeOrThrow to call into the substitution // without unification instead. return DecodeNamedType((NamedTypeSymbol)type); case SymbolKind.ArrayType: return DecodeArrayType((ArrayTypeSymbol)type); default: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } } private PointerTypeSymbol DecodePointerType(PointerTypeSymbol type) { return type.WithPointedAtType(DecodeTypeInternal(type.PointedAtTypeWithAnnotations)); } private FunctionPointerTypeSymbol DecodeFunctionPointerType(FunctionPointerTypeSymbol type) { var parameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; var paramsModified = false; if (type.Signature.ParameterCount > 0) { var paramsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(type.Signature.ParameterCount); for (int i = type.Signature.ParameterCount - 1; i >= 0; i--) { var param = type.Signature.Parameters[i]; var decodedParam = DecodeTypeInternal(param.TypeWithAnnotations); paramsModified = paramsModified || !decodedParam.IsSameAs(param.TypeWithAnnotations); paramsBuilder.Add(decodedParam); } if (paramsModified) { paramsBuilder.ReverseContents(); parameterTypes = paramsBuilder.ToImmutableAndFree(); } else { parameterTypes = type.Signature.ParameterTypesWithAnnotations; paramsBuilder.Free(); } } var decodedReturnType = DecodeTypeInternal(type.Signature.ReturnTypeWithAnnotations); if (paramsModified || !decodedReturnType.IsSameAs(type.Signature.ReturnTypeWithAnnotations)) { return type.SubstituteTypeSymbol(decodedReturnType, parameterTypes, refCustomModifiers: default, paramRefCustomModifiers: default); } else { return type; } } private NamedTypeSymbol DecodeNamedType(NamedTypeSymbol type) { // First decode the type arguments var typeArgs = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; var decodedArgs = DecodeTypeArguments(typeArgs); NamedTypeSymbol decodedType = type; // Now check the container NamedTypeSymbol containingType = type.ContainingType; NamedTypeSymbol? decodedContainingType; if (containingType is object && containingType.IsGenericType) { decodedContainingType = DecodeNamedType(containingType); Debug.Assert(decodedContainingType.IsGenericType); } else { decodedContainingType = containingType; } // Replace the type if necessary var containerChanged = !ReferenceEquals(decodedContainingType, containingType); var typeArgsChanged = typeArgs != decodedArgs; if (typeArgsChanged || containerChanged) { if (containerChanged) { decodedType = decodedType.OriginalDefinition.AsMember(decodedContainingType); // If the type is nested, e.g. Outer<T>.Inner<V>, then Inner is definitely // not a tuple, since we know all tuple-compatible types (System.ValueTuple) // are not nested types. Thus, it is safe to return without checking if // Inner is a tuple. return decodedType.ConstructIfGeneric(decodedArgs); } decodedType = type.ConstructedFrom.Construct(decodedArgs, unbound: false); } // Now decode into a tuple, if it is one if (decodedType.IsTupleType) { int tupleCardinality = decodedType.TupleElementTypesWithAnnotations.Length; if (tupleCardinality > 0) { var elementNames = EatElementNamesIfAvailable(tupleCardinality); Debug.Assert(elementNames.IsDefault || elementNames.Length == tupleCardinality); decodedType = NamedTypeSymbol.CreateTuple(decodedType, elementNames); } } return decodedType; } private ImmutableArray<TypeWithAnnotations> DecodeTypeArguments(ImmutableArray<TypeWithAnnotations> typeArgs) { if (typeArgs.IsEmpty) { return typeArgs; } var decodedArgs = ArrayBuilder<TypeWithAnnotations>.GetInstance(typeArgs.Length); var anyDecoded = false; // Visit the type arguments in reverse for (int i = typeArgs.Length - 1; i >= 0; i--) { TypeWithAnnotations typeArg = typeArgs[i]; TypeWithAnnotations decoded = DecodeTypeInternal(typeArg); anyDecoded |= !decoded.IsSameAs(typeArg); decodedArgs.Add(decoded); } if (!anyDecoded) { decodedArgs.Free(); return typeArgs; } decodedArgs.ReverseContents(); return decodedArgs.ToImmutableAndFree(); } private ArrayTypeSymbol DecodeArrayType(ArrayTypeSymbol type) { TypeWithAnnotations decodedElementType = DecodeTypeInternal(type.ElementTypeWithAnnotations); return type.WithElementType(decodedElementType); } private TypeWithAnnotations DecodeTypeInternal(TypeWithAnnotations typeWithAnnotations) { TypeSymbol type = typeWithAnnotations.Type; TypeSymbol decoded = DecodeType(type); return ReferenceEquals(decoded, type) ? typeWithAnnotations : TypeWithAnnotations.Create(decoded, typeWithAnnotations.NullableAnnotation, typeWithAnnotations.CustomModifiers); } private ImmutableArray<string?> EatElementNamesIfAvailable(int numberOfElements) { Debug.Assert(numberOfElements > 0); // If we don't have any element names there's nothing to eat if (_elementNames.IsDefault) { return _elementNames; } // We've gone past the end of the names -- bad metadata if (numberOfElements > _namesIndex) { // We'll want to continue decoding without consuming more names to see if there are any error types _namesIndex = 0; _decodingFailed = true; return default; } // Check to see if all the elements are null var start = _namesIndex - numberOfElements; _namesIndex = start; bool allNull = true; for (int i = 0; i < numberOfElements; i++) { if (_elementNames[start + i] != null) { allNull = false; break; } } if (allNull) { return default; } return ImmutableArray.Create(_elementNames, start, numberOfElements); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Workspaces/Remote/ServiceHub/Host/RemoteWorkspaceManager.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.ServiceHub.Framework; using Microsoft.VisualStudio.Composition; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Manages remote workspaces. Currently supports only a single, primary workspace of kind <see cref="WorkspaceKind.RemoteWorkspace"/>. /// In future it should support workspaces of all kinds. /// </summary> internal class RemoteWorkspaceManager { /// <summary> /// Default workspace manager used by the product. Tests may specify a custom <see cref="RemoteWorkspaceManager"/> /// in order to override workspace services. /// </summary> internal static readonly RemoteWorkspaceManager Default = new RemoteWorkspaceManager( new SolutionAssetCache(cleanupInterval: TimeSpan.FromMinutes(1), purgeAfter: TimeSpan.FromMinutes(3), gcAfter: TimeSpan.FromMinutes(5))); internal static readonly ImmutableArray<Assembly> RemoteHostAssemblies = MefHostServices.DefaultAssemblies .Add(typeof(BrokeredServiceBase).Assembly) .Add(typeof(RemoteWorkspacesResources).Assembly); private readonly Lazy<RemoteWorkspace> _lazyPrimaryWorkspace; internal readonly SolutionAssetCache SolutionAssetCache; public RemoteWorkspaceManager(SolutionAssetCache assetCache) { _lazyPrimaryWorkspace = new Lazy<RemoteWorkspace>(CreatePrimaryWorkspace); SolutionAssetCache = assetCache; } private static ComposableCatalog CreateCatalog(ImmutableArray<Assembly> assemblies) { var resolver = new Resolver(SimpleAssemblyLoader.Instance); var discovery = new AttributedPartDiscovery(resolver, isNonPublicSupported: true); var parts = Task.Run(async () => await discovery.CreatePartsAsync(assemblies).ConfigureAwait(false)).GetAwaiter().GetResult(); return ComposableCatalog.Create(resolver).AddParts(parts); } private static IExportProviderFactory CreateExportProviderFactory(ComposableCatalog catalog) { var configuration = CompositionConfiguration.Create(catalog); var runtimeComposition = RuntimeComposition.CreateRuntimeComposition(configuration); return runtimeComposition.CreateExportProviderFactory(); } private static RemoteWorkspace CreatePrimaryWorkspace() { var catalog = CreateCatalog(RemoteHostAssemblies); var exportProviderFactory = CreateExportProviderFactory(catalog); var exportProvider = exportProviderFactory.CreateExportProvider(); return new RemoteWorkspace(VisualStudioMefHostServices.Create(exportProvider), WorkspaceKind.RemoteWorkspace); } public virtual RemoteWorkspace GetWorkspace() => _lazyPrimaryWorkspace.Value; public ValueTask<Solution> GetSolutionAsync(ServiceBrokerClient client, PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken) { var assetSource = new SolutionAssetSource(client); var workspace = GetWorkspace(); var assetProvider = workspace.CreateAssetProvider(solutionInfo, SolutionAssetCache, assetSource); return workspace.GetSolutionAsync(assetProvider, solutionInfo.SolutionChecksum, solutionInfo.FromPrimaryBranch, solutionInfo.WorkspaceVersion, solutionInfo.ProjectId, cancellationToken); } private sealed class SimpleAssemblyLoader : IAssemblyLoader { public static readonly IAssemblyLoader Instance = new SimpleAssemblyLoader(); public Assembly LoadAssembly(AssemblyName assemblyName) => Assembly.Load(assemblyName); public Assembly LoadAssembly(string assemblyFullName, string codeBasePath) { var assemblyName = new AssemblyName(assemblyFullName); if (!string.IsNullOrEmpty(codeBasePath)) { assemblyName.CodeBase = codeBasePath; } return LoadAssembly(assemblyName); } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.ServiceHub.Framework; using Microsoft.VisualStudio.Composition; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Manages remote workspaces. Currently supports only a single, primary workspace of kind <see cref="WorkspaceKind.RemoteWorkspace"/>. /// In future it should support workspaces of all kinds. /// </summary> internal class RemoteWorkspaceManager { /// <summary> /// Default workspace manager used by the product. Tests may specify a custom <see cref="RemoteWorkspaceManager"/> /// in order to override workspace services. /// </summary> internal static readonly RemoteWorkspaceManager Default = new RemoteWorkspaceManager( new SolutionAssetCache(cleanupInterval: TimeSpan.FromMinutes(1), purgeAfter: TimeSpan.FromMinutes(3), gcAfter: TimeSpan.FromMinutes(5))); internal static readonly ImmutableArray<Assembly> RemoteHostAssemblies = MefHostServices.DefaultAssemblies .Add(typeof(BrokeredServiceBase).Assembly) .Add(typeof(RemoteWorkspacesResources).Assembly); private readonly Lazy<RemoteWorkspace> _lazyPrimaryWorkspace; internal readonly SolutionAssetCache SolutionAssetCache; public RemoteWorkspaceManager(SolutionAssetCache assetCache) { _lazyPrimaryWorkspace = new Lazy<RemoteWorkspace>(CreatePrimaryWorkspace); SolutionAssetCache = assetCache; } private static ComposableCatalog CreateCatalog(ImmutableArray<Assembly> assemblies) { var resolver = new Resolver(SimpleAssemblyLoader.Instance); var discovery = new AttributedPartDiscovery(resolver, isNonPublicSupported: true); var parts = Task.Run(async () => await discovery.CreatePartsAsync(assemblies).ConfigureAwait(false)).GetAwaiter().GetResult(); return ComposableCatalog.Create(resolver).AddParts(parts); } private static IExportProviderFactory CreateExportProviderFactory(ComposableCatalog catalog) { var configuration = CompositionConfiguration.Create(catalog); var runtimeComposition = RuntimeComposition.CreateRuntimeComposition(configuration); return runtimeComposition.CreateExportProviderFactory(); } private static RemoteWorkspace CreatePrimaryWorkspace() { var catalog = CreateCatalog(RemoteHostAssemblies); var exportProviderFactory = CreateExportProviderFactory(catalog); var exportProvider = exportProviderFactory.CreateExportProvider(); return new RemoteWorkspace(VisualStudioMefHostServices.Create(exportProvider), WorkspaceKind.RemoteWorkspace); } public virtual RemoteWorkspace GetWorkspace() => _lazyPrimaryWorkspace.Value; public ValueTask<Solution> GetSolutionAsync(ServiceBrokerClient client, PinnedSolutionInfo solutionInfo, CancellationToken cancellationToken) { var assetSource = new SolutionAssetSource(client); var workspace = GetWorkspace(); var assetProvider = workspace.CreateAssetProvider(solutionInfo, SolutionAssetCache, assetSource); return workspace.GetSolutionAsync(assetProvider, solutionInfo.SolutionChecksum, solutionInfo.FromPrimaryBranch, solutionInfo.WorkspaceVersion, solutionInfo.ProjectId, cancellationToken); } private sealed class SimpleAssemblyLoader : IAssemblyLoader { public static readonly IAssemblyLoader Instance = new SimpleAssemblyLoader(); public Assembly LoadAssembly(AssemblyName assemblyName) => Assembly.Load(assemblyName); public Assembly LoadAssembly(string assemblyFullName, string codeBasePath) { var assemblyName = new AssemblyName(assemblyFullName); if (!string.IsNullOrEmpty(codeBasePath)) { assemblyName.CodeBase = codeBasePath; } return LoadAssembly(assemblyName); } } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Features/Core/Portable/SolutionCrawler/GlobalOperationAwareIdleProcessor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal abstract class GlobalOperationAwareIdleProcessor : IdleProcessor { private readonly IGlobalOperationNotificationService _globalOperationNotificationService; private TaskCompletionSource<object?>? _globalOperation; private Task _globalOperationTask; public GlobalOperationAwareIdleProcessor( IAsynchronousOperationListener listener, IGlobalOperationNotificationService globalOperationNotificationService, TimeSpan backOffTimeSpan, CancellationToken shutdownToken) : base(listener, backOffTimeSpan, shutdownToken) { _globalOperation = null; _globalOperationTask = Task.CompletedTask; _globalOperationNotificationService = globalOperationNotificationService; _globalOperationNotificationService.Started += OnGlobalOperationStarted; _globalOperationNotificationService.Stopped += OnGlobalOperationStopped; } protected Task GlobalOperationTask => _globalOperationTask; protected abstract void PauseOnGlobalOperation(); private void OnGlobalOperationStarted(object? sender, EventArgs e) { Contract.ThrowIfFalse(_globalOperation == null); // events are serialized. no lock is needed _globalOperation = new TaskCompletionSource<object?>(); _globalOperationTask = _globalOperation.Task; PauseOnGlobalOperation(); } private void OnGlobalOperationStopped(object? sender, GlobalOperationEventArgs e) { if (_globalOperation == null) { // we subscribed to the event while it is already running. return; } // events are serialized. no lock is needed _globalOperation.SetResult(null); _globalOperation = null; // set to empty task so that we don't need a lock _globalOperationTask = Task.CompletedTask; } public virtual void Shutdown() { _globalOperationNotificationService.Started -= OnGlobalOperationStarted; _globalOperationNotificationService.Stopped -= OnGlobalOperationStopped; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Shared.TestHooks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal abstract class GlobalOperationAwareIdleProcessor : IdleProcessor { private readonly IGlobalOperationNotificationService _globalOperationNotificationService; private TaskCompletionSource<object?>? _globalOperation; private Task _globalOperationTask; public GlobalOperationAwareIdleProcessor( IAsynchronousOperationListener listener, IGlobalOperationNotificationService globalOperationNotificationService, TimeSpan backOffTimeSpan, CancellationToken shutdownToken) : base(listener, backOffTimeSpan, shutdownToken) { _globalOperation = null; _globalOperationTask = Task.CompletedTask; _globalOperationNotificationService = globalOperationNotificationService; _globalOperationNotificationService.Started += OnGlobalOperationStarted; _globalOperationNotificationService.Stopped += OnGlobalOperationStopped; } protected Task GlobalOperationTask => _globalOperationTask; protected abstract void PauseOnGlobalOperation(); private void OnGlobalOperationStarted(object? sender, EventArgs e) { Contract.ThrowIfFalse(_globalOperation == null); // events are serialized. no lock is needed _globalOperation = new TaskCompletionSource<object?>(); _globalOperationTask = _globalOperation.Task; PauseOnGlobalOperation(); } private void OnGlobalOperationStopped(object? sender, GlobalOperationEventArgs e) { if (_globalOperation == null) { // we subscribed to the event while it is already running. return; } // events are serialized. no lock is needed _globalOperation.SetResult(null); _globalOperation = null; // set to empty task so that we don't need a lock _globalOperationTask = Task.CompletedTask; } public virtual void Shutdown() { _globalOperationNotificationService.Started -= OnGlobalOperationStarted; _globalOperationNotificationService.Stopped -= OnGlobalOperationStopped; } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpExtractMethod.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpExtractMethod : AbstractEditorTest { private const string TestSource = @" using System; public class Program { public int Method() { Console.WriteLine(""Hello World""); int a; int b; a = 5; b = 10; int result = a * b; return result; } }"; protected override string LanguageName => LanguageNames.CSharp; public CSharpExtractMethod(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpExtractMethod)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public void SimpleExtractMethod() { VisualStudio.Editor.SetText(TestSource); VisualStudio.Editor.PlaceCaret("Console", charsOffset: -1); VisualStudio.Editor.PlaceCaret("World", charsOffset: 4, extendSelection: true); VisualStudio.ExecuteCommand(WellKnownCommandNames.Refactor_ExtractMethod); var expectedMarkup = @" using System; public class Program { public int Method() { [|NewMethod|](); int a; int b; a = 5; b = 10; int result = a * b; return result; } private static void [|NewMethod|]() { Console.WriteLine(""Hello World""); } }"; MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out ImmutableArray<TextSpan> spans); VisualStudio.Editor.Verify.TextContains(expectedText); AssertEx.SetEqual(spans, VisualStudio.Editor.GetTagSpans(VisualStudio.InlineRenameDialog.ValidRenameTag)); VisualStudio.Editor.SendKeys("SayHello", VirtualKey.Enter); VisualStudio.Editor.Verify.TextContains(@"private static void SayHello() { Console.WriteLine(""Hello World""); }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public void ExtractViaCodeAction() { VisualStudio.Editor.SetText(TestSource); VisualStudio.Editor.PlaceCaret("a = 5", charsOffset: -1); VisualStudio.Editor.PlaceCaret("a * b", charsOffset: 1, extendSelection: true); VisualStudio.Editor.Verify.CodeAction("Extract method", applyFix: true, blockUntilComplete: true); var expectedMarkup = @" using System; public class Program { public int Method() { Console.WriteLine(""Hello World""); int a; int b; int result; [|NewMethod|](out a, out b, out result); return result; } private static void [|NewMethod|](out int a, out int b, out int result) { a = 5; b = 10; result = a * b; } }"; MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out ImmutableArray<TextSpan> spans); Assert.Equal(expectedText, VisualStudio.Editor.GetText()); AssertEx.SetEqual(spans, VisualStudio.Editor.GetTagSpans(VisualStudio.InlineRenameDialog.ValidRenameTag)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpExtractMethod : AbstractEditorTest { private const string TestSource = @" using System; public class Program { public int Method() { Console.WriteLine(""Hello World""); int a; int b; a = 5; b = 10; int result = a * b; return result; } }"; protected override string LanguageName => LanguageNames.CSharp; public CSharpExtractMethod(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpExtractMethod)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public void SimpleExtractMethod() { VisualStudio.Editor.SetText(TestSource); VisualStudio.Editor.PlaceCaret("Console", charsOffset: -1); VisualStudio.Editor.PlaceCaret("World", charsOffset: 4, extendSelection: true); VisualStudio.ExecuteCommand(WellKnownCommandNames.Refactor_ExtractMethod); var expectedMarkup = @" using System; public class Program { public int Method() { [|NewMethod|](); int a; int b; a = 5; b = 10; int result = a * b; return result; } private static void [|NewMethod|]() { Console.WriteLine(""Hello World""); } }"; MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out ImmutableArray<TextSpan> spans); VisualStudio.Editor.Verify.TextContains(expectedText); AssertEx.SetEqual(spans, VisualStudio.Editor.GetTagSpans(VisualStudio.InlineRenameDialog.ValidRenameTag)); VisualStudio.Editor.SendKeys("SayHello", VirtualKey.Enter); VisualStudio.Editor.Verify.TextContains(@"private static void SayHello() { Console.WriteLine(""Hello World""); }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.ExtractMethod)] public void ExtractViaCodeAction() { VisualStudio.Editor.SetText(TestSource); VisualStudio.Editor.PlaceCaret("a = 5", charsOffset: -1); VisualStudio.Editor.PlaceCaret("a * b", charsOffset: 1, extendSelection: true); VisualStudio.Editor.Verify.CodeAction("Extract method", applyFix: true, blockUntilComplete: true); var expectedMarkup = @" using System; public class Program { public int Method() { Console.WriteLine(""Hello World""); int a; int b; int result; [|NewMethod|](out a, out b, out result); return result; } private static void [|NewMethod|](out int a, out int b, out int result) { a = 5; b = 10; result = a * b; } }"; MarkupTestFile.GetSpans(expectedMarkup, out var expectedText, out ImmutableArray<TextSpan> spans); Assert.Equal(expectedText, VisualStudio.Editor.GetText()); AssertEx.SetEqual(spans, VisualStudio.Editor.GetTagSpans(VisualStudio.InlineRenameDialog.ValidRenameTag)); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/Core/Portable/SourceGeneration/GeneratorAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 { /// <summary> /// Place this attribute onto a type to cause it to be considered a source generator /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class GeneratorAttribute : Attribute { /// <summary> /// The source languages to which this generator applies. See <see cref="LanguageNames"/>. /// </summary> public string[] Languages { get; } /// <summary> /// Attribute constructor used to specify the attached class is a source generator that provides CSharp sources. /// </summary> public GeneratorAttribute() : this(LanguageNames.CSharp) { } /// <summary> /// Attribute constructor used to specify the attached class is a source generator and indicate which language(s) it supports. /// </summary> /// <param name="firstLanguage">One language to which the generator applies.</param> /// <param name="additionalLanguages">Additional languages to which the generator applies. See <see cref="LanguageNames"/>.</param> public GeneratorAttribute(string firstLanguage, params string[] additionalLanguages) { if (firstLanguage == null) { throw new ArgumentNullException(nameof(firstLanguage)); } if (additionalLanguages == null) { throw new ArgumentNullException(nameof(additionalLanguages)); } var languages = new string[additionalLanguages.Length + 1]; languages[0] = firstLanguage; for (int index = 0; index < additionalLanguages.Length; index++) { languages[index + 1] = additionalLanguages[index]; } this.Languages = languages; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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 { /// <summary> /// Place this attribute onto a type to cause it to be considered a source generator /// </summary> [AttributeUsage(AttributeTargets.Class)] public sealed class GeneratorAttribute : Attribute { /// <summary> /// The source languages to which this generator applies. See <see cref="LanguageNames"/>. /// </summary> public string[] Languages { get; } /// <summary> /// Attribute constructor used to specify the attached class is a source generator that provides CSharp sources. /// </summary> public GeneratorAttribute() : this(LanguageNames.CSharp) { } /// <summary> /// Attribute constructor used to specify the attached class is a source generator and indicate which language(s) it supports. /// </summary> /// <param name="firstLanguage">One language to which the generator applies.</param> /// <param name="additionalLanguages">Additional languages to which the generator applies. See <see cref="LanguageNames"/>.</param> public GeneratorAttribute(string firstLanguage, params string[] additionalLanguages) { if (firstLanguage == null) { throw new ArgumentNullException(nameof(firstLanguage)); } if (additionalLanguages == null) { throw new ArgumentNullException(nameof(additionalLanguages)); } var languages = new string[additionalLanguages.Length + 1]; languages[0] = firstLanguage; for (int index = 0; index < additionalLanguages.Length; index++) { languages[index + 1] = additionalLanguages[index]; } this.Languages = languages; } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Workspaces/Core/Portable/Storage/SQLite/AbstractSQLitePersistentStorageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Storage; namespace Microsoft.CodeAnalysis.SQLite { /// <summary> /// Base type <see cref="v2.SQLitePersistentStorageService"/>. Used as a common location for the common static /// helpers to load the sqlite pcl library. /// </summary> internal abstract class AbstractSQLitePersistentStorageService : AbstractPersistentStorageService { protected static bool TryInitializeLibraries() => s_initialized.Value; private static readonly Lazy<bool> s_initialized = new(() => TryInitializeLibrariesLazy()); private static bool TryInitializeLibrariesLazy() { try { // Necessary to initialize SQLitePCL. SQLitePCL.Batteries_V2.Init(); } catch (Exception e) when (e is DllNotFoundException or EntryPointNotFoundException) { StorageDatabaseLogger.LogException(e); return false; } return true; } protected AbstractSQLitePersistentStorageService(IPersistentStorageConfiguration configuration) : base(configuration) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Storage; namespace Microsoft.CodeAnalysis.SQLite { /// <summary> /// Base type <see cref="v2.SQLitePersistentStorageService"/>. Used as a common location for the common static /// helpers to load the sqlite pcl library. /// </summary> internal abstract class AbstractSQLitePersistentStorageService : AbstractPersistentStorageService { protected static bool TryInitializeLibraries() => s_initialized.Value; private static readonly Lazy<bool> s_initialized = new(() => TryInitializeLibrariesLazy()); private static bool TryInitializeLibrariesLazy() { try { // Necessary to initialize SQLitePCL. SQLitePCL.Batteries_V2.Init(); } catch (Exception e) when (e is DllNotFoundException or EntryPointNotFoundException) { StorageDatabaseLogger.LogException(e); return false; } return true; } protected AbstractSQLitePersistentStorageService(IPersistentStorageConfiguration configuration) : base(configuration) { } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Features/Core/Portable/BraceCompletion/IBraceCompletionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.BraceCompletion { internal interface IBraceCompletionService : ILanguageService { /// <summary> /// Checks if this brace completion service should be the service used to provide brace completions at /// the specified position with the specified opening brace. /// /// Only one implementation of <see cref="IBraceCompletionService"/> should return true /// for a given brace, opening position, and document. Only that service will be asked /// for brace completion results. /// </summary> /// <param name="brace"> /// The opening brace character to be inserted at the opening position.</param> /// <param name="openingPosition"> /// The opening position to insert the brace. /// Note that the brace is not yet inserted at this position in the document. /// </param> /// <param name="document">The document to insert the brace at the position.</param> /// <param name="cancellationToken">A cancellation token.</param> Task<bool> CanProvideBraceCompletionAsync(char brace, int openingPosition, Document document, CancellationToken cancellationToken); /// <summary> /// Returns the text change to add the closing brace given the context. /// </summary> Task<BraceCompletionResult?> GetBraceCompletionAsync(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken); /// <summary> /// Returns any text changes that need to be made after adding the closing brace. /// </summary> /// <remarks> /// This cannot be merged with <see cref="GetBraceCompletionAsync(BraceCompletionContext, CancellationToken)"/> /// as we need to swap the editor tracking mode of the closing point from positive to negative /// in BraceCompletionSessionProvider.BraceCompletionSession.Start after completing the brace and before /// doing any kind of formatting on it. So these must be two distinct steps until we fully move to LSP. /// </remarks> Task<BraceCompletionResult?> GetTextChangesAfterCompletionAsync(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken); /// <summary> /// Get any text changes that should be applied after the enter key is typed inside a brace completion context. /// </summary> Task<BraceCompletionResult?> GetTextChangeAfterReturnAsync(BraceCompletionContext braceCompletionContext, DocumentOptionSet documentOptions, CancellationToken cancellationToken); /// <summary> /// Returns the brace completion context if the caret is located between an already completed /// set of braces with only whitespace in between. /// </summary> Task<BraceCompletionContext?> GetCompletedBraceContextAsync(Document document, int caretLocation, CancellationToken cancellationToken); /// <summary> /// Returns true if over typing should be allowed given the caret location and completed pair of braces. /// For example some providers allow over typing in non-user code and others do not. /// </summary> Task<bool> AllowOverTypeAsync(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken); } internal readonly struct BraceCompletionResult { /// <summary> /// The set of text changes that should be applied to the input text to retrieve the /// brace completion result. /// </summary> public ImmutableArray<TextChange> TextChanges { get; } /// <summary> /// The caret location in the new text created by applying all <see cref="TextChanges"/> /// to the input text. Note the column in the line position can be virtual in that it points /// to a location in the line which does not actually contain whitespace. /// Hosts can determine how best to handle that virtual location. /// For example, placing the character in virtual space (when suppported) /// or inserting an appropriate number of spaces into the document". /// </summary> public LinePosition CaretLocation { get; } public BraceCompletionResult(ImmutableArray<TextChange> textChanges, LinePosition caretLocation) { CaretLocation = caretLocation; TextChanges = textChanges; } } internal readonly struct BraceCompletionContext { public Document Document { get; } public int OpeningPoint { get; } public int ClosingPoint { get; } public int CaretLocation { get; } public BraceCompletionContext(Document document, int openingPoint, int closingPoint, int caretLocation) { Document = document; OpeningPoint = openingPoint; ClosingPoint = closingPoint; CaretLocation = caretLocation; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.BraceCompletion { internal interface IBraceCompletionService : ILanguageService { /// <summary> /// Checks if this brace completion service should be the service used to provide brace completions at /// the specified position with the specified opening brace. /// /// Only one implementation of <see cref="IBraceCompletionService"/> should return true /// for a given brace, opening position, and document. Only that service will be asked /// for brace completion results. /// </summary> /// <param name="brace"> /// The opening brace character to be inserted at the opening position.</param> /// <param name="openingPosition"> /// The opening position to insert the brace. /// Note that the brace is not yet inserted at this position in the document. /// </param> /// <param name="document">The document to insert the brace at the position.</param> /// <param name="cancellationToken">A cancellation token.</param> Task<bool> CanProvideBraceCompletionAsync(char brace, int openingPosition, Document document, CancellationToken cancellationToken); /// <summary> /// Returns the text change to add the closing brace given the context. /// </summary> Task<BraceCompletionResult?> GetBraceCompletionAsync(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken); /// <summary> /// Returns any text changes that need to be made after adding the closing brace. /// </summary> /// <remarks> /// This cannot be merged with <see cref="GetBraceCompletionAsync(BraceCompletionContext, CancellationToken)"/> /// as we need to swap the editor tracking mode of the closing point from positive to negative /// in BraceCompletionSessionProvider.BraceCompletionSession.Start after completing the brace and before /// doing any kind of formatting on it. So these must be two distinct steps until we fully move to LSP. /// </remarks> Task<BraceCompletionResult?> GetTextChangesAfterCompletionAsync(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken); /// <summary> /// Get any text changes that should be applied after the enter key is typed inside a brace completion context. /// </summary> Task<BraceCompletionResult?> GetTextChangeAfterReturnAsync(BraceCompletionContext braceCompletionContext, DocumentOptionSet documentOptions, CancellationToken cancellationToken); /// <summary> /// Returns the brace completion context if the caret is located between an already completed /// set of braces with only whitespace in between. /// </summary> Task<BraceCompletionContext?> GetCompletedBraceContextAsync(Document document, int caretLocation, CancellationToken cancellationToken); /// <summary> /// Returns true if over typing should be allowed given the caret location and completed pair of braces. /// For example some providers allow over typing in non-user code and others do not. /// </summary> Task<bool> AllowOverTypeAsync(BraceCompletionContext braceCompletionContext, CancellationToken cancellationToken); } internal readonly struct BraceCompletionResult { /// <summary> /// The set of text changes that should be applied to the input text to retrieve the /// brace completion result. /// </summary> public ImmutableArray<TextChange> TextChanges { get; } /// <summary> /// The caret location in the new text created by applying all <see cref="TextChanges"/> /// to the input text. Note the column in the line position can be virtual in that it points /// to a location in the line which does not actually contain whitespace. /// Hosts can determine how best to handle that virtual location. /// For example, placing the character in virtual space (when suppported) /// or inserting an appropriate number of spaces into the document". /// </summary> public LinePosition CaretLocation { get; } public BraceCompletionResult(ImmutableArray<TextChange> textChanges, LinePosition caretLocation) { CaretLocation = caretLocation; TextChanges = textChanges; } } internal readonly struct BraceCompletionContext { public Document Document { get; } public int OpeningPoint { get; } public int ClosingPoint { get; } public int CaretLocation { get; } public BraceCompletionContext(Document document, int openingPoint, int closingPoint, int caretLocation) { Document = document; OpeningPoint = openingPoint; ClosingPoint = closingPoint; CaretLocation = caretLocation; } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/Core/Portable/DiaSymReader/Writer/ISymUnmanagedWriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #pragma warning disable 436 // SuppressUnmanagedCodeSecurityAttribute defined in source and mscorlib using System; using System.Runtime.InteropServices; using System.Security; namespace Microsoft.DiaSymReader { [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("98ECEE1E-752D-11d3-8D56-00C04F680B2B"), SuppressUnmanagedCodeSecurity] internal interface IPdbWriter { int __SetPath(/*[in] const WCHAR* szFullPathName, [in] IStream* pIStream, [in] BOOL fFullBuild*/); int __OpenMod(/*[in] const WCHAR* szModuleName, [in] const WCHAR* szFileName*/); int __CloseMod(); int __GetPath(/*[in] DWORD ccData,[out] DWORD* pccData,[out, size_is(ccData),length_is(*pccData)] WCHAR szPath[]*/); void GetSignatureAge(out uint sig, out int age); } /// <summary> /// The highest version of the interface available on Desktop FX 4.0+. /// </summary> [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("DCF7780D-BDE9-45DF-ACFE-21731A32000C"), SuppressUnmanagedCodeSecurity] internal unsafe interface ISymUnmanagedWriter5 { #region ISymUnmanagedWriter ISymUnmanagedDocumentWriter DefineDocument(string url, ref Guid language, ref Guid languageVendor, ref Guid documentType); void SetUserEntryPoint(int entryMethodToken); void OpenMethod(uint methodToken); void CloseMethod(); uint OpenScope(int startOffset); void CloseScope(int endOffset); void SetScopeRange(uint scopeID, uint startOffset, uint endOffset); void DefineLocalVariable(string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint startOffset, uint endOffset); void DefineParameter(string name, uint attributes, uint sequence, uint addrKind, uint addr1, uint addr2, uint addr3); void DefineField(uint parent, string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint addr3); void DefineGlobalVariable(string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint addr3); void Close(); void SetSymAttribute(uint parent, string name, int length, byte* data); void OpenNamespace(string name); void CloseNamespace(); void UsingNamespace(string fullName); void SetMethodSourceRange(ISymUnmanagedDocumentWriter startDoc, uint startLine, uint startColumn, object endDoc, uint endLine, uint endColumn); void Initialize([MarshalAs(UnmanagedType.IUnknown)] object emitter, string filename, [MarshalAs(UnmanagedType.IUnknown)] object ptrIStream, bool fullBuild); void GetDebugInfo(ref ImageDebugDirectory debugDirectory, uint dataCount, out uint dataCountPtr, byte* data); void DefineSequencePoints(ISymUnmanagedDocumentWriter document, int count, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] offsets, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] lines, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] columns, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endLines, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endColumns); void RemapToken(uint oldToken, uint newToken); void Initialize2([MarshalAs(UnmanagedType.IUnknown)] object emitter, string tempfilename, [MarshalAs(UnmanagedType.IUnknown)] object ptrIStream, bool fullBuild, string finalfilename); void DefineConstant(string name, object value, uint sig, byte* signature); void Abort(); #endregion #region ISymUnmanagedWriter2 void DefineLocalVariable2(string name, int attributes, int localSignatureToken, uint addrKind, int index, uint addr2, uint addr3, uint startOffset, uint endOffset); void DefineGlobalVariable2(string name, int attributes, int sigToken, uint addrKind, uint addr1, uint addr2, uint addr3); /// <remarks> /// <paramref name="value"/> has type <see cref="VariantStructure"/>, rather than <see cref="object"/>, /// so that we can do custom marshalling of <see cref="System.DateTime"/>. Unfortunately, .NET marshals /// <see cref="System.DateTime"/>s as the number of days since 1899/12/30, whereas the native VB compiler /// marshalled them as the number of ticks since the Unix epoch (i.e. a much, much larger number). /// </remarks> void DefineConstant2([MarshalAs(UnmanagedType.LPWStr)] string name, VariantStructure value, int constantSignatureToken); #endregion #region ISymUnmanagedWriter3 void OpenMethod2(uint methodToken, int sectionIndex, int offsetRelativeOffset); void Commit(); #endregion #region ISymUnmanagedWriter4 void GetDebugInfoWithPadding(ref ImageDebugDirectory debugDirectory, uint dataCount, out uint dataCountPtr, byte* data); #endregion #region ISymUnmanagedWriter5 /// <summary> /// Open a special custom data section to emit token to source span mapping information into. /// Opening this section while a method is already open or vice versa is an error. /// </summary> void OpenMapTokensToSourceSpans(); /// <summary> /// Close the special custom data section for token to source span mapping /// information. Once it is closed no more mapping information can be added. /// </summary> void CloseMapTokensToSourceSpans(); /// <summary> /// Maps the given metadata token to the given source line span in the specified source file. /// Must be called between calls to <see cref="OpenMapTokensToSourceSpans"/> and <see cref="CloseMapTokensToSourceSpans"/>. /// </summary> void MapTokenToSourceSpan(int token, ISymUnmanagedDocumentWriter document, int startLine, int startColumn, int endLine, int endColumn); #endregion } /// <summary> /// The highest version of the interface available in Microsoft.DiaSymReader.Native. /// </summary> [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("5ba52f3b-6bf8-40fc-b476-d39c529b331e"), SuppressUnmanagedCodeSecurity] internal interface ISymUnmanagedWriter8 : ISymUnmanagedWriter5 { // ISymUnmanagedWriter, ISymUnmanagedWriter2, ISymUnmanagedWriter3, ISymUnmanagedWriter4, ISymUnmanagedWriter5 void _VtblGap1_33(); // ISymUnmanagedWriter6 void InitializeDeterministic([MarshalAs(UnmanagedType.IUnknown)] object emitter, [MarshalAs(UnmanagedType.IUnknown)] object stream); // ISymUnmanagedWriter7 unsafe void UpdateSignatureByHashingContent([In] byte* buffer, int size); // ISymUnmanagedWriter8 void UpdateSignature(Guid pdbId, uint stamp, int age); unsafe void SetSourceServerData([In] byte* data, int size); unsafe void SetSourceLinkData([In] byte* data, int size); } /// <summary> /// A struct with the same size and layout as the native VARIANT type: /// 2 bytes for a discriminator (i.e. which type of variant it is). /// 6 bytes of padding /// 8 or 16 bytes of data /// </summary> [StructLayout(LayoutKind.Explicit)] internal struct VariantStructure { public VariantStructure(DateTime date) : this() // Need this to avoid errors about the uninteresting union fields. { _longValue = date.Ticks; #pragma warning disable CS0618 // Type or member is obsolete _type = (short)VarEnum.VT_DATE; #pragma warning restore CS0618 } [FieldOffset(0)] private readonly short _type; [FieldOffset(8)] private readonly long _longValue; /// <summary> /// This field determines the size of the struct /// (16 bytes on 32-bit platforms, 24 bytes on 64-bit platforms). /// </summary> [FieldOffset(8)] private readonly VariantPadding _padding; // Fields below this point are only used to make inspecting this struct in the debugger easier. [FieldOffset(0)] // NB: 0, not 8 private readonly decimal _decimalValue; [FieldOffset(8)] private readonly bool _boolValue; [FieldOffset(8)] private readonly long _intValue; [FieldOffset(8)] private readonly double _doubleValue; } /// <summary> /// This type is 8 bytes on a 32-bit platforms and 16 bytes on 64-bit platforms. /// </summary> [StructLayout(LayoutKind.Sequential)] internal unsafe struct VariantPadding { public readonly byte* Data2; public readonly byte* Data3; } [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct ImageDebugDirectory { internal int Characteristics; internal int TimeDateStamp; internal short MajorVersion; internal short MinorVersion; internal int Type; internal int SizeOfData; internal int AddressOfRawData; internal int PointerToRawData; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #pragma warning disable 436 // SuppressUnmanagedCodeSecurityAttribute defined in source and mscorlib using System; using System.Runtime.InteropServices; using System.Security; namespace Microsoft.DiaSymReader { [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("98ECEE1E-752D-11d3-8D56-00C04F680B2B"), SuppressUnmanagedCodeSecurity] internal interface IPdbWriter { int __SetPath(/*[in] const WCHAR* szFullPathName, [in] IStream* pIStream, [in] BOOL fFullBuild*/); int __OpenMod(/*[in] const WCHAR* szModuleName, [in] const WCHAR* szFileName*/); int __CloseMod(); int __GetPath(/*[in] DWORD ccData,[out] DWORD* pccData,[out, size_is(ccData),length_is(*pccData)] WCHAR szPath[]*/); void GetSignatureAge(out uint sig, out int age); } /// <summary> /// The highest version of the interface available on Desktop FX 4.0+. /// </summary> [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("DCF7780D-BDE9-45DF-ACFE-21731A32000C"), SuppressUnmanagedCodeSecurity] internal unsafe interface ISymUnmanagedWriter5 { #region ISymUnmanagedWriter ISymUnmanagedDocumentWriter DefineDocument(string url, ref Guid language, ref Guid languageVendor, ref Guid documentType); void SetUserEntryPoint(int entryMethodToken); void OpenMethod(uint methodToken); void CloseMethod(); uint OpenScope(int startOffset); void CloseScope(int endOffset); void SetScopeRange(uint scopeID, uint startOffset, uint endOffset); void DefineLocalVariable(string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint startOffset, uint endOffset); void DefineParameter(string name, uint attributes, uint sequence, uint addrKind, uint addr1, uint addr2, uint addr3); void DefineField(uint parent, string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint addr3); void DefineGlobalVariable(string name, uint attributes, uint sig, byte* signature, uint addrKind, uint addr1, uint addr2, uint addr3); void Close(); void SetSymAttribute(uint parent, string name, int length, byte* data); void OpenNamespace(string name); void CloseNamespace(); void UsingNamespace(string fullName); void SetMethodSourceRange(ISymUnmanagedDocumentWriter startDoc, uint startLine, uint startColumn, object endDoc, uint endLine, uint endColumn); void Initialize([MarshalAs(UnmanagedType.IUnknown)] object emitter, string filename, [MarshalAs(UnmanagedType.IUnknown)] object ptrIStream, bool fullBuild); void GetDebugInfo(ref ImageDebugDirectory debugDirectory, uint dataCount, out uint dataCountPtr, byte* data); void DefineSequencePoints(ISymUnmanagedDocumentWriter document, int count, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] offsets, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] lines, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] columns, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endLines, [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] endColumns); void RemapToken(uint oldToken, uint newToken); void Initialize2([MarshalAs(UnmanagedType.IUnknown)] object emitter, string tempfilename, [MarshalAs(UnmanagedType.IUnknown)] object ptrIStream, bool fullBuild, string finalfilename); void DefineConstant(string name, object value, uint sig, byte* signature); void Abort(); #endregion #region ISymUnmanagedWriter2 void DefineLocalVariable2(string name, int attributes, int localSignatureToken, uint addrKind, int index, uint addr2, uint addr3, uint startOffset, uint endOffset); void DefineGlobalVariable2(string name, int attributes, int sigToken, uint addrKind, uint addr1, uint addr2, uint addr3); /// <remarks> /// <paramref name="value"/> has type <see cref="VariantStructure"/>, rather than <see cref="object"/>, /// so that we can do custom marshalling of <see cref="System.DateTime"/>. Unfortunately, .NET marshals /// <see cref="System.DateTime"/>s as the number of days since 1899/12/30, whereas the native VB compiler /// marshalled them as the number of ticks since the Unix epoch (i.e. a much, much larger number). /// </remarks> void DefineConstant2([MarshalAs(UnmanagedType.LPWStr)] string name, VariantStructure value, int constantSignatureToken); #endregion #region ISymUnmanagedWriter3 void OpenMethod2(uint methodToken, int sectionIndex, int offsetRelativeOffset); void Commit(); #endregion #region ISymUnmanagedWriter4 void GetDebugInfoWithPadding(ref ImageDebugDirectory debugDirectory, uint dataCount, out uint dataCountPtr, byte* data); #endregion #region ISymUnmanagedWriter5 /// <summary> /// Open a special custom data section to emit token to source span mapping information into. /// Opening this section while a method is already open or vice versa is an error. /// </summary> void OpenMapTokensToSourceSpans(); /// <summary> /// Close the special custom data section for token to source span mapping /// information. Once it is closed no more mapping information can be added. /// </summary> void CloseMapTokensToSourceSpans(); /// <summary> /// Maps the given metadata token to the given source line span in the specified source file. /// Must be called between calls to <see cref="OpenMapTokensToSourceSpans"/> and <see cref="CloseMapTokensToSourceSpans"/>. /// </summary> void MapTokenToSourceSpan(int token, ISymUnmanagedDocumentWriter document, int startLine, int startColumn, int endLine, int endColumn); #endregion } /// <summary> /// The highest version of the interface available in Microsoft.DiaSymReader.Native. /// </summary> [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("5ba52f3b-6bf8-40fc-b476-d39c529b331e"), SuppressUnmanagedCodeSecurity] internal interface ISymUnmanagedWriter8 : ISymUnmanagedWriter5 { // ISymUnmanagedWriter, ISymUnmanagedWriter2, ISymUnmanagedWriter3, ISymUnmanagedWriter4, ISymUnmanagedWriter5 void _VtblGap1_33(); // ISymUnmanagedWriter6 void InitializeDeterministic([MarshalAs(UnmanagedType.IUnknown)] object emitter, [MarshalAs(UnmanagedType.IUnknown)] object stream); // ISymUnmanagedWriter7 unsafe void UpdateSignatureByHashingContent([In] byte* buffer, int size); // ISymUnmanagedWriter8 void UpdateSignature(Guid pdbId, uint stamp, int age); unsafe void SetSourceServerData([In] byte* data, int size); unsafe void SetSourceLinkData([In] byte* data, int size); } /// <summary> /// A struct with the same size and layout as the native VARIANT type: /// 2 bytes for a discriminator (i.e. which type of variant it is). /// 6 bytes of padding /// 8 or 16 bytes of data /// </summary> [StructLayout(LayoutKind.Explicit)] internal struct VariantStructure { public VariantStructure(DateTime date) : this() // Need this to avoid errors about the uninteresting union fields. { _longValue = date.Ticks; #pragma warning disable CS0618 // Type or member is obsolete _type = (short)VarEnum.VT_DATE; #pragma warning restore CS0618 } [FieldOffset(0)] private readonly short _type; [FieldOffset(8)] private readonly long _longValue; /// <summary> /// This field determines the size of the struct /// (16 bytes on 32-bit platforms, 24 bytes on 64-bit platforms). /// </summary> [FieldOffset(8)] private readonly VariantPadding _padding; // Fields below this point are only used to make inspecting this struct in the debugger easier. [FieldOffset(0)] // NB: 0, not 8 private readonly decimal _decimalValue; [FieldOffset(8)] private readonly bool _boolValue; [FieldOffset(8)] private readonly long _intValue; [FieldOffset(8)] private readonly double _doubleValue; } /// <summary> /// This type is 8 bytes on a 32-bit platforms and 16 bytes on 64-bit platforms. /// </summary> [StructLayout(LayoutKind.Sequential)] internal unsafe struct VariantPadding { public readonly byte* Data2; public readonly byte* Data3; } [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct ImageDebugDirectory { internal int Characteristics; internal int TimeDateStamp; internal short MajorVersion; internal short MinorVersion; internal int Type; internal int SizeOfData; internal int AddressOfRawData; internal int PointerToRawData; } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/CSharp/Portable/BoundTree/NullabilityRewriter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class NullabilityRewriter : BoundTreeRewriter { protected override BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node) { return (BoundExpression)Visit(node); } public override BoundNode? VisitBinaryOperator(BoundBinaryOperator node) { return VisitBinaryOperatorBase(node); } public override BoundNode? VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { return VisitBinaryOperatorBase(node); } private BoundNode VisitBinaryOperatorBase(BoundBinaryOperatorBase binaryOperator) { // Use an explicit stack to avoid blowing the managed stack when visiting deeply-recursive // binary nodes var stack = ArrayBuilder<BoundBinaryOperatorBase>.GetInstance(); BoundBinaryOperatorBase? currentBinary = binaryOperator; do { stack.Push(currentBinary); currentBinary = currentBinary.Left as BoundBinaryOperatorBase; } while (currentBinary is not null); Debug.Assert(stack.Count > 0); var leftChild = (BoundExpression)Visit(stack.Peek().Left); do { currentBinary = stack.Pop(); bool foundInfo = _updatedNullabilities.TryGetValue(currentBinary, out (NullabilityInfo Info, TypeSymbol? Type) infoAndType); var right = (BoundExpression)Visit(currentBinary.Right); var type = foundInfo ? infoAndType.Type : currentBinary.Type; currentBinary = currentBinary switch { BoundBinaryOperator binary => binary.Update( binary.OperatorKind, binary.Data?.WithUpdatedMethod(GetUpdatedSymbol(binary, binary.Method)), binary.ResultKind, leftChild, right, type!), // https://github.com/dotnet/roslyn/issues/35031: We'll need to update logical.LogicalOperator BoundUserDefinedConditionalLogicalOperator logical => logical.Update(logical.OperatorKind, logical.LogicalOperator, logical.TrueOperator, logical.FalseOperator, logical.ConstrainedToTypeOpt, logical.ResultKind, logical.OriginalUserDefinedOperatorsOpt, leftChild, right, type!), _ => throw ExceptionUtilities.UnexpectedValue(currentBinary.Kind), }; if (foundInfo) { currentBinary.TopLevelNullability = infoAndType.Info; } leftChild = currentBinary; } while (stack.Count > 0); Debug.Assert(currentBinary != null); return currentBinary!; } private T GetUpdatedSymbol<T>(BoundNode expr, T sym) where T : Symbol? { if (sym is null) return sym; Symbol? updatedSymbol = null; if (_snapshotManager?.TryGetUpdatedSymbol(expr, sym, out updatedSymbol) != true) { updatedSymbol = sym; } RoslynDebug.Assert(updatedSymbol is object); switch (updatedSymbol) { case LambdaSymbol lambda: return (T)remapLambda((BoundLambda)expr, lambda); case SourceLocalSymbol local: return (T)remapLocal(local); case ParameterSymbol param: if (_remappedSymbols.TryGetValue(param, out var updatedParam)) { return (T)updatedParam; } break; } return (T)updatedSymbol; Symbol remapLambda(BoundLambda boundLambda, LambdaSymbol lambda) { var updatedDelegateType = _snapshotManager?.GetUpdatedDelegateTypeForLambda(lambda); if (!_remappedSymbols.TryGetValue(lambda.ContainingSymbol, out Symbol? updatedContaining) && updatedDelegateType is null) { return lambda; } LambdaSymbol updatedLambda; if (updatedDelegateType is null) { Debug.Assert(updatedContaining is object); updatedLambda = boundLambda.CreateLambdaSymbol(updatedContaining, lambda.ReturnTypeWithAnnotations, lambda.ParameterTypesWithAnnotations, lambda.ParameterRefKinds, lambda.RefKind); } else { Debug.Assert(updatedDelegateType is object); updatedLambda = boundLambda.CreateLambdaSymbol(updatedDelegateType, updatedContaining ?? lambda.ContainingSymbol); } _remappedSymbols.Add(lambda, updatedLambda); Debug.Assert(lambda.ParameterCount == updatedLambda.ParameterCount); for (int i = 0; i < lambda.ParameterCount; i++) { _remappedSymbols.Add(lambda.Parameters[i], updatedLambda.Parameters[i]); } return updatedLambda; } Symbol remapLocal(SourceLocalSymbol local) { if (_remappedSymbols.TryGetValue(local, out var updatedLocal)) { return updatedLocal; } var updatedType = _snapshotManager?.GetUpdatedTypeForLocalSymbol(local); if (!_remappedSymbols.TryGetValue(local.ContainingSymbol, out Symbol? updatedContaining) && !updatedType.HasValue) { // Map the local to itself so we don't have to search again in the future _remappedSymbols.Add(local, local); return local; } updatedLocal = new UpdatedContainingSymbolAndNullableAnnotationLocal(local, updatedContaining ?? local.ContainingSymbol, updatedType ?? local.TypeWithAnnotations); _remappedSymbols.Add(local, updatedLocal); return updatedLocal; } } private ImmutableArray<T> GetUpdatedArray<T>(BoundNode expr, ImmutableArray<T> symbols) where T : Symbol? { if (symbols.IsDefaultOrEmpty) { return symbols; } var builder = ArrayBuilder<T>.GetInstance(symbols.Length); bool foundUpdate = false; foreach (var originalSymbol in symbols) { T updatedSymbol = null!; if (originalSymbol is object) { updatedSymbol = GetUpdatedSymbol(expr, originalSymbol); Debug.Assert(updatedSymbol is object); if ((object)originalSymbol != updatedSymbol) { foundUpdate = true; } } builder.Add(updatedSymbol); } if (foundUpdate) { return builder.ToImmutableAndFree(); } else { builder.Free(); return symbols; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class NullabilityRewriter : BoundTreeRewriter { protected override BoundExpression? VisitExpressionWithoutStackGuard(BoundExpression node) { return (BoundExpression)Visit(node); } public override BoundNode? VisitBinaryOperator(BoundBinaryOperator node) { return VisitBinaryOperatorBase(node); } public override BoundNode? VisitUserDefinedConditionalLogicalOperator(BoundUserDefinedConditionalLogicalOperator node) { return VisitBinaryOperatorBase(node); } private BoundNode VisitBinaryOperatorBase(BoundBinaryOperatorBase binaryOperator) { // Use an explicit stack to avoid blowing the managed stack when visiting deeply-recursive // binary nodes var stack = ArrayBuilder<BoundBinaryOperatorBase>.GetInstance(); BoundBinaryOperatorBase? currentBinary = binaryOperator; do { stack.Push(currentBinary); currentBinary = currentBinary.Left as BoundBinaryOperatorBase; } while (currentBinary is not null); Debug.Assert(stack.Count > 0); var leftChild = (BoundExpression)Visit(stack.Peek().Left); do { currentBinary = stack.Pop(); bool foundInfo = _updatedNullabilities.TryGetValue(currentBinary, out (NullabilityInfo Info, TypeSymbol? Type) infoAndType); var right = (BoundExpression)Visit(currentBinary.Right); var type = foundInfo ? infoAndType.Type : currentBinary.Type; currentBinary = currentBinary switch { BoundBinaryOperator binary => binary.Update( binary.OperatorKind, binary.Data?.WithUpdatedMethod(GetUpdatedSymbol(binary, binary.Method)), binary.ResultKind, leftChild, right, type!), // https://github.com/dotnet/roslyn/issues/35031: We'll need to update logical.LogicalOperator BoundUserDefinedConditionalLogicalOperator logical => logical.Update(logical.OperatorKind, logical.LogicalOperator, logical.TrueOperator, logical.FalseOperator, logical.ConstrainedToTypeOpt, logical.ResultKind, logical.OriginalUserDefinedOperatorsOpt, leftChild, right, type!), _ => throw ExceptionUtilities.UnexpectedValue(currentBinary.Kind), }; if (foundInfo) { currentBinary.TopLevelNullability = infoAndType.Info; } leftChild = currentBinary; } while (stack.Count > 0); Debug.Assert(currentBinary != null); return currentBinary!; } private T GetUpdatedSymbol<T>(BoundNode expr, T sym) where T : Symbol? { if (sym is null) return sym; Symbol? updatedSymbol = null; if (_snapshotManager?.TryGetUpdatedSymbol(expr, sym, out updatedSymbol) != true) { updatedSymbol = sym; } RoslynDebug.Assert(updatedSymbol is object); switch (updatedSymbol) { case LambdaSymbol lambda: return (T)remapLambda((BoundLambda)expr, lambda); case SourceLocalSymbol local: return (T)remapLocal(local); case ParameterSymbol param: if (_remappedSymbols.TryGetValue(param, out var updatedParam)) { return (T)updatedParam; } break; } return (T)updatedSymbol; Symbol remapLambda(BoundLambda boundLambda, LambdaSymbol lambda) { var updatedDelegateType = _snapshotManager?.GetUpdatedDelegateTypeForLambda(lambda); if (!_remappedSymbols.TryGetValue(lambda.ContainingSymbol, out Symbol? updatedContaining) && updatedDelegateType is null) { return lambda; } LambdaSymbol updatedLambda; if (updatedDelegateType is null) { Debug.Assert(updatedContaining is object); updatedLambda = boundLambda.CreateLambdaSymbol(updatedContaining, lambda.ReturnTypeWithAnnotations, lambda.ParameterTypesWithAnnotations, lambda.ParameterRefKinds, lambda.RefKind); } else { Debug.Assert(updatedDelegateType is object); updatedLambda = boundLambda.CreateLambdaSymbol(updatedDelegateType, updatedContaining ?? lambda.ContainingSymbol); } _remappedSymbols.Add(lambda, updatedLambda); Debug.Assert(lambda.ParameterCount == updatedLambda.ParameterCount); for (int i = 0; i < lambda.ParameterCount; i++) { _remappedSymbols.Add(lambda.Parameters[i], updatedLambda.Parameters[i]); } return updatedLambda; } Symbol remapLocal(SourceLocalSymbol local) { if (_remappedSymbols.TryGetValue(local, out var updatedLocal)) { return updatedLocal; } var updatedType = _snapshotManager?.GetUpdatedTypeForLocalSymbol(local); if (!_remappedSymbols.TryGetValue(local.ContainingSymbol, out Symbol? updatedContaining) && !updatedType.HasValue) { // Map the local to itself so we don't have to search again in the future _remappedSymbols.Add(local, local); return local; } updatedLocal = new UpdatedContainingSymbolAndNullableAnnotationLocal(local, updatedContaining ?? local.ContainingSymbol, updatedType ?? local.TypeWithAnnotations); _remappedSymbols.Add(local, updatedLocal); return updatedLocal; } } private ImmutableArray<T> GetUpdatedArray<T>(BoundNode expr, ImmutableArray<T> symbols) where T : Symbol? { if (symbols.IsDefaultOrEmpty) { return symbols; } var builder = ArrayBuilder<T>.GetInstance(symbols.Length); bool foundUpdate = false; foreach (var originalSymbol in symbols) { T updatedSymbol = null!; if (originalSymbol is object) { updatedSymbol = GetUpdatedSymbol(expr, originalSymbol); Debug.Assert(updatedSymbol is object); if ((object)originalSymbol != updatedSymbol) { foundUpdate = true; } } builder.Add(updatedSymbol); } if (foundUpdate) { return builder.ToImmutableAndFree(); } else { builder.Free(); return symbols; } } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/EditorFeatures/Core/Shared/Extensions/IContentTypeExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class IContentTypeExtensions { /// <summary> /// Test whether an extension matches a content type. /// </summary> /// <param name="dataContentType">Content type (typically of a text buffer) against which to /// match an extension.</param> /// <param name="extensionContentTypes">Content types from extension metadata.</param> public static bool MatchesAny(this IContentType dataContentType, IEnumerable<string> extensionContentTypes) => extensionContentTypes.Any(v => dataContentType.IsOfType(v)); public static bool MatchesAny(this IContentType dataContentType, params string[] extensionContentTypes) => dataContentType.MatchesAny((IEnumerable<string>)extensionContentTypes); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class IContentTypeExtensions { /// <summary> /// Test whether an extension matches a content type. /// </summary> /// <param name="dataContentType">Content type (typically of a text buffer) against which to /// match an extension.</param> /// <param name="extensionContentTypes">Content types from extension metadata.</param> public static bool MatchesAny(this IContentType dataContentType, IEnumerable<string> extensionContentTypes) => extensionContentTypes.Any(v => dataContentType.IsOfType(v)); public static bool MatchesAny(this IContentType dataContentType, params string[] extensionContentTypes) => dataContentType.MatchesAny((IEnumerable<string>)extensionContentTypes); } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/CSharp/Portable/FlowAnalysis/DefiniteAssignment.VariableIdentifier.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class LocalDataFlowPass<TLocalState, TLocalFunctionState> { internal readonly struct VariableIdentifier : IEquatable<VariableIdentifier> { public readonly Symbol Symbol; /// <summary> /// Indicates whether this variable is nested inside another tracked variable. /// For instance, if a field `x` of a struct is a tracked variable, the symbol is not sufficient /// to uniquely determine which field is being tracked. The containing slot(s) would /// identify which tracked variable the field `x` is part of. /// </summary> public readonly int ContainingSlot; public VariableIdentifier(Symbol symbol, int containingSlot = 0) { Debug.Assert(containingSlot >= 0); Debug.Assert(symbol.Kind switch { SymbolKind.Local => true, SymbolKind.Parameter => true, SymbolKind.Field => true, SymbolKind.Property => true, SymbolKind.Event => true, SymbolKind.ErrorType => true, SymbolKind.Method when symbol is MethodSymbol m && m.MethodKind == MethodKind.LocalFunction => true, _ => false }); Symbol = symbol; ContainingSlot = containingSlot; } public bool Exists { get { return (object)Symbol != null; } } public override int GetHashCode() { Debug.Assert(Exists); int currentKey = ContainingSlot; // MemberIndexOpt, if available, is a fast approach to comparing relative members, // and is necessary in cases such as anonymous types where OriginalDefinition will be distinct. int? thisIndex = Symbol.MemberIndexOpt; return thisIndex.HasValue ? Hash.Combine(thisIndex.GetValueOrDefault(), currentKey) : Hash.Combine(Symbol.OriginalDefinition, currentKey); } public bool Equals(VariableIdentifier other) { Debug.Assert(Exists); Debug.Assert(other.Exists); if (ContainingSlot != other.ContainingSlot) { return false; } // MemberIndexOpt, if available, is a fast approach to comparing relative members, // and is necessary in cases such as anonymous types where OriginalDefinition will be distinct. int? thisIndex = Symbol.MemberIndexOpt; int? otherIndex = other.Symbol.MemberIndexOpt; if (thisIndex != otherIndex) { return false; } if (thisIndex.HasValue) { return true; } return Symbol.Equals(other.Symbol, TypeCompareKind.AllIgnoreOptions); } public override bool Equals(object? obj) { throw ExceptionUtilities.Unreachable; } [Obsolete] public static bool operator ==(VariableIdentifier left, VariableIdentifier right) { throw ExceptionUtilities.Unreachable; } [Obsolete] public static bool operator !=(VariableIdentifier left, VariableIdentifier right) { throw ExceptionUtilities.Unreachable; } public override string ToString() { return $"ContainingSlot={ContainingSlot}, Symbol={Symbol.GetDebuggerDisplay()}"; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class LocalDataFlowPass<TLocalState, TLocalFunctionState> { internal readonly struct VariableIdentifier : IEquatable<VariableIdentifier> { public readonly Symbol Symbol; /// <summary> /// Indicates whether this variable is nested inside another tracked variable. /// For instance, if a field `x` of a struct is a tracked variable, the symbol is not sufficient /// to uniquely determine which field is being tracked. The containing slot(s) would /// identify which tracked variable the field `x` is part of. /// </summary> public readonly int ContainingSlot; public VariableIdentifier(Symbol symbol, int containingSlot = 0) { Debug.Assert(containingSlot >= 0); Debug.Assert(symbol.Kind switch { SymbolKind.Local => true, SymbolKind.Parameter => true, SymbolKind.Field => true, SymbolKind.Property => true, SymbolKind.Event => true, SymbolKind.ErrorType => true, SymbolKind.Method when symbol is MethodSymbol m && m.MethodKind == MethodKind.LocalFunction => true, _ => false }); Symbol = symbol; ContainingSlot = containingSlot; } public bool Exists { get { return (object)Symbol != null; } } public override int GetHashCode() { Debug.Assert(Exists); int currentKey = ContainingSlot; // MemberIndexOpt, if available, is a fast approach to comparing relative members, // and is necessary in cases such as anonymous types where OriginalDefinition will be distinct. int? thisIndex = Symbol.MemberIndexOpt; return thisIndex.HasValue ? Hash.Combine(thisIndex.GetValueOrDefault(), currentKey) : Hash.Combine(Symbol.OriginalDefinition, currentKey); } public bool Equals(VariableIdentifier other) { Debug.Assert(Exists); Debug.Assert(other.Exists); if (ContainingSlot != other.ContainingSlot) { return false; } // MemberIndexOpt, if available, is a fast approach to comparing relative members, // and is necessary in cases such as anonymous types where OriginalDefinition will be distinct. int? thisIndex = Symbol.MemberIndexOpt; int? otherIndex = other.Symbol.MemberIndexOpt; if (thisIndex != otherIndex) { return false; } if (thisIndex.HasValue) { return true; } return Symbol.Equals(other.Symbol, TypeCompareKind.AllIgnoreOptions); } public override bool Equals(object? obj) { throw ExceptionUtilities.Unreachable; } [Obsolete] public static bool operator ==(VariableIdentifier left, VariableIdentifier right) { throw ExceptionUtilities.Unreachable; } [Obsolete] public static bool operator !=(VariableIdentifier left, VariableIdentifier right) { throw ExceptionUtilities.Unreachable; } public override string ToString() { return $"ContainingSlot={ContainingSlot}, Symbol={Symbol.GetDebuggerDisplay()}"; } } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Interactive/Host/Interactive/Core/InteractiveHost.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Newtonsoft.Json; using Roslyn.Utilities; using StreamJsonRpc; namespace Microsoft.CodeAnalysis.Interactive { /// <summary> /// Represents a process that hosts an interactive session. /// </summary> /// <remarks> /// Handles spawning of the host process and communication between the local callers and the remote session. /// </remarks> internal sealed partial class InteractiveHost : IDisposable { internal const InteractiveHostPlatform DefaultPlatform = InteractiveHostPlatform.Desktop32; /// <summary> /// Use Unicode encoding for STDOUT and STDERR of the InteractiveHost process. /// Ideally, we would use UTF8 but SetConsoleOutputCP Windows API fails with "Invalid Handle" when Console.OutputEncoding is set to UTF8. /// (issue tracked by https://github.com/dotnet/roslyn/issues/47571, https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1253106) /// Unicode is not ideal since the message printed directly to STDOUT/STDERR from native code that do not encode the output are going to be garbled /// (e.g. messages reported by CLR stack overflow and OOM exception handlers: https://github.com/dotnet/runtime/issues/45503). /// </summary> internal static readonly Encoding OutputEncoding = Encoding.Unicode; private static readonly JsonRpcTargetOptions s_jsonRpcTargetOptions = new JsonRpcTargetOptions() { // Do not allow JSON-RPC to automatically subscribe to events and remote their calls. NotifyClientOfEvents = false, // Only allow public methods (may be on internal types) to be invoked remotely. AllowNonPublicInvocation = false }; private readonly Type _replServiceProviderType; private readonly string _initialWorkingDirectory; // adjustable for testing purposes private readonly int _millisecondsTimeout; private const int MaxAttemptsToCreateProcess = 2; private LazyRemoteService? _lazyRemoteService; private int _remoteServiceInstanceId; private TextWriter _output; private TextWriter _errorOutput; private readonly object _outputGuard; private readonly object _errorOutputGuard; /// <remarks> /// Test only setting. /// True to join output writing threads when the host is being disposed. /// We have to join the threads before each test is finished, otherwise xunit won't be able to unload the AppDomain. /// WARNING: Joining the threads might deadlock if <see cref="Dispose()"/> is executing on the UI thread, /// since the threads are dispatching to UI thread to write the output to the editor buffer. /// </remarks> private readonly bool _joinOutputWritingThreadsOnDisposal; internal event Action<InteractiveHostPlatformInfo, InteractiveHostOptions, RemoteExecutionResult>? ProcessInitialized; public InteractiveHost( Type replServiceProviderType, string workingDirectory, int millisecondsTimeout = 5000, bool joinOutputWritingThreadsOnDisposal = false) { _millisecondsTimeout = millisecondsTimeout; _joinOutputWritingThreadsOnDisposal = joinOutputWritingThreadsOnDisposal; _output = TextWriter.Null; _errorOutput = TextWriter.Null; _replServiceProviderType = replServiceProviderType; _initialWorkingDirectory = workingDirectory; _outputGuard = new object(); _errorOutputGuard = new object(); } #region Test hooks internal event Action<char[], int>? OutputReceived; internal event Action<char[], int>? ErrorOutputReceived; internal Process? TryGetProcess() => _lazyRemoteService?.TryGetInitializedService()?.Service?.Process; internal async Task<RemoteService?> TryGetServiceAsync() => (await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false)).Service; // Triggered whenever we create a fresh process. // The ProcessExited event is not hooked yet. internal event Action<Process>? InteractiveHostProcessCreated; // Triggered whenever InteractiveHost process creation fails. internal event Action<Exception?, int?>? InteractiveHostProcessCreationFailed; #endregion ~InteractiveHost() { DisposeRemoteService(); } // Dispose may be called anytime. public void Dispose() { // Run this in background to avoid deadlocking with UIThread operations performing with active outputs. _ = Task.Run(() => SetOutputs(TextWriter.Null, TextWriter.Null)); DisposeRemoteService(); GC.SuppressFinalize(this); } private void DisposeRemoteService() { Interlocked.Exchange(ref _lazyRemoteService, null)?.Dispose(); } public void SetOutputs(TextWriter output, TextWriter errorOutput) { if (output == null) { throw new ArgumentNullException(nameof(output)); } if (errorOutput == null) { throw new ArgumentNullException(nameof(errorOutput)); } lock (_outputGuard) { _output.Flush(); _output = output; } lock (_errorOutputGuard) { _errorOutput.Flush(); _errorOutput = errorOutput; } } internal void OnOutputReceived(bool error, char[] buffer, int count) { (error ? ErrorOutputReceived : OutputReceived)?.Invoke(buffer, count); var writer = error ? _errorOutput : _output; var guard = error ? _errorOutputGuard : _outputGuard; lock (guard) { writer.Write(buffer, 0, count); } } private void WriteOutputInBackground(bool isError, string firstLine, string? secondLine = null) { var writer = isError ? _errorOutput : _output; var guard = isError ? _errorOutputGuard : _outputGuard; // We cannot guarantee that writers can perform writing synchronously // without deadlocks with other operations. // This could happen, for example, for writers provided by the Interactive Window, // and in the case where the window is being disposed. Task.Run(() => { lock (guard) { writer.WriteLine(firstLine); if (secondLine != null) { writer.WriteLine(secondLine); } } }); } private LazyRemoteService CreateRemoteService(InteractiveHostOptions options, bool skipInitialization) { return new LazyRemoteService(this, options, Interlocked.Increment(ref _remoteServiceInstanceId), skipInitialization); } private Task OnProcessExitedAsync(Process process) { ReportProcessExited(process); return TryGetOrCreateRemoteServiceAsync(); } private void ReportProcessExited(Process process) { int? exitCode; try { exitCode = process.HasExited ? process.ExitCode : (int?)null; } catch { exitCode = null; } if (exitCode.HasValue) { WriteOutputInBackground(isError: true, string.Format(InteractiveHostResources.Hosting_process_exited_with_exit_code_0, exitCode.Value)); } } private async Task<InitializedRemoteService> TryGetOrCreateRemoteServiceAsync() { try { LazyRemoteService? currentRemoteService = _lazyRemoteService; for (int attempt = 0; attempt < MaxAttemptsToCreateProcess; attempt++) { // Remote service may be disposed anytime. if (currentRemoteService == null) { return default; } var initializedService = await currentRemoteService.GetInitializedServiceAsync().ConfigureAwait(false); if (initializedService.Service != null && initializedService.Service.Process.IsAlive()) { return initializedService; } // Service failed to start or initialize or the process died. var newService = CreateRemoteService(currentRemoteService.Options, skipInitialization: !initializedService.InitializationResult.Success); var previousService = Interlocked.CompareExchange(ref _lazyRemoteService, newService, currentRemoteService); if (previousService == currentRemoteService) { // we replaced the service whose process we know is dead: currentRemoteService.Dispose(); currentRemoteService = newService; } else { // the process was reset in between our checks, try to use the new service: newService.Dispose(); currentRemoteService = previousService; } } WriteOutputInBackground(isError: true, InteractiveHostResources.Unable_to_create_hosting_process); } catch (OperationCanceledException) { // The user reset the process during initialization. // The reset operation will recreate the process. } catch (Exception e) when (FatalError.ReportAndPropagate(e)) { throw ExceptionUtilities.Unreachable; } return default; } private async Task<RemoteExecutionResult> ExecuteRemoteAsync(string targetName, params object?[] arguments) => (await InvokeRemoteAsync<RemoteExecutionResult.Data>(targetName, arguments).ConfigureAwait(false))?.Deserialize() ?? default; private async Task<TResult> InvokeRemoteAsync<TResult>(string targetName, params object?[] arguments) { var initializedRemoteService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false); if (initializedRemoteService.Service == null) { return default!; } return await InvokeRemoteAsync<TResult>(initializedRemoteService.Service, targetName, arguments).ConfigureAwait(false); } private static async Task<RemoteExecutionResult> ExecuteRemoteAsync(RemoteService remoteService, string targetName, params object?[] arguments) => (await InvokeRemoteAsync<RemoteExecutionResult.Data>(remoteService, targetName, arguments).ConfigureAwait(false))?.Deserialize() ?? default; private static async Task<TResult> InvokeRemoteAsync<TResult>(RemoteService remoteService, string targetName, params object?[] arguments) { try { return await remoteService.JsonRpc.InvokeAsync<TResult>(targetName, arguments).ConfigureAwait(false); } catch (Exception e) when (e is ObjectDisposedException || !remoteService.Process.IsAlive()) { return default!; } } private static JsonRpc CreateRpc(Stream stream, object? incomingCallTarget) { var jsonFormatter = new JsonMessageFormatter(); // disable interpreting of strings as DateTime during deserialization: jsonFormatter.JsonSerializer.DateParseHandling = DateParseHandling.None; var rpc = new JsonRpc(new HeaderDelimitedMessageHandler(stream, jsonFormatter)) { CancelLocallyInvokedMethodsWhenConnectionIsClosed = true, ExceptionStrategy = ExceptionProcessing.ISerializable, }; if (incomingCallTarget != null) { rpc.AddLocalRpcTarget(incomingCallTarget, s_jsonRpcTargetOptions); } rpc.StartListening(); return rpc; } #region Operations public InteractiveHostOptions? OptionsOpt => _lazyRemoteService?.Options; /// <summary> /// Restarts and reinitializes the host process (or starts a new one if it is not running yet). /// </summary> /// <param name="options">The options to initialize the new process with.</param> public async Task<RemoteExecutionResult> ResetAsync(InteractiveHostOptions options) { try { // replace the existing service with a new one: var newService = CreateRemoteService(options, skipInitialization: false); var oldService = Interlocked.Exchange(ref _lazyRemoteService, newService); if (oldService != null) { oldService.Dispose(); } var initializedService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false); if (initializedService.Service == null) { return default; } return initializedService.InitializationResult; } catch (Exception e) when (FatalError.ReportAndPropagate(e)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Asynchronously executes given code in the remote interactive session. /// </summary> /// <param name="code">The code to execute.</param> /// <remarks> /// This method is thread safe but operations are sent to the remote process /// asynchronously so tasks should be executed serially if order is important. /// </remarks> public Task<RemoteExecutionResult> ExecuteAsync(string code) { Contract.ThrowIfNull(code); return ExecuteRemoteAsync(nameof(Service.ExecuteAsync), code); } /// <summary> /// Asynchronously executes given code in the remote interactive session. /// </summary> /// <param name="path">The file to execute.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <remarks> /// This method is thread safe but operations are sent to the remote process /// asynchronously so tasks should be executed serially if order is important. /// </remarks> public Task<RemoteExecutionResult> ExecuteFileAsync(string path) { Contract.ThrowIfNull(path); return ExecuteRemoteAsync(nameof(Service.ExecuteFileAsync), path); } /// <summary> /// Asynchronously adds a reference to the set of available references for next submission. /// </summary> /// <param name="reference">The reference to add.</param> /// <remarks> /// This method is thread safe but operations are sent to the remote process /// asynchronously so tasks should be executed serially if order is important. /// </remarks> public Task<bool> AddReferenceAsync(string reference) { Contract.ThrowIfNull(reference); return InvokeRemoteAsync<bool>(nameof(Service.AddReferenceAsync), reference); } /// <summary> /// Sets the current session's search paths and base directory. /// </summary> public Task<RemoteExecutionResult> SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string baseDirectory) { Contract.ThrowIfTrue(referenceSearchPaths.IsDefault); Contract.ThrowIfTrue(sourceSearchPaths.IsDefault); Contract.ThrowIfNull(baseDirectory); return ExecuteRemoteAsync(nameof(Service.SetPathsAsync), referenceSearchPaths, sourceSearchPaths, baseDirectory); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Newtonsoft.Json; using Roslyn.Utilities; using StreamJsonRpc; namespace Microsoft.CodeAnalysis.Interactive { /// <summary> /// Represents a process that hosts an interactive session. /// </summary> /// <remarks> /// Handles spawning of the host process and communication between the local callers and the remote session. /// </remarks> internal sealed partial class InteractiveHost : IDisposable { internal const InteractiveHostPlatform DefaultPlatform = InteractiveHostPlatform.Desktop32; /// <summary> /// Use Unicode encoding for STDOUT and STDERR of the InteractiveHost process. /// Ideally, we would use UTF8 but SetConsoleOutputCP Windows API fails with "Invalid Handle" when Console.OutputEncoding is set to UTF8. /// (issue tracked by https://github.com/dotnet/roslyn/issues/47571, https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1253106) /// Unicode is not ideal since the message printed directly to STDOUT/STDERR from native code that do not encode the output are going to be garbled /// (e.g. messages reported by CLR stack overflow and OOM exception handlers: https://github.com/dotnet/runtime/issues/45503). /// </summary> internal static readonly Encoding OutputEncoding = Encoding.Unicode; private static readonly JsonRpcTargetOptions s_jsonRpcTargetOptions = new JsonRpcTargetOptions() { // Do not allow JSON-RPC to automatically subscribe to events and remote their calls. NotifyClientOfEvents = false, // Only allow public methods (may be on internal types) to be invoked remotely. AllowNonPublicInvocation = false }; private readonly Type _replServiceProviderType; private readonly string _initialWorkingDirectory; // adjustable for testing purposes private readonly int _millisecondsTimeout; private const int MaxAttemptsToCreateProcess = 2; private LazyRemoteService? _lazyRemoteService; private int _remoteServiceInstanceId; private TextWriter _output; private TextWriter _errorOutput; private readonly object _outputGuard; private readonly object _errorOutputGuard; /// <remarks> /// Test only setting. /// True to join output writing threads when the host is being disposed. /// We have to join the threads before each test is finished, otherwise xunit won't be able to unload the AppDomain. /// WARNING: Joining the threads might deadlock if <see cref="Dispose()"/> is executing on the UI thread, /// since the threads are dispatching to UI thread to write the output to the editor buffer. /// </remarks> private readonly bool _joinOutputWritingThreadsOnDisposal; internal event Action<InteractiveHostPlatformInfo, InteractiveHostOptions, RemoteExecutionResult>? ProcessInitialized; public InteractiveHost( Type replServiceProviderType, string workingDirectory, int millisecondsTimeout = 5000, bool joinOutputWritingThreadsOnDisposal = false) { _millisecondsTimeout = millisecondsTimeout; _joinOutputWritingThreadsOnDisposal = joinOutputWritingThreadsOnDisposal; _output = TextWriter.Null; _errorOutput = TextWriter.Null; _replServiceProviderType = replServiceProviderType; _initialWorkingDirectory = workingDirectory; _outputGuard = new object(); _errorOutputGuard = new object(); } #region Test hooks internal event Action<char[], int>? OutputReceived; internal event Action<char[], int>? ErrorOutputReceived; internal Process? TryGetProcess() => _lazyRemoteService?.TryGetInitializedService()?.Service?.Process; internal async Task<RemoteService?> TryGetServiceAsync() => (await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false)).Service; // Triggered whenever we create a fresh process. // The ProcessExited event is not hooked yet. internal event Action<Process>? InteractiveHostProcessCreated; // Triggered whenever InteractiveHost process creation fails. internal event Action<Exception?, int?>? InteractiveHostProcessCreationFailed; #endregion ~InteractiveHost() { DisposeRemoteService(); } // Dispose may be called anytime. public void Dispose() { // Run this in background to avoid deadlocking with UIThread operations performing with active outputs. _ = Task.Run(() => SetOutputs(TextWriter.Null, TextWriter.Null)); DisposeRemoteService(); GC.SuppressFinalize(this); } private void DisposeRemoteService() { Interlocked.Exchange(ref _lazyRemoteService, null)?.Dispose(); } public void SetOutputs(TextWriter output, TextWriter errorOutput) { if (output == null) { throw new ArgumentNullException(nameof(output)); } if (errorOutput == null) { throw new ArgumentNullException(nameof(errorOutput)); } lock (_outputGuard) { _output.Flush(); _output = output; } lock (_errorOutputGuard) { _errorOutput.Flush(); _errorOutput = errorOutput; } } internal void OnOutputReceived(bool error, char[] buffer, int count) { (error ? ErrorOutputReceived : OutputReceived)?.Invoke(buffer, count); var writer = error ? _errorOutput : _output; var guard = error ? _errorOutputGuard : _outputGuard; lock (guard) { writer.Write(buffer, 0, count); } } private void WriteOutputInBackground(bool isError, string firstLine, string? secondLine = null) { var writer = isError ? _errorOutput : _output; var guard = isError ? _errorOutputGuard : _outputGuard; // We cannot guarantee that writers can perform writing synchronously // without deadlocks with other operations. // This could happen, for example, for writers provided by the Interactive Window, // and in the case where the window is being disposed. Task.Run(() => { lock (guard) { writer.WriteLine(firstLine); if (secondLine != null) { writer.WriteLine(secondLine); } } }); } private LazyRemoteService CreateRemoteService(InteractiveHostOptions options, bool skipInitialization) { return new LazyRemoteService(this, options, Interlocked.Increment(ref _remoteServiceInstanceId), skipInitialization); } private Task OnProcessExitedAsync(Process process) { ReportProcessExited(process); return TryGetOrCreateRemoteServiceAsync(); } private void ReportProcessExited(Process process) { int? exitCode; try { exitCode = process.HasExited ? process.ExitCode : (int?)null; } catch { exitCode = null; } if (exitCode.HasValue) { WriteOutputInBackground(isError: true, string.Format(InteractiveHostResources.Hosting_process_exited_with_exit_code_0, exitCode.Value)); } } private async Task<InitializedRemoteService> TryGetOrCreateRemoteServiceAsync() { try { LazyRemoteService? currentRemoteService = _lazyRemoteService; for (int attempt = 0; attempt < MaxAttemptsToCreateProcess; attempt++) { // Remote service may be disposed anytime. if (currentRemoteService == null) { return default; } var initializedService = await currentRemoteService.GetInitializedServiceAsync().ConfigureAwait(false); if (initializedService.Service != null && initializedService.Service.Process.IsAlive()) { return initializedService; } // Service failed to start or initialize or the process died. var newService = CreateRemoteService(currentRemoteService.Options, skipInitialization: !initializedService.InitializationResult.Success); var previousService = Interlocked.CompareExchange(ref _lazyRemoteService, newService, currentRemoteService); if (previousService == currentRemoteService) { // we replaced the service whose process we know is dead: currentRemoteService.Dispose(); currentRemoteService = newService; } else { // the process was reset in between our checks, try to use the new service: newService.Dispose(); currentRemoteService = previousService; } } WriteOutputInBackground(isError: true, InteractiveHostResources.Unable_to_create_hosting_process); } catch (OperationCanceledException) { // The user reset the process during initialization. // The reset operation will recreate the process. } catch (Exception e) when (FatalError.ReportAndPropagate(e)) { throw ExceptionUtilities.Unreachable; } return default; } private async Task<RemoteExecutionResult> ExecuteRemoteAsync(string targetName, params object?[] arguments) => (await InvokeRemoteAsync<RemoteExecutionResult.Data>(targetName, arguments).ConfigureAwait(false))?.Deserialize() ?? default; private async Task<TResult> InvokeRemoteAsync<TResult>(string targetName, params object?[] arguments) { var initializedRemoteService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false); if (initializedRemoteService.Service == null) { return default!; } return await InvokeRemoteAsync<TResult>(initializedRemoteService.Service, targetName, arguments).ConfigureAwait(false); } private static async Task<RemoteExecutionResult> ExecuteRemoteAsync(RemoteService remoteService, string targetName, params object?[] arguments) => (await InvokeRemoteAsync<RemoteExecutionResult.Data>(remoteService, targetName, arguments).ConfigureAwait(false))?.Deserialize() ?? default; private static async Task<TResult> InvokeRemoteAsync<TResult>(RemoteService remoteService, string targetName, params object?[] arguments) { try { return await remoteService.JsonRpc.InvokeAsync<TResult>(targetName, arguments).ConfigureAwait(false); } catch (Exception e) when (e is ObjectDisposedException || !remoteService.Process.IsAlive()) { return default!; } } private static JsonRpc CreateRpc(Stream stream, object? incomingCallTarget) { var jsonFormatter = new JsonMessageFormatter(); // disable interpreting of strings as DateTime during deserialization: jsonFormatter.JsonSerializer.DateParseHandling = DateParseHandling.None; var rpc = new JsonRpc(new HeaderDelimitedMessageHandler(stream, jsonFormatter)) { CancelLocallyInvokedMethodsWhenConnectionIsClosed = true, ExceptionStrategy = ExceptionProcessing.ISerializable, }; if (incomingCallTarget != null) { rpc.AddLocalRpcTarget(incomingCallTarget, s_jsonRpcTargetOptions); } rpc.StartListening(); return rpc; } #region Operations public InteractiveHostOptions? OptionsOpt => _lazyRemoteService?.Options; /// <summary> /// Restarts and reinitializes the host process (or starts a new one if it is not running yet). /// </summary> /// <param name="options">The options to initialize the new process with.</param> public async Task<RemoteExecutionResult> ResetAsync(InteractiveHostOptions options) { try { // replace the existing service with a new one: var newService = CreateRemoteService(options, skipInitialization: false); var oldService = Interlocked.Exchange(ref _lazyRemoteService, newService); if (oldService != null) { oldService.Dispose(); } var initializedService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false); if (initializedService.Service == null) { return default; } return initializedService.InitializationResult; } catch (Exception e) when (FatalError.ReportAndPropagate(e)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Asynchronously executes given code in the remote interactive session. /// </summary> /// <param name="code">The code to execute.</param> /// <remarks> /// This method is thread safe but operations are sent to the remote process /// asynchronously so tasks should be executed serially if order is important. /// </remarks> public Task<RemoteExecutionResult> ExecuteAsync(string code) { Contract.ThrowIfNull(code); return ExecuteRemoteAsync(nameof(Service.ExecuteAsync), code); } /// <summary> /// Asynchronously executes given code in the remote interactive session. /// </summary> /// <param name="path">The file to execute.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <remarks> /// This method is thread safe but operations are sent to the remote process /// asynchronously so tasks should be executed serially if order is important. /// </remarks> public Task<RemoteExecutionResult> ExecuteFileAsync(string path) { Contract.ThrowIfNull(path); return ExecuteRemoteAsync(nameof(Service.ExecuteFileAsync), path); } /// <summary> /// Asynchronously adds a reference to the set of available references for next submission. /// </summary> /// <param name="reference">The reference to add.</param> /// <remarks> /// This method is thread safe but operations are sent to the remote process /// asynchronously so tasks should be executed serially if order is important. /// </remarks> public Task<bool> AddReferenceAsync(string reference) { Contract.ThrowIfNull(reference); return InvokeRemoteAsync<bool>(nameof(Service.AddReferenceAsync), reference); } /// <summary> /// Sets the current session's search paths and base directory. /// </summary> public Task<RemoteExecutionResult> SetPathsAsync(ImmutableArray<string> referenceSearchPaths, ImmutableArray<string> sourceSearchPaths, string baseDirectory) { Contract.ThrowIfTrue(referenceSearchPaths.IsDefault); Contract.ThrowIfTrue(sourceSearchPaths.IsDefault); Contract.ThrowIfNull(baseDirectory); return ExecuteRemoteAsync(nameof(Service.SetPathsAsync), referenceSearchPaths, sourceSearchPaths, baseDirectory); } #endregion } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicSquigglesNetCore.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicSquigglesNetCore : BasicSquigglesCommon { public BasicSquigglesNetCore(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.VisualBasicNetCoreClassLibrary) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(false); // The VisualBasicNetCoreClassLibrary template does not open a file automatically. VisualStudio.SolutionExplorer.OpenFile(new Project(ProjectName), WellKnownProjectTemplates.VisualBasicNetCoreClassLibraryClassFileName); } [WorkItem(1825, "https://github.com/dotnet/roslyn-project-system/issues/1825")] [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void VerifySyntaxErrorSquiggles() { base.VerifySyntaxErrorSquiggles(); } [WorkItem(1825, "https://github.com/dotnet/roslyn-project-system/issues/1825")] [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void VerifySemanticErrorSquiggles() { base.VerifySemanticErrorSquiggles(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicSquigglesNetCore : BasicSquigglesCommon { public BasicSquigglesNetCore(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.VisualBasicNetCoreClassLibrary) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(false); // The VisualBasicNetCoreClassLibrary template does not open a file automatically. VisualStudio.SolutionExplorer.OpenFile(new Project(ProjectName), WellKnownProjectTemplates.VisualBasicNetCoreClassLibraryClassFileName); } [WorkItem(1825, "https://github.com/dotnet/roslyn-project-system/issues/1825")] [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void VerifySyntaxErrorSquiggles() { base.VerifySyntaxErrorSquiggles(); } [WorkItem(1825, "https://github.com/dotnet/roslyn-project-system/issues/1825")] [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorSquiggles)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void VerifySemanticErrorSquiggles() { base.VerifySemanticErrorSquiggles(); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/Lists/ReferenceListItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists { internal class ReferenceListItem : ObjectListItem { private readonly string _name; private readonly MetadataReference _reference; public ReferenceListItem(ProjectId projectId, string name, MetadataReference reference) : base(projectId, StandardGlyphGroup.GlyphAssembly) { _name = name; _reference = reference; } public override string DisplayText { get { return _name; } } public override string FullNameText { get { return _name; } } public override string SearchText { get { return _name; } } public MetadataReference MetadataReference { get { return _reference; } } public IAssemblySymbol GetAssembly(Compilation compilation) => compilation.GetAssemblyOrModuleSymbol(_reference) as IAssemblySymbol; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists { internal class ReferenceListItem : ObjectListItem { private readonly string _name; private readonly MetadataReference _reference; public ReferenceListItem(ProjectId projectId, string name, MetadataReference reference) : base(projectId, StandardGlyphGroup.GlyphAssembly) { _name = name; _reference = reference; } public override string DisplayText { get { return _name; } } public override string FullNameText { get { return _name; } } public override string SearchText { get { return _name; } } public MetadataReference MetadataReference { get { return _reference; } } public IAssemblySymbol GetAssembly(Compilation compilation) => compilation.GetAssemblyOrModuleSymbol(_reference) as IAssemblySymbol; } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Features/Core/Portable/NavigateTo/RoslynNavigateToItem.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.IO; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.NavigateTo { /// <summary> /// Data about a navigate to match. Only intended for use by C# and VB. Carries enough rich information to /// rehydrate everything needed quickly on either the host or remote side. /// </summary> [DataContract] internal readonly struct RoslynNavigateToItem { [DataMember(Order = 0)] public readonly bool IsStale; [DataMember(Order = 1)] public readonly DocumentId DocumentId; [DataMember(Order = 2)] public readonly ImmutableArray<ProjectId> AdditionalMatchingProjects; [DataMember(Order = 3)] public readonly DeclaredSymbolInfo DeclaredSymbolInfo; /// <summary> /// Will be one of the values from <see cref="NavigateToItemKind"/>. /// </summary> [DataMember(Order = 4)] public readonly string Kind; [DataMember(Order = 5)] public readonly NavigateToMatchKind MatchKind; [DataMember(Order = 6)] public readonly bool IsCaseSensitive; [DataMember(Order = 7)] public readonly ImmutableArray<TextSpan> NameMatchSpans; public RoslynNavigateToItem( bool isStale, DocumentId documentId, ImmutableArray<ProjectId> additionalMatchingProjects, DeclaredSymbolInfo declaredSymbolInfo, string kind, NavigateToMatchKind matchKind, bool isCaseSensitive, ImmutableArray<TextSpan> nameMatchSpans) { IsStale = isStale; DocumentId = documentId; AdditionalMatchingProjects = additionalMatchingProjects; DeclaredSymbolInfo = declaredSymbolInfo; Kind = kind; MatchKind = matchKind; IsCaseSensitive = isCaseSensitive; NameMatchSpans = nameMatchSpans; } public async Task<INavigateToSearchResult?> TryCreateSearchResultAsync(Solution solution, CancellationToken cancellationToken) { if (IsStale) { // may refer to a document that doesn't exist anymore. Bail out gracefully in that case. var document = solution.GetDocument(DocumentId); if (document == null) return null; return new NavigateToSearchResult(this, document); } else { var document = await solution.GetRequiredDocumentAsync( DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); return new NavigateToSearchResult(this, document); } } private class NavigateToSearchResult : INavigateToSearchResult, INavigableItem { private static readonly char[] s_dotArray = { '.' }; private readonly RoslynNavigateToItem _item; private readonly Document _document; private readonly string _additionalInformation; public NavigateToSearchResult(RoslynNavigateToItem item, Document document) { _item = item; _document = document; _additionalInformation = ComputeAdditionalInformation(); } private string ComputeAdditionalInformation() { // For partial types, state what file they're in so the user can disambiguate the results. var combinedProjectName = ComputeCombinedProjectName(); return (_item.DeclaredSymbolInfo.IsPartial, IsNonNestedNamedType()) switch { (true, true) => string.Format(FeaturesResources._0_dash_1, _document.Name, combinedProjectName), (true, false) => string.Format(FeaturesResources.in_0_1_2, _item.DeclaredSymbolInfo.ContainerDisplayName, _document.Name, combinedProjectName), (false, true) => string.Format(FeaturesResources.project_0, combinedProjectName), (false, false) => string.Format(FeaturesResources.in_0_project_1, _item.DeclaredSymbolInfo.ContainerDisplayName, combinedProjectName), }; } private string ComputeCombinedProjectName() { // If there aren't any additional matches in other projects, we don't need to merge anything. if (_item.AdditionalMatchingProjects.Length > 0) { // First get the simple project name and flavor for the actual project we got a hit in. If we can't // figure this out, we can't create a merged name. var firstProject = _document.Project; var (firstProjectName, firstProjectFlavor) = firstProject.State.NameAndFlavor; if (firstProjectName != null) { var solution = firstProject.Solution; using var _ = ArrayBuilder<string>.GetInstance(out var flavors); flavors.Add(firstProjectFlavor!); // Now, do the same for the other projects where we had a match. As above, if we can't figure out the // simple name/flavor, or if the simple project name doesn't match the simple project name we started // with then we can't merge these. foreach (var additionalProjectId in _item.AdditionalMatchingProjects) { var additionalProject = solution.GetRequiredProject(additionalProjectId); var (projectName, projectFlavor) = additionalProject.State.NameAndFlavor; if (projectName == firstProjectName) flavors.Add(projectFlavor!); } flavors.RemoveDuplicates(); flavors.Sort(); return $"{firstProjectName} ({string.Join(", ", flavors)})"; } } // Couldn't compute a merged project name (or only had one project). Just return the name of hte project itself. return _document.Project.Name; } string INavigateToSearchResult.AdditionalInformation => _additionalInformation; private bool IsNonNestedNamedType() => !_item.DeclaredSymbolInfo.IsNestedType && IsNamedType(); private bool IsNamedType() { switch (_item.DeclaredSymbolInfo.Kind) { case DeclaredSymbolInfoKind.Class: case DeclaredSymbolInfoKind.Record: case DeclaredSymbolInfoKind.Enum: case DeclaredSymbolInfoKind.Interface: case DeclaredSymbolInfoKind.Module: case DeclaredSymbolInfoKind.Struct: case DeclaredSymbolInfoKind.RecordStruct: return true; default: return false; } } string INavigateToSearchResult.Kind => _item.Kind; NavigateToMatchKind INavigateToSearchResult.MatchKind => _item.MatchKind; bool INavigateToSearchResult.IsCaseSensitive => _item.IsCaseSensitive; string INavigateToSearchResult.Name => _item.DeclaredSymbolInfo.Name; ImmutableArray<TextSpan> INavigateToSearchResult.NameMatchSpans => _item.NameMatchSpans; string INavigateToSearchResult.SecondarySort { get { // For partial types, we break up the file name into pieces. i.e. If we have // Outer.cs and Outer.Inner.cs then we add "Outer" and "Outer Inner" to // the secondary sort string. That way "Outer.cs" will be weighted above // "Outer.Inner.cs" var fileName = Path.GetFileNameWithoutExtension(_document.FilePath ?? ""); using var _ = ArrayBuilder<string>.GetInstance(out var parts); parts.Add(_item.DeclaredSymbolInfo.ParameterCount.ToString("X4")); parts.Add(_item.DeclaredSymbolInfo.TypeParameterCount.ToString("X4")); parts.Add(_item.DeclaredSymbolInfo.Name); parts.AddRange(fileName.Split(s_dotArray)); return string.Join(" ", parts); } } string? INavigateToSearchResult.Summary => null; INavigableItem INavigateToSearchResult.NavigableItem => this; #region INavigableItem Glyph INavigableItem.Glyph => GetGlyph(_item.DeclaredSymbolInfo.Kind, _item.DeclaredSymbolInfo.Accessibility); private static Glyph GetPublicGlyph(DeclaredSymbolInfoKind kind) => kind switch { DeclaredSymbolInfoKind.Class => Glyph.ClassPublic, DeclaredSymbolInfoKind.Constant => Glyph.ConstantPublic, DeclaredSymbolInfoKind.Constructor => Glyph.MethodPublic, DeclaredSymbolInfoKind.Delegate => Glyph.DelegatePublic, DeclaredSymbolInfoKind.Enum => Glyph.EnumPublic, DeclaredSymbolInfoKind.EnumMember => Glyph.EnumMemberPublic, DeclaredSymbolInfoKind.Event => Glyph.EventPublic, DeclaredSymbolInfoKind.ExtensionMethod => Glyph.ExtensionMethodPublic, DeclaredSymbolInfoKind.Field => Glyph.FieldPublic, DeclaredSymbolInfoKind.Indexer => Glyph.PropertyPublic, DeclaredSymbolInfoKind.Interface => Glyph.InterfacePublic, DeclaredSymbolInfoKind.Method => Glyph.MethodPublic, DeclaredSymbolInfoKind.Module => Glyph.ModulePublic, DeclaredSymbolInfoKind.Property => Glyph.PropertyPublic, DeclaredSymbolInfoKind.Struct => Glyph.StructurePublic, DeclaredSymbolInfoKind.RecordStruct => Glyph.StructurePublic, _ => Glyph.ClassPublic, }; private static Glyph GetGlyph(DeclaredSymbolInfoKind kind, Accessibility accessibility) { // Glyphs are stored in this order: // ClassPublic, // ClassProtected, // ClassPrivate, // ClassInternal, var rawGlyph = GetPublicGlyph(kind); switch (accessibility) { case Accessibility.Private: rawGlyph += (Glyph.ClassPrivate - Glyph.ClassPublic); break; case Accessibility.Internal: rawGlyph += (Glyph.ClassInternal - Glyph.ClassPublic); break; case Accessibility.Protected: case Accessibility.ProtectedOrInternal: case Accessibility.ProtectedAndInternal: rawGlyph += (Glyph.ClassProtected - Glyph.ClassPublic); break; } return rawGlyph; } ImmutableArray<TaggedText> INavigableItem.DisplayTaggedParts => ImmutableArray.Create(new TaggedText( TextTags.Text, _item.DeclaredSymbolInfo.Name + _item.DeclaredSymbolInfo.NameSuffix)); bool INavigableItem.DisplayFileLocation => false; /// <summary> /// DeclaredSymbolInfos always come from some actual declaration in source. So they're /// never implicitly declared. /// </summary> bool INavigableItem.IsImplicitlyDeclared => false; Document INavigableItem.Document => _document; TextSpan INavigableItem.SourceSpan => _item.DeclaredSymbolInfo.Span; bool INavigableItem.IsStale => _item.IsStale; ImmutableArray<INavigableItem> INavigableItem.ChildItems => ImmutableArray<INavigableItem>.Empty; #endregion } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.NavigateTo { /// <summary> /// Data about a navigate to match. Only intended for use by C# and VB. Carries enough rich information to /// rehydrate everything needed quickly on either the host or remote side. /// </summary> [DataContract] internal readonly struct RoslynNavigateToItem { [DataMember(Order = 0)] public readonly bool IsStale; [DataMember(Order = 1)] public readonly DocumentId DocumentId; [DataMember(Order = 2)] public readonly ImmutableArray<ProjectId> AdditionalMatchingProjects; [DataMember(Order = 3)] public readonly DeclaredSymbolInfo DeclaredSymbolInfo; /// <summary> /// Will be one of the values from <see cref="NavigateToItemKind"/>. /// </summary> [DataMember(Order = 4)] public readonly string Kind; [DataMember(Order = 5)] public readonly NavigateToMatchKind MatchKind; [DataMember(Order = 6)] public readonly bool IsCaseSensitive; [DataMember(Order = 7)] public readonly ImmutableArray<TextSpan> NameMatchSpans; public RoslynNavigateToItem( bool isStale, DocumentId documentId, ImmutableArray<ProjectId> additionalMatchingProjects, DeclaredSymbolInfo declaredSymbolInfo, string kind, NavigateToMatchKind matchKind, bool isCaseSensitive, ImmutableArray<TextSpan> nameMatchSpans) { IsStale = isStale; DocumentId = documentId; AdditionalMatchingProjects = additionalMatchingProjects; DeclaredSymbolInfo = declaredSymbolInfo; Kind = kind; MatchKind = matchKind; IsCaseSensitive = isCaseSensitive; NameMatchSpans = nameMatchSpans; } public async Task<INavigateToSearchResult?> TryCreateSearchResultAsync(Solution solution, CancellationToken cancellationToken) { if (IsStale) { // may refer to a document that doesn't exist anymore. Bail out gracefully in that case. var document = solution.GetDocument(DocumentId); if (document == null) return null; return new NavigateToSearchResult(this, document); } else { var document = await solution.GetRequiredDocumentAsync( DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); return new NavigateToSearchResult(this, document); } } private class NavigateToSearchResult : INavigateToSearchResult, INavigableItem { private static readonly char[] s_dotArray = { '.' }; private readonly RoslynNavigateToItem _item; private readonly Document _document; private readonly string _additionalInformation; public NavigateToSearchResult(RoslynNavigateToItem item, Document document) { _item = item; _document = document; _additionalInformation = ComputeAdditionalInformation(); } private string ComputeAdditionalInformation() { // For partial types, state what file they're in so the user can disambiguate the results. var combinedProjectName = ComputeCombinedProjectName(); return (_item.DeclaredSymbolInfo.IsPartial, IsNonNestedNamedType()) switch { (true, true) => string.Format(FeaturesResources._0_dash_1, _document.Name, combinedProjectName), (true, false) => string.Format(FeaturesResources.in_0_1_2, _item.DeclaredSymbolInfo.ContainerDisplayName, _document.Name, combinedProjectName), (false, true) => string.Format(FeaturesResources.project_0, combinedProjectName), (false, false) => string.Format(FeaturesResources.in_0_project_1, _item.DeclaredSymbolInfo.ContainerDisplayName, combinedProjectName), }; } private string ComputeCombinedProjectName() { // If there aren't any additional matches in other projects, we don't need to merge anything. if (_item.AdditionalMatchingProjects.Length > 0) { // First get the simple project name and flavor for the actual project we got a hit in. If we can't // figure this out, we can't create a merged name. var firstProject = _document.Project; var (firstProjectName, firstProjectFlavor) = firstProject.State.NameAndFlavor; if (firstProjectName != null) { var solution = firstProject.Solution; using var _ = ArrayBuilder<string>.GetInstance(out var flavors); flavors.Add(firstProjectFlavor!); // Now, do the same for the other projects where we had a match. As above, if we can't figure out the // simple name/flavor, or if the simple project name doesn't match the simple project name we started // with then we can't merge these. foreach (var additionalProjectId in _item.AdditionalMatchingProjects) { var additionalProject = solution.GetRequiredProject(additionalProjectId); var (projectName, projectFlavor) = additionalProject.State.NameAndFlavor; if (projectName == firstProjectName) flavors.Add(projectFlavor!); } flavors.RemoveDuplicates(); flavors.Sort(); return $"{firstProjectName} ({string.Join(", ", flavors)})"; } } // Couldn't compute a merged project name (or only had one project). Just return the name of hte project itself. return _document.Project.Name; } string INavigateToSearchResult.AdditionalInformation => _additionalInformation; private bool IsNonNestedNamedType() => !_item.DeclaredSymbolInfo.IsNestedType && IsNamedType(); private bool IsNamedType() { switch (_item.DeclaredSymbolInfo.Kind) { case DeclaredSymbolInfoKind.Class: case DeclaredSymbolInfoKind.Record: case DeclaredSymbolInfoKind.Enum: case DeclaredSymbolInfoKind.Interface: case DeclaredSymbolInfoKind.Module: case DeclaredSymbolInfoKind.Struct: case DeclaredSymbolInfoKind.RecordStruct: return true; default: return false; } } string INavigateToSearchResult.Kind => _item.Kind; NavigateToMatchKind INavigateToSearchResult.MatchKind => _item.MatchKind; bool INavigateToSearchResult.IsCaseSensitive => _item.IsCaseSensitive; string INavigateToSearchResult.Name => _item.DeclaredSymbolInfo.Name; ImmutableArray<TextSpan> INavigateToSearchResult.NameMatchSpans => _item.NameMatchSpans; string INavigateToSearchResult.SecondarySort { get { // For partial types, we break up the file name into pieces. i.e. If we have // Outer.cs and Outer.Inner.cs then we add "Outer" and "Outer Inner" to // the secondary sort string. That way "Outer.cs" will be weighted above // "Outer.Inner.cs" var fileName = Path.GetFileNameWithoutExtension(_document.FilePath ?? ""); using var _ = ArrayBuilder<string>.GetInstance(out var parts); parts.Add(_item.DeclaredSymbolInfo.ParameterCount.ToString("X4")); parts.Add(_item.DeclaredSymbolInfo.TypeParameterCount.ToString("X4")); parts.Add(_item.DeclaredSymbolInfo.Name); parts.AddRange(fileName.Split(s_dotArray)); return string.Join(" ", parts); } } string? INavigateToSearchResult.Summary => null; INavigableItem INavigateToSearchResult.NavigableItem => this; #region INavigableItem Glyph INavigableItem.Glyph => GetGlyph(_item.DeclaredSymbolInfo.Kind, _item.DeclaredSymbolInfo.Accessibility); private static Glyph GetPublicGlyph(DeclaredSymbolInfoKind kind) => kind switch { DeclaredSymbolInfoKind.Class => Glyph.ClassPublic, DeclaredSymbolInfoKind.Constant => Glyph.ConstantPublic, DeclaredSymbolInfoKind.Constructor => Glyph.MethodPublic, DeclaredSymbolInfoKind.Delegate => Glyph.DelegatePublic, DeclaredSymbolInfoKind.Enum => Glyph.EnumPublic, DeclaredSymbolInfoKind.EnumMember => Glyph.EnumMemberPublic, DeclaredSymbolInfoKind.Event => Glyph.EventPublic, DeclaredSymbolInfoKind.ExtensionMethod => Glyph.ExtensionMethodPublic, DeclaredSymbolInfoKind.Field => Glyph.FieldPublic, DeclaredSymbolInfoKind.Indexer => Glyph.PropertyPublic, DeclaredSymbolInfoKind.Interface => Glyph.InterfacePublic, DeclaredSymbolInfoKind.Method => Glyph.MethodPublic, DeclaredSymbolInfoKind.Module => Glyph.ModulePublic, DeclaredSymbolInfoKind.Property => Glyph.PropertyPublic, DeclaredSymbolInfoKind.Struct => Glyph.StructurePublic, DeclaredSymbolInfoKind.RecordStruct => Glyph.StructurePublic, _ => Glyph.ClassPublic, }; private static Glyph GetGlyph(DeclaredSymbolInfoKind kind, Accessibility accessibility) { // Glyphs are stored in this order: // ClassPublic, // ClassProtected, // ClassPrivate, // ClassInternal, var rawGlyph = GetPublicGlyph(kind); switch (accessibility) { case Accessibility.Private: rawGlyph += (Glyph.ClassPrivate - Glyph.ClassPublic); break; case Accessibility.Internal: rawGlyph += (Glyph.ClassInternal - Glyph.ClassPublic); break; case Accessibility.Protected: case Accessibility.ProtectedOrInternal: case Accessibility.ProtectedAndInternal: rawGlyph += (Glyph.ClassProtected - Glyph.ClassPublic); break; } return rawGlyph; } ImmutableArray<TaggedText> INavigableItem.DisplayTaggedParts => ImmutableArray.Create(new TaggedText( TextTags.Text, _item.DeclaredSymbolInfo.Name + _item.DeclaredSymbolInfo.NameSuffix)); bool INavigableItem.DisplayFileLocation => false; /// <summary> /// DeclaredSymbolInfos always come from some actual declaration in source. So they're /// never implicitly declared. /// </summary> bool INavigableItem.IsImplicitlyDeclared => false; Document INavigableItem.Document => _document; TextSpan INavigableItem.SourceSpan => _item.DeclaredSymbolInfo.Span; bool INavigableItem.IsStale => _item.IsStale; ImmutableArray<INavigableItem> INavigableItem.ChildItems => ImmutableArray<INavigableItem>.Empty; #endregion } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/Core/Portable/InternalUtilities/SemaphoreSlimExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; namespace Roslyn.Utilities { internal static class SemaphoreSlimExtensions { public static SemaphoreDisposer DisposableWait(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default) { semaphore.Wait(cancellationToken); return new SemaphoreDisposer(semaphore); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", OftenCompletesSynchronously = true)] public static async ValueTask<SemaphoreDisposer> DisposableWaitAsync(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default) { await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); return new SemaphoreDisposer(semaphore); } [NonCopyable] internal struct SemaphoreDisposer : IDisposable { private readonly SemaphoreSlim _semaphore; public SemaphoreDisposer(SemaphoreSlim semaphore) { _semaphore = semaphore; } public void Dispose() { _semaphore.Release(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; using System.Threading.Tasks; namespace Roslyn.Utilities { internal static class SemaphoreSlimExtensions { public static SemaphoreDisposer DisposableWait(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default) { semaphore.Wait(cancellationToken); return new SemaphoreDisposer(semaphore); } [PerformanceSensitive("https://github.com/dotnet/roslyn/issues/36114", OftenCompletesSynchronously = true)] public static async ValueTask<SemaphoreDisposer> DisposableWaitAsync(this SemaphoreSlim semaphore, CancellationToken cancellationToken = default) { await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); return new SemaphoreDisposer(semaphore); } [NonCopyable] internal struct SemaphoreDisposer : IDisposable { private readonly SemaphoreSlim _semaphore; public SemaphoreDisposer(SemaphoreSlim semaphore) { _semaphore = semaphore; } public void Dispose() { _semaphore.Release(); } } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Tools/Source/CompilerGeneratorTools/Source/CSharpSyntaxGenerator/IsExternalInit.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.ComponentModel; namespace System.Runtime.CompilerServices { /// <summary> /// Reserved to be used by the compiler for tracking metadata. /// This class should not be used by developers in source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } }
// Licensed to the .NET Foundation under one or more agreements. // 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.ComponentModel; namespace System.Runtime.CompilerServices { /// <summary> /// Reserved to be used by the compiler for tracking metadata. /// This class should not be used by developers in source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/EditorFeatures/CSharpTest/PullMemberUp/CSharpPullMemberUpTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.PullMemberUp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog; using System.Collections.Generic; using Microsoft.CodeAnalysis.Test.Utilities.PullMemberUp; using Roslyn.Test.Utilities; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PullMemberUp { public class CSharpPullMemberUpTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpPullMemberUpCodeRefactoringProvider((IPullMemberUpOptionsService)parameters.fixProviderData); protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions); #region Quick Action private async Task TestQuickActionNotProvidedAsync( string initialMarkup, TestParameters parameters = default) { using var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters); var (actions, _) = await GetCodeActionsAsync(workspace, parameters); if (actions.Length == 1) { // The dialog shows up, not quick action Assert.Equal(actions.First().Title, FeaturesResources.Pull_members_up_to_base_type); } else if (actions.Length > 1) { Assert.True(false, "Pull Members Up is provided via quick action"); } else { Assert.True(true); } } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullFieldInInterfaceViaQuickAction() { var testText = @" namespace PushUpTest { public interface ITestInterface { } public class TestClass : ITestInterface { public int yo[||]u = 10086; } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenMethodDeclarationAlreadyExistsInInterfaceViaQuickAction() { var methodTest = @" namespace PushUpTest { public interface ITestInterface { void TestMethod(); } public class TestClass : ITestInterface { public void TestM[||]ethod() { System.Console.WriteLine(""Hello World""); } } }"; await TestQuickActionNotProvidedAsync(methodTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPropertyDeclarationAlreadyExistsInInterfaceViaQuickAction() { var propertyTest1 = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { get; } } public class TestClass : IInterface { public int TestPr[||]operty { get; private set; } } }"; await TestQuickActionNotProvidedAsync(propertyTest1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenEventDeclarationAlreadyExistsToInterfaceViaQuickAction() { var eventTest = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event1, Eve[||]nt2, Event3; } }"; await TestQuickActionNotProvidedAsync(eventTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedInNestedTypesViaQuickAction() { var input = @" namespace PushUpTest { public interface ITestInterface { void Foobar(); } public class TestClass : ITestInterface { public class N[||]estedClass { } } }"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public void TestM[||]ethod() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { void TestMethod(); } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullAbstractMethodToInterfaceViaQuickAction() { var testText = @" namespace PushUpTest { public interface IInterface { } public abstract class TestClass : IInterface { public abstract void TestMeth[||]od(); } }"; var expected = @" namespace PushUpTest { public interface IInterface { void TestMethod(); } public abstract class TestClass : IInterface { public abstract void TestMethod(); } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullGenericsUpToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { public interface IInterface { } public class TestClass : IInterface { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; var expected = @" using System; namespace PushUpTest { public interface IInterface { void TestMethod<T>() where T : IDisposable; } public class TestClass : IInterface { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullSingleEventToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; } public class TestClass : IInterface { public event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneEventFromMultipleEventsToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Event1, Eve[||]nt2, Event3; } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event1, Event2, Event3; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPublicEventWithAccessorsToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Eve[||]nt2 { add { System.Console.Writeln(""This is add in event1""); } remove { System.Console.Writeln(""This is remove in event2""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event2 { add { System.Console.Writeln(""This is add in event1""); } remove { System.Console.Writeln(""This is remove in event2""); } } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyWithPrivateSetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public int TestPr[||]operty { get; private set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { get; } } public class TestClass : IInterface { public int TestProperty { get; private set; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyWithPrivateGetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public int TestProperty[||]{ private get; set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { set; } } public class TestClass : IInterface { public int TestProperty{ private get; set; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMemberFromInterfaceToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } interface FooInterface : IInterface { int TestPr[||]operty { set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { set; } } interface FooInterface : IInterface { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerWithOnlySetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private int j; public int th[||]is[int i] { set => j = value; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int this[int i] { set; } } public class TestClass : IInterface { private int j; public int this[int i] { set => j = value; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerWithOnlyGetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private int j; public int th[||]is[int i] { get => j = value; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int this[int i] { get; } } public class TestClass : IInterface { private int j; public int this[int i] { get => j = value; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri Endpoint { get; set; } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToInterfaceWithoutAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { bool TestMethod(); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewReturnTypeToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri Test[||]Method() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { Uri TestMethod(); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri TestMethod() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewParamTypeToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { bool TestMethod(Uri endpoint); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool TestMethod(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullEventToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { event EventHandler TestEvent; } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public event EventHandler TestEvent { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithoutDuplicatingUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyWithNewBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Property { get { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestProperty { get { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewNonDeclaredBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; public class Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithOverlappingUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public async Task&lt;int&gt; Get5Async() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public async Task&lt;int&gt; Get5Async() { return 5; } public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnnecessaryFirstUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System.Threading.Tasks; public class Base { public async Task&lt;int&gt; Get5Async() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Derived : Base { public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; using System.Threading.Tasks; public class Base { public async Task&lt;int&gt; Get5Async() { return 5; } public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedBaseUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return 5; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah public class Base { public int TestMethod() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainPreImportCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah using System.Linq; public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah using System; using System.Linq; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainPostImportCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System.Linq; // blah blah public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; // blah blah public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithLambdaUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5). Select((n) => new Uri(""http://"" + n)). Count((uri) => uri != null); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; using System.Linq; public class Base { public int TestMethod() { return Enumerable.Range(0, 5). Select((n) => new Uri(""http://"" + n)). Count((uri) => uri != null); } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using TestNs1; public class Derived : Base { public Foo Test[||]Method() { return null; } } public class Foo { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { using System; using A_TestNs2; public class Base { public Uri Endpoint{ get; set; } public Foo TestMethod() { return null; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using TestNs1; public class Derived : Base { } public class Foo { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using System; using TestNs1; public class Derived : Base { public Foo Test[||]Method() { var uri = new Uri(""http://localhost""); return null; } } public class Foo { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; using A_TestNs2; namespace TestNs1 { public class Base { public Foo TestMethod() { var uri = new Uri(""http://localhost""); return null; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using System; using TestNs1; public class Derived : Base { } public class Foo { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithExtensionViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } public class Foo { } } </Document> <Document FilePath = ""File2.cs""> namespace TestNs2 { using TestNs1; public class Derived : Base { public int Test[||]Method() { var foo = new Foo(); return foo.FooBar(); } } public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using TestNs2; namespace TestNs1 { public class Base { public int TestMethod() { var foo = new Foo(); return foo.FooBar(); } } public class Foo { } } </Document> <Document FilePath = ""File2.cs""> namespace TestNs2 { using TestNs1; public class Derived : Base { } public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithExtensionViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using TestNs1; using TestNs3; using TestNs4; namespace TestNs2 { public class Derived : Base { public int Test[||]Method() { var foo = new Foo(); return foo.FooBar(); } } } </Document> <Document FilePath = ""File3.cs""> namespace TestNs3 { public class Foo { } } </Document> <Document FilePath = ""File4.cs""> using TestNs3; namespace TestNs4 { public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using TestNs3; using TestNs4; namespace TestNs1 { public class Base { public int TestMethod() { var foo = new Foo(); return foo.FooBar(); } } } </Document> <Document FilePath = ""File2.cs""> using TestNs1; using TestNs3; using TestNs4; namespace TestNs2 { public class Derived : Base { } } </Document> <Document FilePath = ""File3.cs""> namespace TestNs3 { public class Foo { } } </Document> <Document FilePath = ""File4.cs""> using TestNs3; namespace TestNs4 { public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithAliasUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using Enumer = System.Linq.Enumerable; using Sys = System; public class Derived : Base { public void Test[||]Method() { Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using Enumer = System.Linq.Enumerable; using Sys = System; public class Base { public Uri Endpoint{ get; set; } public void TestMethod() { Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using Enumer = System.Linq.Enumerable; using Sys = System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithBaseAliasUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using Enumer = System.Linq.Enumerable; public class Base { public void TestMethod() { System.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point{ get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using Enumer = System.Linq.Enumerable; public class Base { public Uri Endpoint{ get; set; } public void TestMethod() { System.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacedUsingsViaQuickAction() { var testText = @" namespace TestNs1 { using System; public class Base { public Uri Endpoint{ get; set; } } } namespace TestNs2 { using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } "; var expected = @" namespace TestNs1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } } namespace TestNs2 { using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNestedNamespacedUsingsViaQuickAction() { var testText = @" namespace TestNs1 { namespace InnerNs1 { using System; public class Base { public Uri Endpoint { get; set; } } } } namespace TestNs2 { namespace InnerNs2 { using System.Linq; using TestNs1.InnerNs1; public class Derived : Base { public int Test[||]Method() { return Foo.Bar(Enumerable.Range(0, 5).Sum()); } } public class Foo { public static int Bar(int num) { return num + 1; } } } } "; var expected = @" namespace TestNs1 { namespace InnerNs1 { using System; using System.Linq; using TestNs2.InnerNs2; public class Base { public Uri Endpoint { get; set; } public int TestMethod() { return Foo.Bar(Enumerable.Range(0, 5).Sum()); } } } } namespace TestNs2 { namespace InnerNs2 { using System.Linq; using TestNs1.InnerNs1; public class Derived : Base { } public class Foo { public static int Bar(int num) { return num + 1; } } } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNewNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { public Other Get[||]Other() => null; } class Other { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using X.Y; namespace A.B { class Base { public Other GetOther() => null; } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { } class Other { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithFileNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B; class Base { } </Document> <Document FilePath = ""File2.cs""> namespace X.Y; class Derived : A.B.Base { public Other Get[||]Other() => null; } class Other { } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using X.Y; namespace A.B; class Base { public Other GetOther() => null; } </Document> <Document FilePath = ""File2.cs""> namespace X.Y; class Derived : A.B.Base { } class Other { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { public int Get[||]Five() => 5; } class Other { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { public int GetFive() => 5; } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { } class Other { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacesAndCommentsViaQuickAction() { var testText = @" // comment 1 namespace TestNs1 { // comment 2 // comment 3 public class Base { } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return 5; } } } "; var expected = @" // comment 1 namespace TestNs1 { // comment 2 // comment 3 public class Base { public int TestMethod() { return 5; } } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacedUsingsAndCommentsViaQuickAction() { var testText = @" // comment 1 namespace TestNs1 { // comment 2 using System; // comment 3 public class Base { } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } "; var expected = @" // comment 1 namespace TestNs1 { // comment 2 using System; using System.Linq; // comment 3 public class Base { public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNamespacedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> namespace ClassLibrary1 { using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> <Document FilePath = ""File2.cs""> namespace ClassLibrary1 { using System.Linq; public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithDuplicateNamespacedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; namespace ClassLibrary1 { using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; namespace ClassLibrary1 { using System.Linq; public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewReturnTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint() { return new Uri(""http://localhost""); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewParamTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Method(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestMethod(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestMethod() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullEventToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullFieldToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public var en[||]dpoint = new Uri(""http://localhost""); } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public var endpoint = new Uri(""http://localhost""); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullFieldToClassNoConstructorWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public var ran[||]ge = Enumerable.Range(0, 5); } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; public class Base { public var range = Enumerable.Range(0, 5); } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverrideMethodUpToClassViaQuickAction() { var methodTest = @" namespace PushUpTest { public class Base { public virtual void TestMethod() => System.Console.WriteLine(""foo bar bar foo""); } public class TestClass : Base { public override void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; await TestQuickActionNotProvidedAsync(methodTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverridePropertyUpToClassViaQuickAction() { var propertyTest = @" using System; namespace PushUpTest { public class Base { public virtual int TestProperty { get => 111; private set; } } public class TestClass : Base { public override int TestPr[||]operty { get; private set; } } }"; await TestQuickActionNotProvidedAsync(propertyTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverrideEventUpToClassViaQuickAction() { var eventTest = @" using System; namespace PushUpTest { public class Base2 { protected virtual event EventHandler Event3 { add { System.Console.WriteLine(""Hello""); } remove { System.Console.WriteLine(""World""); } }; } public class TestClass2 : Base2 { protected override event EventHandler E[||]vent3 { add { System.Console.WriteLine(""foo""); } remove { System.Console.WriteLine(""bar""); } }; } }"; await TestQuickActionNotProvidedAsync(eventTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullSameNameFieldUpToClassViaQuickAction() { // Fields share the same name will be thought as 'override', since it will cause error // if two same name fields exist in one class var fieldTest = @" namespace PushUpTest { public class Base { public int you = -100000; } public class TestClass : Base { public int y[||]ou = 10086; } }"; await TestQuickActionNotProvidedAsync(fieldTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodToOrdinaryClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" namespace PushUpTest { public class Base { public void TestMethod() { System.Console.WriteLine(""Hello World""); } } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneFieldsToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you[||]= 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int you = 10086; } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullGenericsUpToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class BaseClass { } public class TestClass : BaseClass { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; var expected = @" using System; namespace PushUpTest { public class BaseClass { public void TestMethod<T>() where T : IDisposable { } } public class TestClass : BaseClass { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneFieldFromMultipleFieldsToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you, a[||]nd, someone = 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int and; } public class TestClass : Base { public int you, someone = 10086; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMiddleFieldWithValueToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you, a[||]nd = 4000, someone = 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int and = 4000; } public class TestClass : Base { public int you, someone = 10086; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneEventFromMultipleToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private static event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3; } public class Testclass2 : Base2 { private static event EventHandler Event1, Event4; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class TestClass2 : Base2 { private static event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3; } public class TestClass2 : Base2 { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventWithBodyToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class TestClass2 : Base2 { private static event EventHandler Eve[||]nt3 { add { System.Console.Writeln(""Hello""); } remove { System.Console.Writeln(""World""); } }; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3 { add { System.Console.Writeln(""Hello""); } remove { System.Console.Writeln(""World""); } }; } public class TestClass2 : Base2 { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base { } public class TestClass : Base { public int TestPr[||]operty { get; private set; } } }"; var expected = @" using System; namespace PushUpTest { public class Base { public int TestProperty { get; private set; } } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { private int j; public int th[||]is[int i] { get => j; set => j = value; } } }"; var expected = @" namespace PushUpTest { public class Base { public int this[int i] { get => j; set => j = value; } } public class TestClass : Base { private int j; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Bar[||]Bar() { return 12345; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Bar[||]Bar() { return 12345; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { int BarBar(); } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int F[||]oo { get; set; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Foo { get; set; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { int Foo { get; set; } } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullFieldUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : BaseClass { private int i, j, [||]k = 10; } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public class BaseClass { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : BaseClass { private int i, j; } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public class BaseClass { private int k = 10; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToVBClassViaQuickAction() { // Moving member from C# to Visual Basic is not supported currently since the FindMostRelevantDeclarationAsync method in // AbstractCodeGenerationService will return null. var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int Bar[||]bar() { return 12345; } } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToVBInterfaceViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> public class TestClass : VBInterface { public int Bar[||]bar() { return 12345; } } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace> "; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullFieldUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int fo[||]obar = 0; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int foo[||]bar { get; set; } }</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace> "; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpToVBInterfaceViaQuickAction() { var input = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBInterface { public int foo[||]bar { get; set; } } </Document> </Project> <Project Language = ""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public event EventHandler BarEve[||]nt; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventUpToVBInterfaceViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBInterface { public event EventHandler BarEve[||]nt; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")] public async Task TestPullMethodWithToClassWithAddUsingsInsideNamespaceViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using System; namespace N { public class Derived : Base { public Uri En[||]dpoint() { return new Uri(""http://localhost""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N { using System; public class Base { public Uri Endpoint() { return new Uri(""http://localhost""); } } } </Document> <Document FilePath = ""File2.cs""> using System; namespace N { public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync( testText, expected, options: Option(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, CodeAnalysis.AddImports.AddImportPlacement.InsideNamespace, CodeStyle.NotificationOption2.Silent)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")] public async Task TestPullMethodWithToClassWithAddUsingsSystemUsingsLastViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using System; using N2; namespace N1 { public class Derived : Base { public Goo Ge[||]tGoo() { return new Goo(String.Empty); } } } namespace N2 { public class Goo { public Goo(String s) { } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using N2; using System; namespace N1 { public class Base { public Goo GetGoo() { return new Goo(String.Empty); } } } </Document> <Document FilePath = ""File2.cs""> using System; using N2; namespace N1 { public class Derived : Base { } } namespace N2 { public class Goo { public Goo(String s) { } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync( testText, expected, options: new(GetLanguage()) { { GenerationOptions.PlaceSystemNamespaceFirst, false }, }); } #endregion Quick Action #region Dialog internal Task TestWithPullMemberDialogAsync( string initialMarkUp, string expectedResult, IEnumerable<(string name, bool makeAbstract)> selection = null, string destinationName = null, int index = 0, TestParameters parameters = default) { var service = new TestPullMemberUpService(selection, destinationName); return TestInRegularAndScript1Async( initialMarkUp, expectedResult, index, parameters.WithFixProviderData(service)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullPartialMethodUpToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public partial class TestClass : IInterface { partial void Bar[||]Bar() } public partial class TestClass { partial void BarBar() {} } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { void BarBar(); } public partial class TestClass : IInterface { void BarBar() } public partial class TestClass { partial void BarBar() {} } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullExtendedPartialMethodUpToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public partial class TestClass : IInterface { public partial void Bar[||]Bar() } public partial class TestClass { public partial void BarBar() {} } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { void BarBar(); } public partial class TestClass : IInterface { public partial void BarBar() } public partial class TestClass { public partial void BarBar() {} } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleNonPublicMethodsToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } protected void F[||]oo(int i) { // do awesome things } private static string Bar(string x) {} } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { string Bar(string x); void Foo(int i); void TestMethod(); } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } public void Foo(int i) { // do awesome things } public string Bar(string x) {} } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleNonPublicEventsToInterface() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private event EventHandler Event1, Eve[||]nt2, Event3; } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; event EventHandler Event2; event EventHandler Event3; } public class TestClass : IInterface { public event EventHandler Event1; public event EventHandler Event2; public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMethodToInnerInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public class TestClass : TestClass.IInterface { private void Bar[||]Bar() { } interface IInterface { } } }"; var expected = @" using System; namespace PushUpTest { public class TestClass : TestClass.IInterface { public void BarBar() { } interface IInterface { void BarBar(); } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullDifferentMembersFromClassToPartialInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public class TestClass : IInterface { public int th[||]is[int i] { get => j = value; } private static void BarBar() {} protected static event EventHandler event1, event2; internal static int Foo { get; set; } } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { int this[int i] { get; } int Foo { get; set; } event EventHandler event1; event EventHandler event2; void BarBar(); } public class TestClass : IInterface { public int this[int i] { get => j = value; } public void BarBar() {} public event EventHandler event1; public event EventHandler event2; public int Foo { get; set; } } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullAsyncMethod() { var testText = @" using System.Threading.Tasks; internal interface IPullUp { } internal class PullUp : IPullUp { internal async Task PullU[||]pAsync() { await Task.Delay(1000); } }"; var expectedText = @" using System.Threading.Tasks; internal interface IPullUp { Task PullUpAsync(); } internal class PullUp : IPullUp { public async Task PullUpAsync() { await Task.Delay(1000); } }"; await TestWithPullMemberDialogAsync(testText, expectedText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMethodWithAbstractOptionToClassViaDialog() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" namespace PushUpTest { public abstract class Base { public abstract void TestMethod(); } public class TestClass : Base { public override void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullAbstractMethodToClassViaDialog() { var testText = @" namespace PushUpTest { public class Base { } public abstract class TestClass : Base { public abstract void TestMeth[||]od(); } }"; var expected = @" namespace PushUpTest { public abstract class Base { public abstract void TestMethod(); } public abstract class TestClass : Base { } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleEventsToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private static event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event1; private static event EventHandler Event3; private static event EventHandler Event4; } public class Testclass2 : Base2 { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleAbstractEventsToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public abstract class Testclass2 : ITest { protected abstract event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event1; event EventHandler Event3; event EventHandler Event4; } public abstract class Testclass2 : ITest { public abstract event EventHandler Event1; public abstract event EventHandler Event3; public abstract event EventHandler Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullAbstractEventToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public abstract class Testclass2 : Base2 { private static abstract event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public abstract class Base2 { private static abstract event EventHandler Event3; } public abstract class Testclass2 : Base2 { private static abstract event EventHandler Event1, Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicEventToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event3; } public class Testclass2 : ITest { public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullSingleNonPublicEventToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public abstract class TestClass2 : ITest { protected event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event3; } public abstract class TestClass2 : ITest { public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullNonPublicEventWithAddAndRemoveMethodToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; } public class TestClass : IInterface { public event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullFieldsToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { public int i, [||]j = 10, k = 100; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { public int i; public int j = 10; public int k = 100; } public class Testclass2 : Base2 { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyWithArrowToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private double Test[||]Property => 2.717; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { get; } } public class Testclass2 : ITest { public readonly double TestProperty => 2.717; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private double Test[||]Property { get; set; } } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { get; set; } } public class Testclass2 : ITest { public double TestProperty { get; set; } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyWithSingleAccessorToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private static double Test[||]Property { set; } } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { set; } } public class Testclass2 : ITest { public double Test[||]Property { set; } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [WorkItem(34268, "https://github.com/dotnet/roslyn/issues/34268")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyToAbstractClassViaDialogWithMakeAbstractOption() { var testText = @" abstract class B { } class D : B { int [||]X => 7; }"; var expected = @" abstract class B { private abstract int X { get; } } class D : B { override int X => 7; }"; await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("X", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullEventUpToAbstractClassViaDialogWithMakeAbstractOption() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public abstract class Base2 { private abstract event EventHandler Event3; } public class Testclass2 : Base2 { private event EventHandler Event1, Eve[||]nt3, Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("Event3", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventWithAddAndRemoveMethodToClassViaDialogWithMakeAbstractOption() { var testText = @" using System; namespace PushUpTest { public class BaseClass { } public class TestClass : BaseClass { public event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { public abstract class BaseClass { public abstract event EventHandler Event1; } public class TestClass : BaseClass { public override event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", true) }, index: 1); } #endregion Dialog #region Selections and caret position [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestArgsIsPartOfHeader() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [Test2] void C([||]) { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] [Test2] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretBeforeAttributes() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [||][Test] [Test2] void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] [Test2] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretBetweenAttributes() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [||][Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes1() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test] [|void C() { }|] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [|[Test] void C() { }|] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes3() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test][| void C() { } |] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringInAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [[||]Test] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectionAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [|[Test] [Test2]|] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretInAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [[||]Test] [Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretBetweenAttributeLists() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [||][Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectionAttributeList2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [|[Test]|] [Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [|[Test]|] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLocAfterAttributes1() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test] [||]void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLocAfterAttributes2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] // Comment1 [Test2] // Comment2 [||]void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] // Comment1 [Test2] // Comment2 void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLoc1() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [||]void C() { } } }"; var expected = @" namespace PushUpTest { public class A { void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelection() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [|void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [| // Comment1 void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { // Comment1 void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments2() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [|/// <summary> /// Test /// </summary> void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { /// <summary> /// Test /// </summary> void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments3() { var testText = @" namespace PushUpTest { public class A { } public class B : A { /// <summary> [|/// Test /// </summary> void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { /// <summary> /// Test /// </summary> void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } #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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.PullMemberUp; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings.PullMemberUp.Dialog; using System.Collections.Generic; using Microsoft.CodeAnalysis.Test.Utilities.PullMemberUp; using Roslyn.Test.Utilities; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.PullMemberUp { public class CSharpPullMemberUpTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpPullMemberUpCodeRefactoringProvider((IPullMemberUpOptionsService)parameters.fixProviderData); protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions); #region Quick Action private async Task TestQuickActionNotProvidedAsync( string initialMarkup, TestParameters parameters = default) { using var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters); var (actions, _) = await GetCodeActionsAsync(workspace, parameters); if (actions.Length == 1) { // The dialog shows up, not quick action Assert.Equal(actions.First().Title, FeaturesResources.Pull_members_up_to_base_type); } else if (actions.Length > 1) { Assert.True(false, "Pull Members Up is provided via quick action"); } else { Assert.True(true); } } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullFieldInInterfaceViaQuickAction() { var testText = @" namespace PushUpTest { public interface ITestInterface { } public class TestClass : ITestInterface { public int yo[||]u = 10086; } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenMethodDeclarationAlreadyExistsInInterfaceViaQuickAction() { var methodTest = @" namespace PushUpTest { public interface ITestInterface { void TestMethod(); } public class TestClass : ITestInterface { public void TestM[||]ethod() { System.Console.WriteLine(""Hello World""); } } }"; await TestQuickActionNotProvidedAsync(methodTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPropertyDeclarationAlreadyExistsInInterfaceViaQuickAction() { var propertyTest1 = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { get; } } public class TestClass : IInterface { public int TestPr[||]operty { get; private set; } } }"; await TestQuickActionNotProvidedAsync(propertyTest1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenEventDeclarationAlreadyExistsToInterfaceViaQuickAction() { var eventTest = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event1, Eve[||]nt2, Event3; } }"; await TestQuickActionNotProvidedAsync(eventTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedInNestedTypesViaQuickAction() { var input = @" namespace PushUpTest { public interface ITestInterface { void Foobar(); } public class TestClass : ITestInterface { public class N[||]estedClass { } } }"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public void TestM[||]ethod() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { void TestMethod(); } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullAbstractMethodToInterfaceViaQuickAction() { var testText = @" namespace PushUpTest { public interface IInterface { } public abstract class TestClass : IInterface { public abstract void TestMeth[||]od(); } }"; var expected = @" namespace PushUpTest { public interface IInterface { void TestMethod(); } public abstract class TestClass : IInterface { public abstract void TestMethod(); } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullGenericsUpToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { public interface IInterface { } public class TestClass : IInterface { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; var expected = @" using System; namespace PushUpTest { public interface IInterface { void TestMethod<T>() where T : IDisposable; } public class TestClass : IInterface { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullSingleEventToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; } public class TestClass : IInterface { public event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneEventFromMultipleEventsToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Event1, Eve[||]nt2, Event3; } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event1, Event2, Event3; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPublicEventWithAccessorsToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public event EventHandler Eve[||]nt2 { add { System.Console.Writeln(""This is add in event1""); } remove { System.Console.Writeln(""This is remove in event2""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event2; } public class TestClass : IInterface { public event EventHandler Event2 { add { System.Console.Writeln(""This is add in event1""); } remove { System.Console.Writeln(""This is remove in event2""); } } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyWithPrivateSetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public int TestPr[||]operty { get; private set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { get; } } public class TestClass : IInterface { public int TestProperty { get; private set; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyWithPrivateGetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public int TestProperty[||]{ private get; set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { set; } } public class TestClass : IInterface { public int TestProperty{ private get; set; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMemberFromInterfaceToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } interface FooInterface : IInterface { int TestPr[||]operty { set; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int TestProperty { set; } } interface FooInterface : IInterface { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerWithOnlySetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private int j; public int th[||]is[int i] { set => j = value; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int this[int i] { set; } } public class TestClass : IInterface { private int j; public int this[int i] { set => j = value; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerWithOnlyGetterToInterfaceViaQuickAction() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private int j; public int th[||]is[int i] { get => j = value; } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { int this[int i] { get; } } public class TestClass : IInterface { private int j; public int this[int i] { get => j = value; } } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri Endpoint { get; set; } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToInterfaceWithoutAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { bool TestMethod(); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewReturnTypeToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri Test[||]Method() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { Uri TestMethod(); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public Uri TestMethod() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewParamTypeToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool Test[||]Method(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { bool TestMethod(Uri endpoint); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public bool TestMethod(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullEventToInterfaceWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public interface IBase { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public interface IBase { event EventHandler TestEvent; } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : IBase { public event EventHandler TestEvent { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithAddUsingsViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithoutDuplicatingUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyWithNewBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Property { get { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestProperty { get { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewNonDeclaredBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; public class Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithOverlappingUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public async Task&lt;int&gt; Get5Async() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public async Task&lt;int&gt; Get5Async() { return 5; } public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnnecessaryFirstUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System.Threading.Tasks; public class Base { public async Task&lt;int&gt; Get5Async() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Derived : Base { public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; using System.Threading.Tasks; public class Base { public async Task&lt;int&gt; Get5Async() { return 5; } public async Task&lt;int&gt; Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedBaseUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; using System.Threading.Tasks; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public int Test[||]Method() { return 5; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah public class Base { public int TestMethod() { return 5; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainPreImportCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah using System.Linq; public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> // blah blah using System; using System.Linq; public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithRetainPostImportCommentsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System.Linq; // blah blah public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point { get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; // blah blah public class Base { public Uri Endpoint { get; set; } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithLambdaUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5). Select((n) => new Uri(""http://"" + n)). Count((uri) => uri != null); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; using System.Linq; public class Base { public int TestMethod() { return Enumerable.Range(0, 5). Select((n) => new Uri(""http://"" + n)). Count((uri) => uri != null); } } </Document> <Document FilePath = ""File2.cs""> using System; using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; using System.Threading.Tasks; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using TestNs1; public class Derived : Base { public Foo Test[||]Method() { return null; } } public class Foo { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { using System; using A_TestNs2; public class Base { public Uri Endpoint{ get; set; } public Foo TestMethod() { return null; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using TestNs1; public class Derived : Base { } public class Foo { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassKeepSystemFirstViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using System; using TestNs1; public class Derived : Base { public Foo Test[||]Method() { var uri = new Uri(""http://localhost""); return null; } } public class Foo { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; using A_TestNs2; namespace TestNs1 { public class Base { public Foo TestMethod() { var uri = new Uri(""http://localhost""); return null; } } } </Document> <Document FilePath = ""File2.cs""> namespace A_TestNs2 { using System; using TestNs1; public class Derived : Base { } public class Foo { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithExtensionViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } public class Foo { } } </Document> <Document FilePath = ""File2.cs""> namespace TestNs2 { using TestNs1; public class Derived : Base { public int Test[||]Method() { var foo = new Foo(); return foo.FooBar(); } } public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using TestNs2; namespace TestNs1 { public class Base { public int TestMethod() { var foo = new Foo(); return foo.FooBar(); } } public class Foo { } } </Document> <Document FilePath = ""File2.cs""> namespace TestNs2 { using TestNs1; public class Derived : Base { } public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithExtensionViaQuickAction2() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace TestNs1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using TestNs1; using TestNs3; using TestNs4; namespace TestNs2 { public class Derived : Base { public int Test[||]Method() { var foo = new Foo(); return foo.FooBar(); } } } </Document> <Document FilePath = ""File3.cs""> namespace TestNs3 { public class Foo { } } </Document> <Document FilePath = ""File4.cs""> using TestNs3; namespace TestNs4 { public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using TestNs3; using TestNs4; namespace TestNs1 { public class Base { public int TestMethod() { var foo = new Foo(); return foo.FooBar(); } } } </Document> <Document FilePath = ""File2.cs""> using TestNs1; using TestNs3; using TestNs4; namespace TestNs2 { public class Derived : Base { } } </Document> <Document FilePath = ""File3.cs""> namespace TestNs3 { public class Foo { } } </Document> <Document FilePath = ""File4.cs""> using TestNs3; namespace TestNs4 { public static class FooExtensions { public static int FooBar(this Foo foo) { return 5; } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithAliasUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; public class Base { public Uri Endpoint{ get; set; } } </Document> <Document FilePath = ""File2.cs""> using Enumer = System.Linq.Enumerable; using Sys = System; public class Derived : Base { public void Test[||]Method() { Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using Enumer = System.Linq.Enumerable; using Sys = System; public class Base { public Uri Endpoint{ get; set; } public void TestMethod() { Sys.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using Enumer = System.Linq.Enumerable; using Sys = System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullPropertyToClassWithBaseAliasUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using Enumer = System.Linq.Enumerable; public class Base { public void TestMethod() { System.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri End[||]point{ get; set; } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> using System; using Enumer = System.Linq.Enumerable; public class Base { public Uri Endpoint{ get; set; } public void TestMethod() { System.Console.WriteLine(Enumer.Range(0, 5).Sum()); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacedUsingsViaQuickAction() { var testText = @" namespace TestNs1 { using System; public class Base { public Uri Endpoint{ get; set; } } } namespace TestNs2 { using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } "; var expected = @" namespace TestNs1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } } namespace TestNs2 { using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNestedNamespacedUsingsViaQuickAction() { var testText = @" namespace TestNs1 { namespace InnerNs1 { using System; public class Base { public Uri Endpoint { get; set; } } } } namespace TestNs2 { namespace InnerNs2 { using System.Linq; using TestNs1.InnerNs1; public class Derived : Base { public int Test[||]Method() { return Foo.Bar(Enumerable.Range(0, 5).Sum()); } } public class Foo { public static int Bar(int num) { return num + 1; } } } } "; var expected = @" namespace TestNs1 { namespace InnerNs1 { using System; using System.Linq; using TestNs2.InnerNs2; public class Base { public Uri Endpoint { get; set; } public int TestMethod() { return Foo.Bar(Enumerable.Range(0, 5).Sum()); } } } } namespace TestNs2 { namespace InnerNs2 { using System.Linq; using TestNs1.InnerNs1; public class Derived : Base { } public class Foo { public static int Bar(int num) { return num + 1; } } } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNewNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { public Other Get[||]Other() => null; } class Other { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using X.Y; namespace A.B { class Base { public Other GetOther() => null; } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { } class Other { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithFileNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B; class Base { } </Document> <Document FilePath = ""File2.cs""> namespace X.Y; class Derived : A.B.Base { public Other Get[||]Other() => null; } class Other { } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using X.Y; namespace A.B; class Base { public Other GetOther() => null; } </Document> <Document FilePath = ""File2.cs""> namespace X.Y; class Derived : A.B.Base { } class Other { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithUnusedNamespaceUsingViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { public int Get[||]Five() => 5; } class Other { } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace A.B { class Base { public int GetFive() => 5; } } </Document> <Document FilePath = ""File2.cs""> namespace X.Y { class Derived : A.B.Base { } class Other { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacesAndCommentsViaQuickAction() { var testText = @" // comment 1 namespace TestNs1 { // comment 2 // comment 3 public class Base { } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return 5; } } } "; var expected = @" // comment 1 namespace TestNs1 { // comment 2 // comment 3 public class Base { public int TestMethod() { return 5; } } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithMultipleNamespacedUsingsAndCommentsViaQuickAction() { var testText = @" // comment 1 namespace TestNs1 { // comment 2 using System; // comment 3 public class Base { } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } "; var expected = @" // comment 1 namespace TestNs1 { // comment 2 using System; using System.Linq; // comment 3 public class Base { public int TestMethod() { return Enumerable.Range(0, 5).Sum(); } } } namespace TestNs2 { // comment 4 using System.Linq; using TestNs1; public class Derived : Base { } } "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithNamespacedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> namespace ClassLibrary1 { using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> <Document FilePath = ""File2.cs""> namespace ClassLibrary1 { using System.Linq; public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodToClassWithDuplicateNamespacedUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; public class Base { public Uri Endpoint{ get; set; } } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; namespace ClassLibrary1 { using System.Linq; public class Derived : Base { public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace ClassLibrary1 { using System; using System.Linq; public class Base { public Uri Endpoint{ get; set; } public int Test[||]Method() { return Enumerable.Range(0, 5).Sum(); } } } </Document> <Document FilePath = ""File2.cs""> using System.Linq; namespace ClassLibrary1 { using System.Linq; public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewReturnTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public Uri En[||]dpoint() { return new Uri(""http://localhost""); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public Uri Endpoint() { return new Uri(""http://localhost""); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewParamTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Method(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestMethod(Uri endpoint) { var localHost = new Uri(""http://localhost""); return endpoint.Equals(localhost); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullMethodWithNewBodyTypeToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public bool Test[||]Method() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public bool TestMethod() { var endpoint1 = new Uri(""http://localhost""); var endpoint2 = new Uri(""http://localhost""); return endpoint1.Equals(endpoint2); } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullEventToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public event EventHandler Test[||]Event { add { Console.WriteLine(""adding event...""); } remove { Console.WriteLine(""removing event...""); } } } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullFieldToClassWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { public var en[||]dpoint = new Uri(""http://localhost""); } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System; public class Base { public var endpoint = new Uri(""http://localhost""); } </Document> <Document FilePath = ""File2.cs""> using System; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(46010, "https://github.com/dotnet/roslyn/issues/46010")] public async Task TestPullFieldToClassNoConstructorWithAddUsingsViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> public class Base { } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { public var ran[||]ge = Enumerable.Range(0, 5); } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using System.Linq; public class Base { public var range = Enumerable.Range(0, 5); } </Document> <Document FilePath = ""File2.cs""> using System.Linq; public class Derived : Base { } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverrideMethodUpToClassViaQuickAction() { var methodTest = @" namespace PushUpTest { public class Base { public virtual void TestMethod() => System.Console.WriteLine(""foo bar bar foo""); } public class TestClass : Base { public override void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; await TestQuickActionNotProvidedAsync(methodTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverridePropertyUpToClassViaQuickAction() { var propertyTest = @" using System; namespace PushUpTest { public class Base { public virtual int TestProperty { get => 111; private set; } } public class TestClass : Base { public override int TestPr[||]operty { get; private set; } } }"; await TestQuickActionNotProvidedAsync(propertyTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullOverrideEventUpToClassViaQuickAction() { var eventTest = @" using System; namespace PushUpTest { public class Base2 { protected virtual event EventHandler Event3 { add { System.Console.WriteLine(""Hello""); } remove { System.Console.WriteLine(""World""); } }; } public class TestClass2 : Base2 { protected override event EventHandler E[||]vent3 { add { System.Console.WriteLine(""foo""); } remove { System.Console.WriteLine(""bar""); } }; } }"; await TestQuickActionNotProvidedAsync(eventTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestNoRefactoringProvidedWhenPullSameNameFieldUpToClassViaQuickAction() { // Fields share the same name will be thought as 'override', since it will cause error // if two same name fields exist in one class var fieldTest = @" namespace PushUpTest { public class Base { public int you = -100000; } public class TestClass : Base { public int y[||]ou = 10086; } }"; await TestQuickActionNotProvidedAsync(fieldTest); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodToOrdinaryClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" namespace PushUpTest { public class Base { public void TestMethod() { System.Console.WriteLine(""Hello World""); } } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneFieldsToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you[||]= 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int you = 10086; } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullGenericsUpToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class BaseClass { } public class TestClass : BaseClass { public void TestMeth[||]od<T>() where T : IDisposable { } } }"; var expected = @" using System; namespace PushUpTest { public class BaseClass { public void TestMethod<T>() where T : IDisposable { } } public class TestClass : BaseClass { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneFieldFromMultipleFieldsToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you, a[||]nd, someone = 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int and; } public class TestClass : Base { public int you, someone = 10086; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMiddleFieldWithValueToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public int you, a[||]nd = 4000, someone = 10086; } }"; var expected = @" namespace PushUpTest { public class Base { public int and = 4000; } public class TestClass : Base { public int you, someone = 10086; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullOneEventFromMultipleToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private static event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3; } public class Testclass2 : Base2 { private static event EventHandler Event1, Event4; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class TestClass2 : Base2 { private static event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3; } public class TestClass2 : Base2 { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventWithBodyToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class TestClass2 : Base2 { private static event EventHandler Eve[||]nt3 { add { System.Console.Writeln(""Hello""); } remove { System.Console.Writeln(""World""); } }; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event3 { add { System.Console.Writeln(""Hello""); } remove { System.Console.Writeln(""World""); } }; } public class TestClass2 : Base2 { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyToClassViaQuickAction() { var testText = @" using System; namespace PushUpTest { public class Base { } public class TestClass : Base { public int TestPr[||]operty { get; private set; } } }"; var expected = @" using System; namespace PushUpTest { public class Base { public int TestProperty { get; private set; } } public class TestClass : Base { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullIndexerToClassViaQuickAction() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { private int j; public int th[||]is[int i] { get => j; set => j = value; } } }"; var expected = @" namespace PushUpTest { public class Base { public int this[int i] { get => j; set => j = value; } } public class TestClass : Base { private int j; } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Bar[||]Bar() { return 12345; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Bar[||]Bar() { return 12345; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { int BarBar(); } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int F[||]oo { get; set; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : IInterface { public int Foo { get; set; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public interface IInterface { int Foo { get; set; } } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullFieldUpAcrossProjectViaQuickAction() { var testText = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : BaseClass { private int i, j, [||]k = 10; } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public class BaseClass { } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly1"" CommonReferences=""true""> <ProjectReference>CSAssembly2</ProjectReference> <Document> using Destination; public class TestClass : BaseClass { private int i, j; } </Document> </Project> <Project Language=""C#"" AssemblyName=""CSAssembly2"" CommonReferences=""true""> <Document> namespace Destination { public class BaseClass { private int k = 10; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToVBClassViaQuickAction() { // Moving member from C# to Visual Basic is not supported currently since the FindMostRelevantDeclarationAsync method in // AbstractCodeGenerationService will return null. var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int Bar[||]bar() { return 12345; } } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullMethodUpToVBInterfaceViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> public class TestClass : VBInterface { public int Bar[||]bar() { return 12345; } } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace> "; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullFieldUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int fo[||]obar = 0; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public int foo[||]bar { get; set; } }</Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace> "; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyUpToVBInterfaceViaQuickAction() { var input = @"<Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBInterface { public int foo[||]bar { get; set; } } </Document> </Project> <Project Language = ""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventUpToVBClassViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBClass { public event EventHandler BarEve[||]nt; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Class VBClass End Class </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventUpToVBInterfaceViaQuickAction() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true""> <ProjectReference>VBAssembly</ProjectReference> <Document> using VBAssembly; public class TestClass : VBInterface { public event EventHandler BarEve[||]nt; } </Document> </Project> <Project Language=""Visual Basic"" AssemblyName=""VBAssembly"" CommonReferences=""true""> <Document> Public Interface VBInterface End Interface </Document> </Project> </Workspace>"; await TestQuickActionNotProvidedAsync(input); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")] public async Task TestPullMethodWithToClassWithAddUsingsInsideNamespaceViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using System; namespace N { public class Derived : Base { public Uri En[||]dpoint() { return new Uri(""http://localhost""); } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N { using System; public class Base { public Uri Endpoint() { return new Uri(""http://localhost""); } } } </Document> <Document FilePath = ""File2.cs""> using System; namespace N { public class Derived : Base { } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync( testText, expected, options: Option(CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, CodeAnalysis.AddImports.AddImportPlacement.InsideNamespace, CodeStyle.NotificationOption2.Silent)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(55746, "https://github.com/dotnet/roslyn/issues/55746")] public async Task TestPullMethodWithToClassWithAddUsingsSystemUsingsLastViaQuickAction() { var testText = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs""> namespace N1 { public class Base { } } </Document> <Document FilePath = ""File2.cs""> using System; using N2; namespace N1 { public class Derived : Base { public Goo Ge[||]tGoo() { return new Goo(String.Empty); } } } namespace N2 { public class Goo { public Goo(String s) { } } } </Document> </Project> </Workspace> "; var expected = @" <Workspace> <Project Language = ""C#"" LanguageVersion=""preview"" CommonReferences=""true""> <Document FilePath = ""File1.cs"">using N2; using System; namespace N1 { public class Base { public Goo GetGoo() { return new Goo(String.Empty); } } } </Document> <Document FilePath = ""File2.cs""> using System; using N2; namespace N1 { public class Derived : Base { } } namespace N2 { public class Goo { public Goo(String s) { } } } </Document> </Project> </Workspace> "; await TestInRegularAndScriptAsync( testText, expected, options: new(GetLanguage()) { { GenerationOptions.PlaceSystemNamespaceFirst, false }, }); } #endregion Quick Action #region Dialog internal Task TestWithPullMemberDialogAsync( string initialMarkUp, string expectedResult, IEnumerable<(string name, bool makeAbstract)> selection = null, string destinationName = null, int index = 0, TestParameters parameters = default) { var service = new TestPullMemberUpService(selection, destinationName); return TestInRegularAndScript1Async( initialMarkUp, expectedResult, index, parameters.WithFixProviderData(service)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullPartialMethodUpToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public partial class TestClass : IInterface { partial void Bar[||]Bar() } public partial class TestClass { partial void BarBar() {} } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { void BarBar(); } public partial class TestClass : IInterface { void BarBar() } public partial class TestClass { partial void BarBar() {} } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullExtendedPartialMethodUpToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public partial class TestClass : IInterface { public partial void Bar[||]Bar() } public partial class TestClass { public partial void BarBar() {} } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { void BarBar(); } public partial class TestClass : IInterface { public partial void BarBar() } public partial class TestClass { public partial void BarBar() {} } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleNonPublicMethodsToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } protected void F[||]oo(int i) { // do awesome things } private static string Bar(string x) {} } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { string Bar(string x); void Foo(int i); void TestMethod(); } public class TestClass : IInterface { public void TestMethod() { System.Console.WriteLine(""Hello World""); } public void Foo(int i) { // do awesome things } public string Bar(string x) {} } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleNonPublicEventsToInterface() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private event EventHandler Event1, Eve[||]nt2, Event3; } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; event EventHandler Event2; event EventHandler Event3; } public class TestClass : IInterface { public event EventHandler Event1; public event EventHandler Event2; public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMethodToInnerInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public class TestClass : TestClass.IInterface { private void Bar[||]Bar() { } interface IInterface { } } }"; var expected = @" using System; namespace PushUpTest { public class TestClass : TestClass.IInterface { public void BarBar() { } interface IInterface { void BarBar(); } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullDifferentMembersFromClassToPartialInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { partial interface IInterface { } public class TestClass : IInterface { public int th[||]is[int i] { get => j = value; } private static void BarBar() {} protected static event EventHandler event1, event2; internal static int Foo { get; set; } } partial interface IInterface { } }"; var expected = @" using System; namespace PushUpTest { partial interface IInterface { int this[int i] { get; } int Foo { get; set; } event EventHandler event1; event EventHandler event2; void BarBar(); } public class TestClass : IInterface { public int this[int i] { get => j = value; } public void BarBar() {} public event EventHandler event1; public event EventHandler event2; public int Foo { get; set; } } partial interface IInterface { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullAsyncMethod() { var testText = @" using System.Threading.Tasks; internal interface IPullUp { } internal class PullUp : IPullUp { internal async Task PullU[||]pAsync() { await Task.Delay(1000); } }"; var expectedText = @" using System.Threading.Tasks; internal interface IPullUp { Task PullUpAsync(); } internal class PullUp : IPullUp { public async Task PullUpAsync() { await Task.Delay(1000); } }"; await TestWithPullMemberDialogAsync(testText, expectedText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMethodWithAbstractOptionToClassViaDialog() { var testText = @" namespace PushUpTest { public class Base { } public class TestClass : Base { public void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; var expected = @" namespace PushUpTest { public abstract class Base { public abstract void TestMethod(); } public class TestClass : Base { public override void TestMeth[||]od() { System.Console.WriteLine(""Hello World""); } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullAbstractMethodToClassViaDialog() { var testText = @" namespace PushUpTest { public class Base { } public abstract class TestClass : Base { public abstract void TestMeth[||]od(); } }"; var expected = @" namespace PushUpTest { public abstract class Base { public abstract void TestMethod(); } public abstract class TestClass : Base { } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("TestMethod", true) }, index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleEventsToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private static event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { private static event EventHandler Event1; private static event EventHandler Event3; private static event EventHandler Event4; } public class Testclass2 : Base2 { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullMultipleAbstractEventsToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public abstract class Testclass2 : ITest { protected abstract event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event1; event EventHandler Event3; event EventHandler Event4; } public abstract class Testclass2 : ITest { public abstract event EventHandler Event1; public abstract event EventHandler Event3; public abstract event EventHandler Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullAbstractEventToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public abstract class Testclass2 : Base2 { private static abstract event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public abstract class Base2 { private static abstract event EventHandler Event3; } public abstract class Testclass2 : Base2 { private static abstract event EventHandler Event1, Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicEventToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event3; } public class Testclass2 : ITest { public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullSingleNonPublicEventToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public abstract class TestClass2 : ITest { protected event EventHandler Eve[||]nt3; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { event EventHandler Event3; } public abstract class TestClass2 : ITest { public event EventHandler Event3; } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event3", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullNonPublicEventWithAddAndRemoveMethodToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { interface IInterface { } public class TestClass : IInterface { private event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { interface IInterface { event EventHandler Event1; } public class TestClass : IInterface { public event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", false) }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullFieldsToClassViaDialog() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { public int i, [||]j = 10, k = 100; } }"; var expected = @" using System; namespace PushUpTest { public class Base2 { public int i; public int j = 10; public int k = 100; } public class Testclass2 : Base2 { } }"; await TestWithPullMemberDialogAsync(testText, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyWithArrowToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private double Test[||]Property => 2.717; } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { get; } } public class Testclass2 : ITest { public readonly double TestProperty => 2.717; } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private double Test[||]Property { get; set; } } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { get; set; } } public class Testclass2 : ITest { public double TestProperty { get; set; } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullNonPublicPropertyWithSingleAccessorToInterfaceViaDialog() { var testText = @" using System; namespace PushUpTest { public interface ITest { } public class Testclass2 : ITest { private static double Test[||]Property { set; } } }"; var expected = @" using System; namespace PushUpTest { public interface ITest { double TestProperty { set; } } public class Testclass2 : ITest { public double Test[||]Property { set; } } }"; await TestWithPullMemberDialogAsync(testText, expected); } [WorkItem(34268, "https://github.com/dotnet/roslyn/issues/34268")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullPropertyToAbstractClassViaDialogWithMakeAbstractOption() { var testText = @" abstract class B { } class D : B { int [||]X => 7; }"; var expected = @" abstract class B { private abstract int X { get; } } class D : B { override int X => 7; }"; await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("X", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task PullEventUpToAbstractClassViaDialogWithMakeAbstractOption() { var testText = @" using System; namespace PushUpTest { public class Base2 { } public class Testclass2 : Base2 { private event EventHandler Event1, Eve[||]nt3, Event4; } }"; var expected = @" using System; namespace PushUpTest { public abstract class Base2 { private abstract event EventHandler Event3; } public class Testclass2 : Base2 { private event EventHandler Event1, Eve[||]nt3, Event4; } }"; await TestWithPullMemberDialogAsync(testText, expected, selection: new[] { ("Event3", true) }, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] public async Task TestPullEventWithAddAndRemoveMethodToClassViaDialogWithMakeAbstractOption() { var testText = @" using System; namespace PushUpTest { public class BaseClass { } public class TestClass : BaseClass { public event EventHandler Eve[||]nt1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; var expected = @" using System; namespace PushUpTest { public abstract class BaseClass { public abstract event EventHandler Event1; } public class TestClass : BaseClass { public override event EventHandler Event1 { add { System.Console.Writeline(""This is add""); } remove { System.Console.Writeline(""This is remove""); } } } }"; await TestWithPullMemberDialogAsync(testText, expected, new (string, bool)[] { ("Event1", true) }, index: 1); } #endregion Dialog #region Selections and caret position [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestArgsIsPartOfHeader() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [Test2] void C([||]) { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] [Test2] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretBeforeAttributes() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [||][Test] [Test2] void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] [Test2] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretBetweenAttributes() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [||][Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes1() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test] [|void C() { }|] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [|[Test] void C() { }|] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionWithAttributes3() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test][| void C() { } |] } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringInAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [[||]Test] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectionAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [|[Test] [Test2]|] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretInAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [[||]Test] [Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringCaretBetweenAttributeLists() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] [||][Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectionAttributeList2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [|[Test]|] [Test2] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestMissingRefactoringSelectAttributeList() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [|[Test]|] void C() { } } }"; await TestQuickActionNotProvidedAsync(testText); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLocAfterAttributes1() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { } public class B : A { [Test] [||]void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } public class A { [Test] void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLocAfterAttributes2() { var testText = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { } public class B : A { [Test] // Comment1 [Test2] // Comment2 [||]void C() { } } }"; var expected = @" using System; namespace PushUpTest { class TestAttribute : Attribute { } class Test2Attribute : Attribute { } public class A { [Test] // Comment1 [Test2] // Comment2 void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringCaretLoc1() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [||]void C() { } } }"; var expected = @" namespace PushUpTest { public class A { void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelection() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [|void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [| // Comment1 void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { // Comment1 void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments2() { var testText = @" namespace PushUpTest { public class A { } public class B : A { [|/// <summary> /// Test /// </summary> void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { /// <summary> /// Test /// </summary> void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsPullMemberUp)] [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] public async Task TestRefactoringSelectionComments3() { var testText = @" namespace PushUpTest { public class A { } public class B : A { /// <summary> [|/// Test /// </summary> void C() { }|] } }"; var expected = @" namespace PushUpTest { public class A { /// <summary> /// Test /// </summary> void C() { } } public class B : A { } }"; await TestInRegularAndScriptAsync(testText, expected); } #endregion } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Workspaces/Core/Portable/Shared/Extensions/ITypeSymbolExtensions.SubstituteTypesVisitor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal partial class ITypeSymbolExtensions { private class SubstituteTypesVisitor<TType1, TType2> : SymbolVisitor<ITypeSymbol> where TType1 : ITypeSymbol where TType2 : ITypeSymbol { // private readonly Compilation compilation; private readonly IDictionary<TType1, TType2> _map; private readonly ITypeGenerator _typeGenerator; internal SubstituteTypesVisitor( IDictionary<TType1, TType2> map, ITypeGenerator typeGenerator) { _map = map; _typeGenerator = typeGenerator; } public override ITypeSymbol DefaultVisit(ISymbol node) => throw new NotImplementedException(); private ITypeSymbol VisitType(ITypeSymbol symbol) { if (symbol is TType1 && _map.TryGetValue((TType1)symbol, out var converted)) { return converted; } return symbol; } public override ITypeSymbol VisitDynamicType(IDynamicTypeSymbol symbol) => VisitType(symbol); public override ITypeSymbol VisitTypeParameter(ITypeParameterSymbol symbol) => VisitType(symbol); public override ITypeSymbol VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { // TODO(https://github.com/dotnet/roslyn/issues/43890): also visit the underlying types of // the parameters and return value return VisitType(symbol); } public override ITypeSymbol VisitNamedType(INamedTypeSymbol symbol) { var mapped = VisitType(symbol); if (!Equals(mapped, symbol)) { return mapped; } if (symbol.IsAnonymousType) { return symbol; } // If we don't even have any type arguments, then there's nothing to do. var allTypeArguments = symbol.GetAllTypeArguments().ToList(); if (allTypeArguments.Count == 0) { return symbol; } // If we have a containing type, make sure its type arguments are updated as well. var updatedContainingType = symbol.ContainingType?.Accept(this); // If our containing type changed, then find us again in the new containing type. if (!Equals(updatedContainingType, symbol.ContainingType)) { symbol = updatedContainingType.GetTypeMembers(symbol.Name, symbol.Arity).First(m => m.TypeKind == symbol.TypeKind); } var substitutedArguments = symbol.TypeArguments.Select(t => t.Accept(this)); if (symbol.TypeArguments.SequenceEqual(substitutedArguments)) { return symbol; } return _typeGenerator.Construct(symbol.OriginalDefinition, substitutedArguments.ToArray()).WithNullableAnnotation(symbol.NullableAnnotation); } public override ITypeSymbol VisitArrayType(IArrayTypeSymbol symbol) { var mapped = VisitType(symbol); if (!Equals(mapped, symbol)) { return mapped; } var elementType = symbol.ElementType.Accept(this); if (elementType != null && elementType.Equals(symbol.ElementType)) { return symbol; } return _typeGenerator.CreateArrayTypeSymbol(elementType, symbol.Rank); } public override ITypeSymbol VisitPointerType(IPointerTypeSymbol symbol) { var mapped = VisitType(symbol); if (!Equals(mapped, symbol)) { return mapped; } var pointedAtType = symbol.PointedAtType.Accept(this); if (pointedAtType != null && pointedAtType.Equals(symbol.PointedAtType)) { return symbol; } return _typeGenerator.CreatePointerTypeSymbol(pointedAtType); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal partial class ITypeSymbolExtensions { private class SubstituteTypesVisitor<TType1, TType2> : SymbolVisitor<ITypeSymbol> where TType1 : ITypeSymbol where TType2 : ITypeSymbol { // private readonly Compilation compilation; private readonly IDictionary<TType1, TType2> _map; private readonly ITypeGenerator _typeGenerator; internal SubstituteTypesVisitor( IDictionary<TType1, TType2> map, ITypeGenerator typeGenerator) { _map = map; _typeGenerator = typeGenerator; } public override ITypeSymbol DefaultVisit(ISymbol node) => throw new NotImplementedException(); private ITypeSymbol VisitType(ITypeSymbol symbol) { if (symbol is TType1 && _map.TryGetValue((TType1)symbol, out var converted)) { return converted; } return symbol; } public override ITypeSymbol VisitDynamicType(IDynamicTypeSymbol symbol) => VisitType(symbol); public override ITypeSymbol VisitTypeParameter(ITypeParameterSymbol symbol) => VisitType(symbol); public override ITypeSymbol VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { // TODO(https://github.com/dotnet/roslyn/issues/43890): also visit the underlying types of // the parameters and return value return VisitType(symbol); } public override ITypeSymbol VisitNamedType(INamedTypeSymbol symbol) { var mapped = VisitType(symbol); if (!Equals(mapped, symbol)) { return mapped; } if (symbol.IsAnonymousType) { return symbol; } // If we don't even have any type arguments, then there's nothing to do. var allTypeArguments = symbol.GetAllTypeArguments().ToList(); if (allTypeArguments.Count == 0) { return symbol; } // If we have a containing type, make sure its type arguments are updated as well. var updatedContainingType = symbol.ContainingType?.Accept(this); // If our containing type changed, then find us again in the new containing type. if (!Equals(updatedContainingType, symbol.ContainingType)) { symbol = updatedContainingType.GetTypeMembers(symbol.Name, symbol.Arity).First(m => m.TypeKind == symbol.TypeKind); } var substitutedArguments = symbol.TypeArguments.Select(t => t.Accept(this)); if (symbol.TypeArguments.SequenceEqual(substitutedArguments)) { return symbol; } return _typeGenerator.Construct(symbol.OriginalDefinition, substitutedArguments.ToArray()).WithNullableAnnotation(symbol.NullableAnnotation); } public override ITypeSymbol VisitArrayType(IArrayTypeSymbol symbol) { var mapped = VisitType(symbol); if (!Equals(mapped, symbol)) { return mapped; } var elementType = symbol.ElementType.Accept(this); if (elementType != null && elementType.Equals(symbol.ElementType)) { return symbol; } return _typeGenerator.CreateArrayTypeSymbol(elementType, symbol.Rank); } public override ITypeSymbol VisitPointerType(IPointerTypeSymbol symbol) { var mapped = VisitType(symbol); if (!Equals(mapped, symbol)) { return mapped; } var pointedAtType = symbol.PointedAtType.Accept(this); if (pointedAtType != null && pointedAtType.Equals(symbol.PointedAtType)) { return symbol; } return _typeGenerator.CreatePointerTypeSymbol(pointedAtType); } } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Analyzers/Core/Analyzers/AddRequiredParentheses/AbstractAddRequiredParenthesesDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Precedence; using Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses; namespace Microsoft.CodeAnalysis.AddRequiredParentheses { internal abstract class AbstractAddRequiredParenthesesDiagnosticAnalyzer< TExpressionSyntax, TBinaryLikeExpressionSyntax, TLanguageKindEnum> : AbstractParenthesesDiagnosticAnalyzer where TExpressionSyntax : SyntaxNode where TBinaryLikeExpressionSyntax : TExpressionSyntax where TLanguageKindEnum : struct { private static readonly Dictionary<(bool includeInFixAll, string equivalenceKey), ImmutableDictionary<string, string?>> s_cachedProperties = new(); private readonly IPrecedenceService _precedenceService; static AbstractAddRequiredParenthesesDiagnosticAnalyzer() { var options = new[] { CodeStyleOptions2.ArithmeticBinaryParentheses, CodeStyleOptions2.OtherBinaryParentheses, CodeStyleOptions2.OtherParentheses, CodeStyleOptions2.RelationalBinaryParentheses }; var includeArray = new[] { false, true }; foreach (var option in options) { foreach (var includeInFixAll in includeArray) { var properties = ImmutableDictionary<string, string?>.Empty; if (includeInFixAll) { properties = properties.Add(AddRequiredParenthesesConstants.IncludeInFixAll, ""); } var equivalenceKey = GetEquivalenceKey(option); properties = properties.Add(AddRequiredParenthesesConstants.EquivalenceKey, equivalenceKey); s_cachedProperties.Add((includeInFixAll, equivalenceKey), properties); } } } private static string GetEquivalenceKey(PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> parentPrecedence) => parentPrecedence.Name; private static ImmutableDictionary<string, string?> GetProperties(bool includeInFixAll, string equivalenceKey) => s_cachedProperties[(includeInFixAll, equivalenceKey)]; protected abstract int GetPrecedence(TBinaryLikeExpressionSyntax binaryLike); protected abstract TExpressionSyntax? TryGetAppropriateParent(TBinaryLikeExpressionSyntax binaryLike); protected abstract bool IsBinaryLike(TExpressionSyntax node); protected abstract (TExpressionSyntax, SyntaxToken, TExpressionSyntax) GetPartsOfBinaryLike(TBinaryLikeExpressionSyntax binaryLike); protected AbstractAddRequiredParenthesesDiagnosticAnalyzer(IPrecedenceService precedenceService) : base(IDEDiagnosticIds.AddRequiredParenthesesDiagnosticId, EnforceOnBuildValues.AddRequiredParentheses, new LocalizableResourceString(nameof(AnalyzersResources.Add_parentheses_for_clarity), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Parentheses_should_be_added_for_clarity), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { _precedenceService = precedenceService; } public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, GetSyntaxNodeKinds()); protected abstract ImmutableArray<TLanguageKindEnum> GetSyntaxNodeKinds(); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var binaryLike = (TBinaryLikeExpressionSyntax)context.Node; var parent = TryGetAppropriateParent(binaryLike); if (parent == null || !IsBinaryLike(parent)) { return; } var parentBinaryLike = (TBinaryLikeExpressionSyntax)parent; if (GetPrecedence(binaryLike) == GetPrecedence(parentBinaryLike)) { return; } var childPrecedence = GetLanguageOption(_precedenceService.GetPrecedenceKind(binaryLike)); var parentPrecedence = GetLanguageOption(_precedenceService.GetPrecedenceKind(parentBinaryLike)); // only add parentheses within the same precedence band. if (parentPrecedence != childPrecedence) { return; } var preference = context.GetOption(parentPrecedence, binaryLike.Language); if (preference.Value != ParenthesesPreference.AlwaysForClarity) { return; } var additionalLocations = ImmutableArray.Create(binaryLike.GetLocation()); var precedence = GetPrecedence(binaryLike); var equivalenceKey = GetEquivalenceKey(parentPrecedence); // In a case like "a + b * c * d", we'll add parens to make "a + (b * c * d)". // To make this user experience more pleasant, we will place the diagnostic on // both *'s. AddDiagnostics( context, binaryLike, precedence, preference.Notification.Severity, additionalLocations, equivalenceKey, includeInFixAll: true); } private void AddDiagnostics( SyntaxNodeAnalysisContext context, TBinaryLikeExpressionSyntax? binaryLikeOpt, int precedence, ReportDiagnostic severity, ImmutableArray<Location> additionalLocations, string equivalenceKey, bool includeInFixAll) { if (binaryLikeOpt != null && IsBinaryLike(binaryLikeOpt) && GetPrecedence(binaryLikeOpt) == precedence) { var (left, operatorToken, right) = GetPartsOfBinaryLike(binaryLikeOpt); var properties = GetProperties(includeInFixAll, equivalenceKey); context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, operatorToken.GetLocation(), severity, additionalLocations, properties)); // We're adding diagnostics for all subcomponents so that the user can get the // lightbulb on any of the operator tokens. However, we don't actually want to // 'fix' all of these if the user does a fix-all. if we did, we'd end up adding far // too many parens to the same expr. AddDiagnostics(context, left as TBinaryLikeExpressionSyntax, precedence, severity, additionalLocations, equivalenceKey, includeInFixAll: false); AddDiagnostics(context, right as TBinaryLikeExpressionSyntax, precedence, severity, additionalLocations, equivalenceKey, includeInFixAll: 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.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Precedence; using Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses; namespace Microsoft.CodeAnalysis.AddRequiredParentheses { internal abstract class AbstractAddRequiredParenthesesDiagnosticAnalyzer< TExpressionSyntax, TBinaryLikeExpressionSyntax, TLanguageKindEnum> : AbstractParenthesesDiagnosticAnalyzer where TExpressionSyntax : SyntaxNode where TBinaryLikeExpressionSyntax : TExpressionSyntax where TLanguageKindEnum : struct { private static readonly Dictionary<(bool includeInFixAll, string equivalenceKey), ImmutableDictionary<string, string?>> s_cachedProperties = new(); private readonly IPrecedenceService _precedenceService; static AbstractAddRequiredParenthesesDiagnosticAnalyzer() { var options = new[] { CodeStyleOptions2.ArithmeticBinaryParentheses, CodeStyleOptions2.OtherBinaryParentheses, CodeStyleOptions2.OtherParentheses, CodeStyleOptions2.RelationalBinaryParentheses }; var includeArray = new[] { false, true }; foreach (var option in options) { foreach (var includeInFixAll in includeArray) { var properties = ImmutableDictionary<string, string?>.Empty; if (includeInFixAll) { properties = properties.Add(AddRequiredParenthesesConstants.IncludeInFixAll, ""); } var equivalenceKey = GetEquivalenceKey(option); properties = properties.Add(AddRequiredParenthesesConstants.EquivalenceKey, equivalenceKey); s_cachedProperties.Add((includeInFixAll, equivalenceKey), properties); } } } private static string GetEquivalenceKey(PerLanguageOption2<CodeStyleOption2<ParenthesesPreference>> parentPrecedence) => parentPrecedence.Name; private static ImmutableDictionary<string, string?> GetProperties(bool includeInFixAll, string equivalenceKey) => s_cachedProperties[(includeInFixAll, equivalenceKey)]; protected abstract int GetPrecedence(TBinaryLikeExpressionSyntax binaryLike); protected abstract TExpressionSyntax? TryGetAppropriateParent(TBinaryLikeExpressionSyntax binaryLike); protected abstract bool IsBinaryLike(TExpressionSyntax node); protected abstract (TExpressionSyntax, SyntaxToken, TExpressionSyntax) GetPartsOfBinaryLike(TBinaryLikeExpressionSyntax binaryLike); protected AbstractAddRequiredParenthesesDiagnosticAnalyzer(IPrecedenceService precedenceService) : base(IDEDiagnosticIds.AddRequiredParenthesesDiagnosticId, EnforceOnBuildValues.AddRequiredParentheses, new LocalizableResourceString(nameof(AnalyzersResources.Add_parentheses_for_clarity), AnalyzersResources.ResourceManager, typeof(AnalyzersResources)), new LocalizableResourceString(nameof(AnalyzersResources.Parentheses_should_be_added_for_clarity), AnalyzersResources.ResourceManager, typeof(AnalyzersResources))) { _precedenceService = precedenceService; } public sealed override DiagnosticAnalyzerCategory GetAnalyzerCategory() => DiagnosticAnalyzerCategory.SemanticSpanAnalysis; protected sealed override void InitializeWorker(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSyntax, GetSyntaxNodeKinds()); protected abstract ImmutableArray<TLanguageKindEnum> GetSyntaxNodeKinds(); private void AnalyzeSyntax(SyntaxNodeAnalysisContext context) { var binaryLike = (TBinaryLikeExpressionSyntax)context.Node; var parent = TryGetAppropriateParent(binaryLike); if (parent == null || !IsBinaryLike(parent)) { return; } var parentBinaryLike = (TBinaryLikeExpressionSyntax)parent; if (GetPrecedence(binaryLike) == GetPrecedence(parentBinaryLike)) { return; } var childPrecedence = GetLanguageOption(_precedenceService.GetPrecedenceKind(binaryLike)); var parentPrecedence = GetLanguageOption(_precedenceService.GetPrecedenceKind(parentBinaryLike)); // only add parentheses within the same precedence band. if (parentPrecedence != childPrecedence) { return; } var preference = context.GetOption(parentPrecedence, binaryLike.Language); if (preference.Value != ParenthesesPreference.AlwaysForClarity) { return; } var additionalLocations = ImmutableArray.Create(binaryLike.GetLocation()); var precedence = GetPrecedence(binaryLike); var equivalenceKey = GetEquivalenceKey(parentPrecedence); // In a case like "a + b * c * d", we'll add parens to make "a + (b * c * d)". // To make this user experience more pleasant, we will place the diagnostic on // both *'s. AddDiagnostics( context, binaryLike, precedence, preference.Notification.Severity, additionalLocations, equivalenceKey, includeInFixAll: true); } private void AddDiagnostics( SyntaxNodeAnalysisContext context, TBinaryLikeExpressionSyntax? binaryLikeOpt, int precedence, ReportDiagnostic severity, ImmutableArray<Location> additionalLocations, string equivalenceKey, bool includeInFixAll) { if (binaryLikeOpt != null && IsBinaryLike(binaryLikeOpt) && GetPrecedence(binaryLikeOpt) == precedence) { var (left, operatorToken, right) = GetPartsOfBinaryLike(binaryLikeOpt); var properties = GetProperties(includeInFixAll, equivalenceKey); context.ReportDiagnostic(DiagnosticHelper.Create( Descriptor, operatorToken.GetLocation(), severity, additionalLocations, properties)); // We're adding diagnostics for all subcomponents so that the user can get the // lightbulb on any of the operator tokens. However, we don't actually want to // 'fix' all of these if the user does a fix-all. if we did, we'd end up adding far // too many parens to the same expr. AddDiagnostics(context, left as TBinaryLikeExpressionSyntax, precedence, severity, additionalLocations, equivalenceKey, includeInFixAll: false); AddDiagnostics(context, right as TBinaryLikeExpressionSyntax, precedence, severity, additionalLocations, equivalenceKey, includeInFixAll: false); } } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Workspaces/Remote/ServiceHub/Host/RemoteDocumentDifferenceService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Provide document difference service specific to remote workspace's behavior. /// /// Default <see cref="AbstractDocumentDifferenceService"/> is optimized for typing case in editor where we have events /// for each typing. But in remote workspace, we aggregate changes and update solution in bulk and we don't have concept /// of active file making default implementation unsuitable. Functionally, default one is still correct, but it often /// time makes us to do more than we need. Basically, it always says this project has semantic change which can cause /// a lot of re-analysis. /// </summary> internal class RemoteDocumentDifferenceService : IDocumentDifferenceService { [ExportLanguageService(typeof(IDocumentDifferenceService), LanguageNames.CSharp, layer: WorkspaceKind.Host), Shared] internal sealed class CSharpDocumentDifferenceService : RemoteDocumentDifferenceService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpDocumentDifferenceService() { } } [ExportLanguageService(typeof(IDocumentDifferenceService), LanguageNames.VisualBasic, layer: WorkspaceKind.Host), Shared] internal sealed class VisualBasicDocumentDifferenceService : AbstractDocumentDifferenceService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualBasicDocumentDifferenceService() { } } public async Task<DocumentDifferenceResult?> GetDifferenceAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken) { // in remote workspace, we don't trust any version based on VersionStamp. we only trust content based information such as // checksum or tree comparison and etc. // first check checksum var oldTextChecksum = (await oldDocument.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false)).Text; var newTextChecksum = (await newDocument.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false)).Text; if (oldTextChecksum == newTextChecksum) { // null means nothing has changed. return null; } var oldRoot = await oldDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // the service is only registered for C# and VB documents, which must have syntax trees: Contract.ThrowIfNull(oldRoot); Contract.ThrowIfNull(newRoot); if (oldRoot.IsEquivalentTo(newRoot, topLevel: true)) { // only method body changed return new DocumentDifferenceResult(InvocationReasons.SyntaxChanged); } // semantic has changed as well. return new DocumentDifferenceResult(InvocationReasons.DocumentChanged); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.CodeAnalysis.SolutionCrawler; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Provide document difference service specific to remote workspace's behavior. /// /// Default <see cref="AbstractDocumentDifferenceService"/> is optimized for typing case in editor where we have events /// for each typing. But in remote workspace, we aggregate changes and update solution in bulk and we don't have concept /// of active file making default implementation unsuitable. Functionally, default one is still correct, but it often /// time makes us to do more than we need. Basically, it always says this project has semantic change which can cause /// a lot of re-analysis. /// </summary> internal class RemoteDocumentDifferenceService : IDocumentDifferenceService { [ExportLanguageService(typeof(IDocumentDifferenceService), LanguageNames.CSharp, layer: WorkspaceKind.Host), Shared] internal sealed class CSharpDocumentDifferenceService : RemoteDocumentDifferenceService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpDocumentDifferenceService() { } } [ExportLanguageService(typeof(IDocumentDifferenceService), LanguageNames.VisualBasic, layer: WorkspaceKind.Host), Shared] internal sealed class VisualBasicDocumentDifferenceService : AbstractDocumentDifferenceService { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public VisualBasicDocumentDifferenceService() { } } public async Task<DocumentDifferenceResult?> GetDifferenceAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken) { // in remote workspace, we don't trust any version based on VersionStamp. we only trust content based information such as // checksum or tree comparison and etc. // first check checksum var oldTextChecksum = (await oldDocument.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false)).Text; var newTextChecksum = (await newDocument.State.GetStateChecksumsAsync(cancellationToken).ConfigureAwait(false)).Text; if (oldTextChecksum == newTextChecksum) { // null means nothing has changed. return null; } var oldRoot = await oldDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); // the service is only registered for C# and VB documents, which must have syntax trees: Contract.ThrowIfNull(oldRoot); Contract.ThrowIfNull(newRoot); if (oldRoot.IsEquivalentTo(newRoot, topLevel: true)) { // only method body changed return new DocumentDifferenceResult(InvocationReasons.SyntaxChanged); } // semantic has changed as well. return new DocumentDifferenceResult(InvocationReasons.DocumentChanged); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Extensions/SyntaxTreeExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class SyntaxTreeExtensions { public static bool OverlapsHiddenPosition([NotNullWhen(returnValue: true)] this SyntaxTree? tree, TextSpan span, CancellationToken cancellationToken) { if (tree == null) { return false; } var text = tree.GetText(cancellationToken); return text.OverlapsHiddenPosition(span, (position, cancellationToken2) => { // implements the ASP.NET IsHidden rule var lineVisibility = tree.GetLineVisibility(position, cancellationToken2); return lineVisibility is LineVisibility.Hidden or LineVisibility.BeforeFirstLineDirective; }, cancellationToken); } public static bool IsScript(this SyntaxTree syntaxTree) => syntaxTree.Options.Kind != SourceCodeKind.Regular; /// <summary> /// Returns the identifier, keyword, contextual keyword or preprocessor keyword touching this /// position, or a token of Kind = None if the caret is not touching either. /// </summary> public static Task<SyntaxToken> GetTouchingWordAsync( this SyntaxTree syntaxTree, int position, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken, bool findInsideTrivia = false) { return GetTouchingTokenAsync(syntaxTree, position, syntaxFacts.IsWord, cancellationToken, findInsideTrivia); } public static Task<SyntaxToken> GetTouchingTokenAsync( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool findInsideTrivia = false) { return GetTouchingTokenAsync(syntaxTree, position, _ => true, cancellationToken, findInsideTrivia); } public static async Task<SyntaxToken> GetTouchingTokenAsync( this SyntaxTree syntaxTree, int position, Predicate<SyntaxToken> predicate, CancellationToken cancellationToken, bool findInsideTrivia = false) { Contract.ThrowIfNull(syntaxTree); if (position >= syntaxTree.Length) { return default; } var root = await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position, findInsideTrivia); if ((token.Span.Contains(position) || token.Span.End == position) && predicate(token)) { return token; } token = token.GetPreviousToken(); if (token.Span.End == position && predicate(token)) { return token; } // SyntaxKind = None return default; } public static bool IsEntirelyHidden(this SyntaxTree tree, TextSpan span, CancellationToken cancellationToken) { if (!tree.HasHiddenRegions()) { return false; } var text = tree.GetText(cancellationToken); var startLineNumber = text.Lines.IndexOf(span.Start); var endLineNumber = text.Lines.IndexOf(span.End); for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { cancellationToken.ThrowIfCancellationRequested(); var linePosition = text.Lines[lineNumber].Start; if (!tree.IsHiddenPosition(linePosition, cancellationToken)) { return false; } } return true; } public static bool IsBeforeFirstToken(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var root = syntaxTree.GetRoot(cancellationToken); var firstToken = root.GetFirstToken(includeZeroWidth: true, includeSkipped: true); return position <= firstToken.SpanStart; } public static SyntaxToken FindTokenOrEndToken( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { Contract.ThrowIfNull(syntaxTree); var root = syntaxTree.GetRoot(cancellationToken); var result = root.FindToken(position, findInsideTrivia: true); if (result.RawKind != 0) { return result; } // Special cases. See if we're actually at the end of a: // a) doc comment // b) pp directive // c) file var compilationUnit = (ICompilationUnitSyntax)root; var triviaList = compilationUnit.EndOfFileToken.LeadingTrivia; foreach (var trivia in triviaList.Reverse()) { if (trivia.HasStructure) { var token = trivia.GetStructure()!.GetLastToken(includeZeroWidth: true); if (token.Span.End == position) { return token; } } } if (position == root.FullSpan.End) { return compilationUnit.EndOfFileToken; } return default; } internal static SyntaxTrivia FindTriviaAndAdjustForEndOfFile( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool findInsideTrivia = false) { var root = syntaxTree.GetRoot(cancellationToken); var trivia = root.FindTrivia(position, findInsideTrivia); // If we ask right at the end of the file, we'll get back nothing. // We handle that case specially for now, though SyntaxTree.FindTrivia should // work at the end of a file. if (position == root.FullWidth()) { var compilationUnit = (ICompilationUnitSyntax)root; var endOfFileToken = compilationUnit.EndOfFileToken; if (endOfFileToken.HasLeadingTrivia) { trivia = endOfFileToken.LeadingTrivia.Last(); } else { var token = endOfFileToken.GetPreviousToken(includeSkipped: true); if (token.HasTrailingTrivia) { trivia = token.TrailingTrivia.Last(); } } } return trivia; } /// <summary> /// If the position is inside of token, return that token; otherwise, return the token to the right. /// </summary> public static SyntaxToken FindTokenOnRightOfPosition( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false) { return syntaxTree.GetRoot(cancellationToken).FindTokenOnRightOfPosition( position, includeSkipped, includeDirectives, includeDocumentationComments); } /// <summary> /// If the position is inside of token, return that token; otherwise, return the token to the left. /// </summary> public static SyntaxToken FindTokenOnLeftOfPosition( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false) { return syntaxTree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition( position, includeSkipped, includeDirectives, includeDocumentationComments); } public static bool IsGeneratedCode(this SyntaxTree syntaxTree, AnalyzerOptions? analyzerOptions, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { // First check if user has configured "generated_code = true | false" in .editorconfig if (analyzerOptions != null) { var analyzerConfigOptions = analyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(syntaxTree); var isUserConfiguredGeneratedCode = GeneratedCodeUtilities.GetIsGeneratedCodeFromOptions(analyzerConfigOptions); if (isUserConfiguredGeneratedCode.HasValue) { return isUserConfiguredGeneratedCode.Value; } } // Otherwise, fallback to generated code heuristic. return GeneratedCodeUtilities.IsGeneratedCode( syntaxTree, t => syntaxFacts.IsRegularComment(t) || syntaxFacts.IsDocumentationComment(t), 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.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class SyntaxTreeExtensions { public static bool OverlapsHiddenPosition([NotNullWhen(returnValue: true)] this SyntaxTree? tree, TextSpan span, CancellationToken cancellationToken) { if (tree == null) { return false; } var text = tree.GetText(cancellationToken); return text.OverlapsHiddenPosition(span, (position, cancellationToken2) => { // implements the ASP.NET IsHidden rule var lineVisibility = tree.GetLineVisibility(position, cancellationToken2); return lineVisibility is LineVisibility.Hidden or LineVisibility.BeforeFirstLineDirective; }, cancellationToken); } public static bool IsScript(this SyntaxTree syntaxTree) => syntaxTree.Options.Kind != SourceCodeKind.Regular; /// <summary> /// Returns the identifier, keyword, contextual keyword or preprocessor keyword touching this /// position, or a token of Kind = None if the caret is not touching either. /// </summary> public static Task<SyntaxToken> GetTouchingWordAsync( this SyntaxTree syntaxTree, int position, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken, bool findInsideTrivia = false) { return GetTouchingTokenAsync(syntaxTree, position, syntaxFacts.IsWord, cancellationToken, findInsideTrivia); } public static Task<SyntaxToken> GetTouchingTokenAsync( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool findInsideTrivia = false) { return GetTouchingTokenAsync(syntaxTree, position, _ => true, cancellationToken, findInsideTrivia); } public static async Task<SyntaxToken> GetTouchingTokenAsync( this SyntaxTree syntaxTree, int position, Predicate<SyntaxToken> predicate, CancellationToken cancellationToken, bool findInsideTrivia = false) { Contract.ThrowIfNull(syntaxTree); if (position >= syntaxTree.Length) { return default; } var root = await syntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position, findInsideTrivia); if ((token.Span.Contains(position) || token.Span.End == position) && predicate(token)) { return token; } token = token.GetPreviousToken(); if (token.Span.End == position && predicate(token)) { return token; } // SyntaxKind = None return default; } public static bool IsEntirelyHidden(this SyntaxTree tree, TextSpan span, CancellationToken cancellationToken) { if (!tree.HasHiddenRegions()) { return false; } var text = tree.GetText(cancellationToken); var startLineNumber = text.Lines.IndexOf(span.Start); var endLineNumber = text.Lines.IndexOf(span.End); for (var lineNumber = startLineNumber; lineNumber <= endLineNumber; lineNumber++) { cancellationToken.ThrowIfCancellationRequested(); var linePosition = text.Lines[lineNumber].Start; if (!tree.IsHiddenPosition(linePosition, cancellationToken)) { return false; } } return true; } public static bool IsBeforeFirstToken(this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { var root = syntaxTree.GetRoot(cancellationToken); var firstToken = root.GetFirstToken(includeZeroWidth: true, includeSkipped: true); return position <= firstToken.SpanStart; } public static SyntaxToken FindTokenOrEndToken( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken) { Contract.ThrowIfNull(syntaxTree); var root = syntaxTree.GetRoot(cancellationToken); var result = root.FindToken(position, findInsideTrivia: true); if (result.RawKind != 0) { return result; } // Special cases. See if we're actually at the end of a: // a) doc comment // b) pp directive // c) file var compilationUnit = (ICompilationUnitSyntax)root; var triviaList = compilationUnit.EndOfFileToken.LeadingTrivia; foreach (var trivia in triviaList.Reverse()) { if (trivia.HasStructure) { var token = trivia.GetStructure()!.GetLastToken(includeZeroWidth: true); if (token.Span.End == position) { return token; } } } if (position == root.FullSpan.End) { return compilationUnit.EndOfFileToken; } return default; } internal static SyntaxTrivia FindTriviaAndAdjustForEndOfFile( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool findInsideTrivia = false) { var root = syntaxTree.GetRoot(cancellationToken); var trivia = root.FindTrivia(position, findInsideTrivia); // If we ask right at the end of the file, we'll get back nothing. // We handle that case specially for now, though SyntaxTree.FindTrivia should // work at the end of a file. if (position == root.FullWidth()) { var compilationUnit = (ICompilationUnitSyntax)root; var endOfFileToken = compilationUnit.EndOfFileToken; if (endOfFileToken.HasLeadingTrivia) { trivia = endOfFileToken.LeadingTrivia.Last(); } else { var token = endOfFileToken.GetPreviousToken(includeSkipped: true); if (token.HasTrailingTrivia) { trivia = token.TrailingTrivia.Last(); } } } return trivia; } /// <summary> /// If the position is inside of token, return that token; otherwise, return the token to the right. /// </summary> public static SyntaxToken FindTokenOnRightOfPosition( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false) { return syntaxTree.GetRoot(cancellationToken).FindTokenOnRightOfPosition( position, includeSkipped, includeDirectives, includeDocumentationComments); } /// <summary> /// If the position is inside of token, return that token; otherwise, return the token to the left. /// </summary> public static SyntaxToken FindTokenOnLeftOfPosition( this SyntaxTree syntaxTree, int position, CancellationToken cancellationToken, bool includeSkipped = true, bool includeDirectives = false, bool includeDocumentationComments = false) { return syntaxTree.GetRoot(cancellationToken).FindTokenOnLeftOfPosition( position, includeSkipped, includeDirectives, includeDocumentationComments); } public static bool IsGeneratedCode(this SyntaxTree syntaxTree, AnalyzerOptions? analyzerOptions, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken) { // First check if user has configured "generated_code = true | false" in .editorconfig if (analyzerOptions != null) { var analyzerConfigOptions = analyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(syntaxTree); var isUserConfiguredGeneratedCode = GeneratedCodeUtilities.GetIsGeneratedCodeFromOptions(analyzerConfigOptions); if (isUserConfiguredGeneratedCode.HasValue) { return isUserConfiguredGeneratedCode.Value; } } // Otherwise, fallback to generated code heuristic. return GeneratedCodeUtilities.IsGeneratedCode( syntaxTree, t => syntaxFacts.IsRegularComment(t) || syntaxFacts.IsDocumentationComment(t), cancellationToken); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol_ImplementationChecks.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal delegate void ReportMismatchInReturnType<TArg>(BindingDiagnosticBag bag, MethodSymbol overriddenMethod, MethodSymbol overridingMethod, bool topLevel, TArg arg); internal delegate void ReportMismatchInParameterType<TArg>(BindingDiagnosticBag bag, MethodSymbol overriddenMethod, MethodSymbol overridingMethod, ParameterSymbol parameter, bool topLevel, TArg arg); internal partial class SourceMemberContainerTypeSymbol { /// <summary> /// In some circumstances (e.g. implicit implementation of an interface method by a non-virtual method in a /// base type from another assembly) it is necessary for the compiler to generate explicit implementations for /// some interface methods. They don't go in the symbol table, but if we are emitting, then we should /// generate code for them. /// </summary> internal SynthesizedExplicitImplementations GetSynthesizedExplicitImplementations( CancellationToken cancellationToken) { if (_lazySynthesizedExplicitImplementations is null) { var diagnostics = BindingDiagnosticBag.GetInstance(); try { cancellationToken.ThrowIfCancellationRequested(); CheckMembersAgainstBaseType(diagnostics, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); CheckAbstractClassImplementations(diagnostics); cancellationToken.ThrowIfCancellationRequested(); CheckInterfaceUnification(diagnostics); if (this.IsInterface) { cancellationToken.ThrowIfCancellationRequested(); this.CheckInterfaceVarianceSafety(diagnostics); } if (Interlocked.CompareExchange( ref _lazySynthesizedExplicitImplementations, ComputeInterfaceImplementations(diagnostics, cancellationToken), null) is null) { // Do not cancel from this point on. We've assigned the member, so we must add // the diagnostics. AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.SynthesizedExplicitImplementations); } } finally { diagnostics.Free(); } } return _lazySynthesizedExplicitImplementations; } internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { SynthesizedExplicitImplementations synthesizedImplementations = GetSynthesizedExplicitImplementations(cancellationToken: default); foreach (var methodImpl in synthesizedImplementations.MethodImpls) { yield return methodImpl; } foreach (var forwardingMethod in synthesizedImplementations.ForwardingMethods) { yield return (forwardingMethod.ImplementingMethod, forwardingMethod.ExplicitInterfaceImplementations.Single()); } } private void CheckAbstractClassImplementations(BindingDiagnosticBag diagnostics) { NamedTypeSymbol baseType = this.BaseTypeNoUseSiteDiagnostics; if (this.IsAbstract || (object)baseType == null || !baseType.IsAbstract) { return; } // CONSIDER: We know that no-one will ask for NotOverriddenAbstractMembers again // (since this class is concrete), so we could just call the construction method // directly to avoid storing the result. foreach (var abstractMember in this.AbstractMembers) { // Dev10 reports failure to implement properties/events in terms of the accessors if (abstractMember.Kind == SymbolKind.Method && abstractMember is not SynthesizedRecordOrdinaryMethod) { diagnostics.Add(ErrorCode.ERR_UnimplementedAbstractMethod, this.Locations[0], this, abstractMember); } } } private SynthesizedExplicitImplementations ComputeInterfaceImplementations( BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) { var forwardingMethods = ArrayBuilder<SynthesizedExplicitImplementationForwardingMethod>.GetInstance(); var methodImpls = ArrayBuilder<(MethodSymbol Body, MethodSymbol Implemented)>.GetInstance(); // NOTE: We can't iterator over this collection directly, since it is not ordered. Instead we // iterate over AllInterfaces and filter out the interfaces that are not in this set. This is // preferable to doing the DFS ourselves because both AllInterfaces and // InterfacesAndTheirBaseInterfaces are cached and used in multiple places. MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> interfacesAndTheirBases = this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics; foreach (var @interface in this.AllInterfacesNoUseSiteDiagnostics) { cancellationToken.ThrowIfCancellationRequested(); if (!interfacesAndTheirBases[@interface].Contains(@interface)) { continue; } HasBaseTypeDeclaringInterfaceResult? hasBaseClassDeclaringInterface = null; foreach (var interfaceMember in @interface.GetMembers()) { cancellationToken.ThrowIfCancellationRequested(); // Only require implementations for members that can be implemented in C#. SymbolKind interfaceMemberKind = interfaceMember.Kind; switch (interfaceMemberKind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: if (!interfaceMember.IsImplementableInterfaceMember()) { continue; } break; default: continue; } SymbolAndDiagnostics implementingMemberAndDiagnostics; if (this.IsInterface) { MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = this.GetExplicitImplementationForInterfaceMember(interfaceMember); switch (explicitImpl.Count) { case 0: continue; // There is no requirement to implement anything in an interface case 1: implementingMemberAndDiagnostics = new SymbolAndDiagnostics(explicitImpl.Single(), ImmutableBindingDiagnostic<AssemblySymbol>.Empty); break; default: Diagnostic diag = new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_DuplicateExplicitImpl, interfaceMember), this.Locations[0]); implementingMemberAndDiagnostics = new SymbolAndDiagnostics(null, new ImmutableBindingDiagnostic<AssemblySymbol>(ImmutableArray.Create(diag), default)); break; } } else { implementingMemberAndDiagnostics = this.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMember); } var implementingMember = implementingMemberAndDiagnostics.Symbol; var synthesizedImplementation = this.SynthesizeInterfaceMemberImplementation(implementingMemberAndDiagnostics, interfaceMember); bool wasImplementingMemberFound = (object)implementingMember != null; if (synthesizedImplementation.ForwardingMethod is SynthesizedExplicitImplementationForwardingMethod forwardingMethod) { if (forwardingMethod.IsVararg) { diagnostics.Add( ErrorCode.ERR_InterfaceImplementedImplicitlyByVariadic, GetImplicitImplementationDiagnosticLocation(interfaceMember, this, implementingMember), implementingMember, interfaceMember, this); } else { forwardingMethods.Add(forwardingMethod); } } if (synthesizedImplementation.MethodImpl is { } methodImpl) { Debug.Assert(methodImpl is { Body: not null, Implemented: not null }); methodImpls.Add(methodImpl); } if (wasImplementingMemberFound && interfaceMemberKind == SymbolKind.Event) { // NOTE: unlike dev11, we're including a related location for the implementing type, because // otherwise the only error location will be in the containing type of the implementing event // (i.e. no indication of which type's interface list is actually problematic). EventSymbol interfaceEvent = (EventSymbol)interfaceMember; EventSymbol implementingEvent = (EventSymbol)implementingMember; EventSymbol maybeWinRTEvent; EventSymbol maybeRegularEvent; if (interfaceEvent.IsWindowsRuntimeEvent) { maybeWinRTEvent = interfaceEvent; // Definitely WinRT. maybeRegularEvent = implementingEvent; // Maybe regular. } else { maybeWinRTEvent = implementingEvent; // Maybe WinRT. maybeRegularEvent = interfaceEvent; // Definitely regular. } if (interfaceEvent.IsWindowsRuntimeEvent != implementingEvent.IsWindowsRuntimeEvent) { // At this point (and not before), we know that maybeWinRTEvent is definitely a WinRT event and maybeRegularEvent is definitely a regular event. var args = new object[] { implementingEvent, interfaceEvent, maybeWinRTEvent, maybeRegularEvent }; var info = new CSDiagnosticInfo(ErrorCode.ERR_MixingWinRTEventWithRegular, args, ImmutableArray<Symbol>.Empty, ImmutableArray.Create<Location>(this.Locations[0])); diagnostics.Add(info, implementingEvent.Locations[0]); } } // Dev10: If a whole property is missing, report the property. If the property is present, but an accessor // is missing, report just the accessor. var associatedPropertyOrEvent = interfaceMemberKind == SymbolKind.Method ? ((MethodSymbol)interfaceMember).AssociatedSymbol : null; if ((object)associatedPropertyOrEvent == null || ReportAccessorOfInterfacePropertyOrEvent(associatedPropertyOrEvent) || (wasImplementingMemberFound && !implementingMember.IsAccessor())) { //we're here because //(a) the interface member is not an accessor, or //(b) the interface member is an accessor of an interesting (see ReportAccessorOfInterfacePropertyOrEvent) property or event, or //(c) the implementing member exists and is not an accessor. bool reportedAnError = false; if (implementingMemberAndDiagnostics.Diagnostics.Diagnostics.Any()) { diagnostics.AddRange(implementingMemberAndDiagnostics.Diagnostics); reportedAnError = implementingMemberAndDiagnostics.Diagnostics.Diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error); } if (!reportedAnError) { if (!wasImplementingMemberFound || (!implementingMember.ContainingType.Equals(this, TypeCompareKind.ConsiderEverything) && implementingMember.GetExplicitInterfaceImplementations().Contains(interfaceMember, ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance))) { // NOTE: An alternative approach would be to keep track of this while searching for the implementing member. // In some cases, we might even be able to stop looking and just accept that a base type has things covered // (though we'd have to be careful about losing diagnostics and we might produce fewer bridge methods). // However, this approach has the advantage that there is no cost unless we encounter a base type that // claims to implement an interface, but we can't figure out how (i.e. free in nearly all cases). hasBaseClassDeclaringInterface = hasBaseClassDeclaringInterface ?? HasBaseClassDeclaringInterface(@interface); HasBaseTypeDeclaringInterfaceResult matchResult = hasBaseClassDeclaringInterface.GetValueOrDefault(); if (matchResult != HasBaseTypeDeclaringInterfaceResult.ExactMatch && wasImplementingMemberFound && implementingMember.ContainingType.IsInterface) { HasBaseInterfaceDeclaringInterface(implementingMember.ContainingType, @interface, ref matchResult); } // If a base type from metadata declares that it implements the interface, we'll just trust it. // (See fFoundImport in SymbolPreparer::CheckInterfaceMethodImplementation.) switch (matchResult) { case HasBaseTypeDeclaringInterfaceResult.NoMatch: { // CONSIDER: Dev10 does not emit this diagnostic for interface properties if the // derived type attempts to implement an accessor directly as a method. // Suppress for bogus properties and events and for indexed properties. if (!interfaceMember.MustCallMethodsDirectly() && !interfaceMember.IsIndexedProperty()) { DiagnosticInfo useSiteDiagnostic = interfaceMember.GetUseSiteInfo().DiagnosticInfo; if (useSiteDiagnostic != null && useSiteDiagnostic.DefaultSeverity == DiagnosticSeverity.Error) { diagnostics.Add(useSiteDiagnostic, GetImplementsLocationOrFallback(@interface)); } else { diagnostics.Add(ErrorCode.ERR_UnimplementedInterfaceMember, GetImplementsLocationOrFallback(@interface), this, interfaceMember); } } } break; case HasBaseTypeDeclaringInterfaceResult.ExactMatch: break; case HasBaseTypeDeclaringInterfaceResult.IgnoringNullableMatch: diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, GetImplementsLocationOrFallback(@interface), this, interfaceMember); break; default: throw ExceptionUtilities.UnexpectedValue(matchResult); } } if (wasImplementingMemberFound && interfaceMemberKind == SymbolKind.Method) { // Don't report use site errors on properties - we'll report them on each of their accessors. // Don't report use site errors for implementations in other types unless // a synthesized implementation is needed that invokes the base method. // We can do so only if there are no use-site errors. if (synthesizedImplementation.ForwardingMethod is not null || TypeSymbol.Equals(implementingMember.ContainingType, this, TypeCompareKind.ConsiderEverything2)) { UseSiteInfo<AssemblySymbol> useSiteInfo = interfaceMember.GetUseSiteInfo(); // Don't report a use site error with a location in another compilation. For example, // if the error is that a base type in another assembly implemented an interface member // on our behalf and the use site error is that the current assembly does not reference // some required assembly, then we want to report the error in the current assembly - // not in the implementing assembly. Location location = implementingMember.IsFromCompilation(this.DeclaringCompilation) ? implementingMember.Locations[0] : this.Locations[0]; diagnostics.Add(useSiteInfo, location); } } } } } } return SynthesizedExplicitImplementations.Create(forwardingMethods.ToImmutableAndFree(), methodImpls.ToImmutableAndFree()); } protected abstract Location GetCorrespondingBaseListLocation(NamedTypeSymbol @base); #nullable enable private Location GetImplementsLocationOrFallback(NamedTypeSymbol implementedInterface) { return GetImplementsLocation(implementedInterface) ?? this.Locations[0]; } internal Location? GetImplementsLocation(NamedTypeSymbol implementedInterface) #nullable disable { // We ideally want to identify the interface location in the base list with an exact match but // will fall back and use the first derived interface if exact interface is not present. // this is the similar logic as the VB implementation. Debug.Assert(this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[implementedInterface].Contains(implementedInterface)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; NamedTypeSymbol directInterface = null; foreach (var iface in this.InterfacesNoUseSiteDiagnostics()) { if (TypeSymbol.Equals(iface, implementedInterface, TypeCompareKind.ConsiderEverything2)) { directInterface = iface; break; } else if ((object)directInterface == null && iface.ImplementsInterface(implementedInterface, ref discardedUseSiteInfo)) { directInterface = iface; } } Debug.Assert((object)directInterface != null); return GetCorrespondingBaseListLocation(directInterface); } /// <summary> /// It's not interesting to report diagnostics on implementation of interface accessors /// if the corresponding events or properties are not implemented (i.e. we want to suppress /// cascading diagnostics). /// Caveat: Indexed property accessors are always interesting. /// Caveat: It's also uninteresting if a WinRT event is implemented by a non-WinRT event, /// or vice versa. /// </summary> private bool ReportAccessorOfInterfacePropertyOrEvent(Symbol interfacePropertyOrEvent) { Debug.Assert((object)interfacePropertyOrEvent != null); // Accessors of indexed properties are always interesting. if (interfacePropertyOrEvent.IsIndexedProperty()) { return true; } Symbol implementingPropertyOrEvent; if (this.IsInterface) { MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = this.GetExplicitImplementationForInterfaceMember(interfacePropertyOrEvent); switch (explicitImpl.Count) { case 0: return true; case 1: implementingPropertyOrEvent = explicitImpl.Single(); break; default: implementingPropertyOrEvent = null; break; } } else { implementingPropertyOrEvent = this.FindImplementationForInterfaceMemberInNonInterface(interfacePropertyOrEvent); } // If the property or event wasn't implemented, then we'd prefer to report diagnostics about that. if ((object)implementingPropertyOrEvent == null) { return false; } // If the property or event was an event and was implemented, but the WinRT-ness didn't agree, // then we'd prefer to report diagnostics about that. if (interfacePropertyOrEvent.Kind == SymbolKind.Event && implementingPropertyOrEvent.Kind == SymbolKind.Event && ((EventSymbol)interfacePropertyOrEvent).IsWindowsRuntimeEvent != ((EventSymbol)implementingPropertyOrEvent).IsWindowsRuntimeEvent) { return false; } return true; } private enum HasBaseTypeDeclaringInterfaceResult { NoMatch, IgnoringNullableMatch, ExactMatch, } private HasBaseTypeDeclaringInterfaceResult HasBaseClassDeclaringInterface(NamedTypeSymbol @interface) { HasBaseTypeDeclaringInterfaceResult result = HasBaseTypeDeclaringInterfaceResult.NoMatch; for (NamedTypeSymbol currType = this.BaseTypeNoUseSiteDiagnostics; (object)currType != null; currType = currType.BaseTypeNoUseSiteDiagnostics) { if (DeclaresBaseInterface(currType, @interface, ref result)) { break; } } return result; } private static bool DeclaresBaseInterface(NamedTypeSymbol currType, NamedTypeSymbol @interface, ref HasBaseTypeDeclaringInterfaceResult result) { MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>.ValueSet set = currType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[@interface]; if (set.Count != 0) { if (set.Contains(@interface)) { result = HasBaseTypeDeclaringInterfaceResult.ExactMatch; return true; } else if (result == HasBaseTypeDeclaringInterfaceResult.NoMatch && set.Contains(@interface, Symbols.SymbolEqualityComparer.IgnoringNullable)) { result = HasBaseTypeDeclaringInterfaceResult.IgnoringNullableMatch; } } return false; } private void HasBaseInterfaceDeclaringInterface(NamedTypeSymbol baseInterface, NamedTypeSymbol @interface, ref HasBaseTypeDeclaringInterfaceResult matchResult) { // Let's check for the trivial case first if (DeclaresBaseInterface(baseInterface, @interface, ref matchResult)) { return; } foreach (var interfaceType in this.AllInterfacesNoUseSiteDiagnostics) { if ((object)interfaceType == baseInterface) { continue; } if (interfaceType.Equals(baseInterface, TypeCompareKind.CLRSignatureCompareOptions) && DeclaresBaseInterface(interfaceType, @interface, ref matchResult)) { return; } } } private void CheckMembersAgainstBaseType( BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) { switch (this.TypeKind) { // These checks don't make sense for enums and delegates: case TypeKind.Enum: case TypeKind.Delegate: return; case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Submission: // we have to check that "override" is not used break; default: throw ExceptionUtilities.UnexpectedValue(this.TypeKind); } foreach (var member in this.GetMembersUnordered()) { cancellationToken.ThrowIfCancellationRequested(); bool suppressAccessors; switch (member.Kind) { case SymbolKind.Method: var method = (MethodSymbol)member; if (MethodSymbol.CanOverrideOrHide(method.MethodKind) && !method.IsAccessor()) { if (member.IsOverride) { CheckOverrideMember(method, method.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } else { var sourceMethod = method as SourceMemberMethodSymbol; if ((object)sourceMethod != null) // skip submission initializer { var isNew = sourceMethod.IsNew; CheckNonOverrideMember(method, isNew, method.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } } } else if (method.MethodKind == MethodKind.Destructor) { // NOTE: Normal finalize methods CanOverrideOrHide and will go through the normal code path. // First is fine, since there should only be one, since there are no parameters. MethodSymbol overridden = method.GetFirstRuntimeOverriddenMethodIgnoringNewSlot(out _); // NOTE: Dev11 doesn't expose symbols, so it can treat destructors as override and let them go through the normal // checks. Roslyn can't, since the language says they are not virtual/override and that's what we need to expose // in the symbol model. Having said that, Dev11 doesn't seem to produce override errors other than this one // (see SymbolPreparer::prepareOperator). if ((object)overridden != null && overridden.IsMetadataFinal) { diagnostics.Add(ErrorCode.ERR_CantOverrideSealed, method.Locations[0], method, overridden); } } break; case SymbolKind.Property: var property = (PropertySymbol)member; var getMethod = property.GetMethod; var setMethod = property.SetMethod; // Handle the accessors here, instead of in the loop, so that we can ensure that // they're checked *after* the corresponding property. if (member.IsOverride) { CheckOverrideMember(property, property.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); if (!suppressAccessors) { if ((object)getMethod != null) { CheckOverrideMember(getMethod, getMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } if ((object)setMethod != null) { CheckOverrideMember(setMethod, setMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } } } else if (property is SourcePropertySymbolBase sourceProperty) { var isNewProperty = sourceProperty.IsNew; CheckNonOverrideMember(property, isNewProperty, property.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); if (!suppressAccessors) { if ((object)getMethod != null) { CheckNonOverrideMember(getMethod, isNewProperty, getMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } if ((object)setMethod != null) { CheckNonOverrideMember(setMethod, isNewProperty, setMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } } } break; case SymbolKind.Event: var @event = (EventSymbol)member; var addMethod = @event.AddMethod; var removeMethod = @event.RemoveMethod; // Handle the accessors here, instead of in the loop, so that we can ensure that // they're checked *after* the corresponding event. if (member.IsOverride) { CheckOverrideMember(@event, @event.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); if (!suppressAccessors) { if ((object)addMethod != null) { CheckOverrideMember(addMethod, addMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } if ((object)removeMethod != null) { CheckOverrideMember(removeMethod, removeMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } } } else { var isNewEvent = ((SourceEventSymbol)@event).IsNew; CheckNonOverrideMember(@event, isNewEvent, @event.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); if (!suppressAccessors) { if ((object)addMethod != null) { CheckNonOverrideMember(addMethod, isNewEvent, addMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } if ((object)removeMethod != null) { CheckNonOverrideMember(removeMethod, isNewEvent, removeMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } } } break; case SymbolKind.Field: var sourceField = member as SourceFieldSymbol; var isNewField = (object)sourceField != null && sourceField.IsNew; // We don't want to report diagnostics for field-like event backing fields (redundant), // but that shouldn't be an issue since they shouldn't be in the member list. Debug.Assert((object)sourceField == null || (object)sourceField.AssociatedSymbol == null || sourceField.AssociatedSymbol.Kind != SymbolKind.Event); CheckNewModifier(member, isNewField, diagnostics); break; case SymbolKind.NamedType: CheckNewModifier(member, ((SourceMemberContainerTypeSymbol)member).IsNew, diagnostics); break; } } } private void CheckNewModifier(Symbol symbol, bool isNew, BindingDiagnosticBag diagnostics) { Debug.Assert(symbol.Kind == SymbolKind.Field || symbol.Kind == SymbolKind.NamedType); // Do not give warnings about missing 'new' modifier for implicitly declared members, // e.g. backing fields for auto-properties if (symbol.IsImplicitlyDeclared) { return; } if (symbol.ContainingType.IsInterface) { CheckNonOverrideMember(symbol, isNew, OverriddenOrHiddenMembersHelpers.MakeInterfaceOverriddenOrHiddenMembers(symbol, memberIsFromSomeCompilation: true), diagnostics, out _); return; } // for error cases if ((object)this.BaseTypeNoUseSiteDiagnostics == null) { return; } int symbolArity = symbol.GetMemberArity(); Location symbolLocation = symbol.Locations.FirstOrDefault(); bool unused = false; NamedTypeSymbol currType = this.BaseTypeNoUseSiteDiagnostics; while ((object)currType != null) { foreach (var hiddenMember in currType.GetMembers(symbol.Name)) { if (hiddenMember.Kind == SymbolKind.Method && !((MethodSymbol)hiddenMember).CanBeHiddenByMemberKind(symbol.Kind)) { continue; } var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); bool isAccessible = AccessCheck.IsSymbolAccessible(hiddenMember, this, ref useSiteInfo); diagnostics.Add(symbolLocation, useSiteInfo); if (isAccessible && hiddenMember.GetMemberArity() == symbolArity) { if (!isNew) { diagnostics.Add(ErrorCode.WRN_NewRequired, symbolLocation, symbol, hiddenMember); } AddHidingAbstractDiagnostic(symbol, symbolLocation, hiddenMember, diagnostics, ref unused); return; } } currType = currType.BaseTypeNoUseSiteDiagnostics; } if (isNew) { diagnostics.Add(ErrorCode.WRN_NewNotRequired, symbolLocation, symbol); } } private void CheckOverrideMember( Symbol overridingMember, OverriddenOrHiddenMembersResult overriddenOrHiddenMembers, BindingDiagnosticBag diagnostics, out bool suppressAccessors) { Debug.Assert((object)overridingMember != null); Debug.Assert(overriddenOrHiddenMembers != null); suppressAccessors = false; var overridingMemberIsMethod = overridingMember.Kind == SymbolKind.Method; var overridingMemberIsProperty = overridingMember.Kind == SymbolKind.Property; var overridingMemberIsEvent = overridingMember.Kind == SymbolKind.Event; Debug.Assert(overridingMemberIsMethod ^ overridingMemberIsProperty ^ overridingMemberIsEvent); var overridingMemberLocation = overridingMember.Locations[0]; var overriddenMembers = overriddenOrHiddenMembers.OverriddenMembers; Debug.Assert(!overriddenMembers.IsDefault); if (overriddenMembers.Length == 0) { var hiddenMembers = overriddenOrHiddenMembers.HiddenMembers; Debug.Assert(!hiddenMembers.IsDefault); if (hiddenMembers.Any()) { ErrorCode errorCode = overridingMemberIsMethod ? ErrorCode.ERR_CantOverrideNonFunction : overridingMemberIsProperty ? ErrorCode.ERR_CantOverrideNonProperty : ErrorCode.ERR_CantOverrideNonEvent; diagnostics.Add(errorCode, overridingMemberLocation, overridingMember, hiddenMembers[0]); } else { Symbol associatedPropertyOrEvent = null; if (overridingMemberIsMethod) { associatedPropertyOrEvent = ((MethodSymbol)overridingMember).AssociatedSymbol; } if ((object)associatedPropertyOrEvent == null) { bool suppressError = false; if (overridingMemberIsMethod || overridingMember.IsIndexer()) { var parameterTypes = overridingMemberIsMethod ? ((MethodSymbol)overridingMember).ParameterTypesWithAnnotations : ((PropertySymbol)overridingMember).ParameterTypesWithAnnotations; foreach (var parameterType in parameterTypes) { if (IsOrContainsErrorType(parameterType.Type)) { suppressError = true; // The parameter type must be fixed before the override can be found, so suppress error break; } } } if (!suppressError) { diagnostics.Add(ErrorCode.ERR_OverrideNotExpected, overridingMemberLocation, overridingMember); } } else if (associatedPropertyOrEvent.Kind == SymbolKind.Property) //no specific errors for event accessors { PropertySymbol associatedProperty = (PropertySymbol)associatedPropertyOrEvent; PropertySymbol overriddenProperty = associatedProperty.OverriddenProperty; if ((object)overriddenProperty == null) { //skip remaining checks } else if (associatedProperty.GetMethod == overridingMember && (object)overriddenProperty.GetMethod == null) { diagnostics.Add(ErrorCode.ERR_NoGetToOverride, overridingMemberLocation, overridingMember, overriddenProperty); } else if (associatedProperty.SetMethod == overridingMember && (object)overriddenProperty.SetMethod == null) { diagnostics.Add(ErrorCode.ERR_NoSetToOverride, overridingMemberLocation, overridingMember, overriddenProperty); } else { diagnostics.Add(ErrorCode.ERR_OverrideNotExpected, overridingMemberLocation, overridingMember); } } } } else { NamedTypeSymbol overridingType = overridingMember.ContainingType; if (overriddenMembers.Length > 1) { diagnostics.Add(ErrorCode.ERR_AmbigOverride, overridingMemberLocation, overriddenMembers[0].OriginalDefinition, overriddenMembers[1].OriginalDefinition, overridingType); suppressAccessors = true; } else { checkSingleOverriddenMember(overridingMember, overriddenMembers[0], diagnostics, ref suppressAccessors); } } // Both `ref` and `out` parameters (and `in` too) are implemented as references and are not distinguished by the runtime // when resolving overrides. Similarly, distinctions between types that would map together because of generic substitution // in the derived type where the override appears are the same from the runtime's point of view. In these cases we will // need to produce a methodimpl to disambiguate. See the call to `RequiresExplicitOverride` below. It produces a boolean // `warnAmbiguous` if the methodimpl could be misinterpreted due to a bug in the runtime // (https://github.com/dotnet/runtime/issues/38119) in which case we produce a warning regarding that ambiguity. // See https://github.com/dotnet/roslyn/issues/45453 for details. if (!this.ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses && overridingMember is MethodSymbol overridingMethod) { overridingMethod.RequiresExplicitOverride(out bool warnAmbiguous); if (warnAmbiguous) { var ambiguousMethod = overridingMethod.OverriddenMethod; diagnostics.Add(ErrorCode.WRN_MultipleRuntimeOverrideMatches, ambiguousMethod.Locations[0], ambiguousMethod, overridingMember); suppressAccessors = true; } } return; void checkSingleOverriddenMember(Symbol overridingMember, Symbol overriddenMember, BindingDiagnosticBag diagnostics, ref bool suppressAccessors) { var overridingMemberLocation = overridingMember.Locations[0]; var overridingMemberIsMethod = overridingMember.Kind == SymbolKind.Method; var overridingMemberIsProperty = overridingMember.Kind == SymbolKind.Property; var overridingMemberIsEvent = overridingMember.Kind == SymbolKind.Event; var overridingType = overridingMember.ContainingType; //otherwise, it would have been excluded during lookup #if DEBUG { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; Debug.Assert(AccessCheck.IsSymbolAccessible(overriddenMember, overridingType, ref discardedUseSiteInfo)); } #endif Debug.Assert(overriddenMember.Kind == overridingMember.Kind); if (overriddenMember.MustCallMethodsDirectly()) { diagnostics.Add(ErrorCode.ERR_CantOverrideBogusMethod, overridingMemberLocation, overridingMember, overriddenMember); suppressAccessors = true; } else if (!overriddenMember.IsVirtual && !overriddenMember.IsAbstract && !overriddenMember.IsOverride && !(overridingMemberIsMethod && ((MethodSymbol)overriddenMember).MethodKind == MethodKind.Destructor)) //destructors are metadata virtual { // CONSIDER: To match Dev10, skip the error for properties, and don't suppressAccessors diagnostics.Add(ErrorCode.ERR_CantOverrideNonVirtual, overridingMemberLocation, overridingMember, overriddenMember); suppressAccessors = true; } else if (overriddenMember.IsSealed) { // CONSIDER: To match Dev10, skip the error for properties, and don't suppressAccessors diagnostics.Add(ErrorCode.ERR_CantOverrideSealed, overridingMemberLocation, overridingMember, overriddenMember); suppressAccessors = true; } else if (!OverrideHasCorrectAccessibility(overriddenMember, overridingMember)) { var accessibility = SyntaxFacts.GetText(overriddenMember.DeclaredAccessibility); diagnostics.Add(ErrorCode.ERR_CantChangeAccessOnOverride, overridingMemberLocation, overridingMember, accessibility, overriddenMember); suppressAccessors = true; } else if (overridingMember.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(overridingMember, overriddenMember)) { // it is ok to override with no tuple names, for compatibility with C# 6, but otherwise names should match diagnostics.Add(ErrorCode.ERR_CantChangeTupleNamesOnOverride, overridingMemberLocation, overridingMember, overriddenMember); } else { // As in dev11, we don't compare obsoleteness to the immediately-overridden member, // but to the least-overridden member. var leastOverriddenMember = overriddenMember.GetLeastOverriddenMember(overriddenMember.ContainingType); overridingMember.ForceCompleteObsoleteAttribute(); leastOverriddenMember.ForceCompleteObsoleteAttribute(); Debug.Assert(overridingMember.ObsoleteState != ThreeState.Unknown); Debug.Assert(leastOverriddenMember.ObsoleteState != ThreeState.Unknown); bool overridingMemberIsObsolete = overridingMember.ObsoleteState == ThreeState.True; bool leastOverriddenMemberIsObsolete = leastOverriddenMember.ObsoleteState == ThreeState.True; if (overridingMemberIsObsolete != leastOverriddenMemberIsObsolete) { ErrorCode code = overridingMemberIsObsolete ? ErrorCode.WRN_ObsoleteOverridingNonObsolete : ErrorCode.WRN_NonObsoleteOverridingObsolete; diagnostics.Add(code, overridingMemberLocation, overridingMember, leastOverriddenMember); } if (overridingMemberIsProperty) { checkOverriddenProperty((PropertySymbol)overridingMember, (PropertySymbol)overriddenMember, diagnostics, ref suppressAccessors); } else if (overridingMemberIsEvent) { EventSymbol overridingEvent = (EventSymbol)overridingMember; EventSymbol overriddenEvent = (EventSymbol)overriddenMember; TypeWithAnnotations overridingMemberType = overridingEvent.TypeWithAnnotations; TypeWithAnnotations overriddenMemberType = overriddenEvent.TypeWithAnnotations; // Ignore custom modifiers because this diagnostic is based on the C# semantics. if (!overridingMemberType.Equals(overriddenMemberType, TypeCompareKind.AllIgnoreOptions)) { // if the type is or contains an error type, the type must be fixed before the override can be found, so suppress error if (!IsOrContainsErrorType(overridingMemberType.Type)) { diagnostics.Add(ErrorCode.ERR_CantChangeTypeOnOverride, overridingMemberLocation, overridingMember, overriddenMember, overriddenMemberType.Type); } suppressAccessors = true; //we get really unhelpful errors from the accessor if the type is mismatched } else { CheckValidNullableEventOverride(overridingEvent.DeclaringCompilation, overriddenEvent, overridingEvent, diagnostics, (diagnostics, overriddenEvent, overridingEvent, location) => diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, location), overridingMemberLocation); } } else { Debug.Assert(overridingMemberIsMethod); var overridingMethod = (MethodSymbol)overridingMember; var overriddenMethod = (MethodSymbol)overriddenMember; if (overridingMethod.IsGenericMethod) { overriddenMethod = overriddenMethod.Construct(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(overridingMethod.TypeParameters)); } // Check for mismatched byref returns and return type. Ignore custom modifiers, because this diagnostic is based on the C# semantics. if (overridingMethod.RefKind != overriddenMethod.RefKind) { diagnostics.Add(ErrorCode.ERR_CantChangeRefReturnOnOverride, overridingMemberLocation, overridingMember, overriddenMember); } else if (!IsValidOverrideReturnType(overridingMethod, overridingMethod.ReturnTypeWithAnnotations, overriddenMethod.ReturnTypeWithAnnotations, diagnostics)) { // if the Return type is or contains an error type, the return type must be fixed before the override can be found, so suppress error if (!IsOrContainsErrorType(overridingMethod.ReturnType)) { // If the return type would be a valid covariant return, suggest using covariant return feature. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if (DeclaringCompilation.Conversions.HasIdentityOrImplicitReferenceConversion(overridingMethod.ReturnTypeWithAnnotations.Type, overriddenMethod.ReturnTypeWithAnnotations.Type, ref discardedUseSiteInfo)) { if (!overridingMethod.ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses, overridingMemberLocation, overridingMember, overriddenMember, overriddenMethod.ReturnType); } else if (MessageID.IDS_FeatureCovariantReturnsForOverrides.GetFeatureAvailabilityDiagnosticInfo(this.DeclaringCompilation) is { } diagnosticInfo) { diagnostics.Add(diagnosticInfo, overridingMemberLocation); } else { throw ExceptionUtilities.Unreachable; } } else { // error CS0508: return type must be 'C<V>' to match overridden member 'M<T>()' diagnostics.Add(ErrorCode.ERR_CantChangeReturnTypeOnOverride, overridingMemberLocation, overridingMember, overriddenMember, overriddenMethod.ReturnType); } } } else if (overriddenMethod.IsRuntimeFinalizer()) { diagnostics.Add(ErrorCode.ERR_OverrideFinalizeDeprecated, overridingMemberLocation); } else if (!overridingMethod.IsAccessor()) { // Accessors will have already been checked above checkValidNullableMethodOverride( overridingMemberLocation, overriddenMethod, overridingMethod, diagnostics, checkReturnType: true, checkParameters: true); } } // NOTE: this error may be redundant (if an error has already been reported // for the return type or parameter type in question), but the scenario is // too rare to justify complicated checks. if (Binder.ReportUseSite(overriddenMember, diagnostics, overridingMember.Locations[0])) { suppressAccessors = true; } } void checkOverriddenProperty(PropertySymbol overridingProperty, PropertySymbol overriddenProperty, BindingDiagnosticBag diagnostics, ref bool suppressAccessors) { var overridingMemberLocation = overridingProperty.Locations[0]; var overridingType = overridingProperty.ContainingType; TypeWithAnnotations overridingMemberType = overridingProperty.TypeWithAnnotations; TypeWithAnnotations overriddenMemberType = overriddenProperty.TypeWithAnnotations; // Check for mismatched byref returns and return type. Ignore custom modifiers, because this diagnostic is based on the C# semantics. if (overridingProperty.RefKind != overriddenProperty.RefKind) { diagnostics.Add(ErrorCode.ERR_CantChangeRefReturnOnOverride, overridingMemberLocation, overridingProperty, overriddenProperty); suppressAccessors = true; //we get really unhelpful errors from the accessor if the ref kind is mismatched } else if (overridingProperty.SetMethod is null ? !IsValidOverrideReturnType(overridingProperty, overridingMemberType, overriddenMemberType, diagnostics) : !overridingMemberType.Equals(overriddenMemberType, TypeCompareKind.AllIgnoreOptions)) { // if the type is or contains an error type, the type must be fixed before the override can be found, so suppress error if (!IsOrContainsErrorType(overridingMemberType.Type)) { // If the type would be a valid covariant return, suggest using covariant return feature. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if (overridingProperty.SetMethod is null && DeclaringCompilation.Conversions.HasIdentityOrImplicitReferenceConversion(overridingMemberType.Type, overriddenMemberType.Type, ref discardedUseSiteInfo)) { if (!overridingProperty.ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportCovariantPropertiesOfClasses, overridingMemberLocation, overridingMember, overriddenMember, overriddenMemberType.Type); } else { var diagnosticInfo = MessageID.IDS_FeatureCovariantReturnsForOverrides.GetFeatureAvailabilityDiagnosticInfo(this.DeclaringCompilation); Debug.Assert(diagnosticInfo is { }); diagnostics.Add(diagnosticInfo, overridingMemberLocation); } } else { // error CS1715: 'Derived.M': type must be 'object' to match overridden member 'Base.M' diagnostics.Add(ErrorCode.ERR_CantChangeTypeOnOverride, overridingMemberLocation, overridingMember, overriddenMember, overriddenMemberType.Type); // https://github.com/dotnet/roslyn/issues/44207 when overriddenMemberType.Type is an inheritable reference type and the covariant return // feature is enabled, and the platform supports it, and there is no setter, we can say it has to be 'object' **or a derived type**. // That would probably be a new error code. } } suppressAccessors = true; //we get really unhelpful errors from the accessor if the type is mismatched } else { if (overridingProperty.GetMethod is object) { MethodSymbol overriddenGetMethod = overriddenProperty.GetOwnOrInheritedGetMethod(); checkValidNullableMethodOverride( overridingProperty.GetMethod.Locations[0], overriddenGetMethod, overridingProperty.GetMethod, diagnostics, checkReturnType: true, // Don't check parameters on the getter if there is a setter // because they will be a subset of the setter checkParameters: overridingProperty.SetMethod is null || overriddenGetMethod?.AssociatedSymbol != overriddenProperty || overriddenProperty.GetOwnOrInheritedSetMethod()?.AssociatedSymbol != overriddenProperty); } if (overridingProperty.SetMethod is object) { var ownOrInheritedOverriddenSetMethod = overriddenProperty.GetOwnOrInheritedSetMethod(); checkValidNullableMethodOverride( overridingProperty.SetMethod.Locations[0], ownOrInheritedOverriddenSetMethod, overridingProperty.SetMethod, diagnostics, checkReturnType: false, checkParameters: true); if (ownOrInheritedOverriddenSetMethod is object && overridingProperty.SetMethod.IsInitOnly != ownOrInheritedOverriddenSetMethod.IsInitOnly) { diagnostics.Add(ErrorCode.ERR_CantChangeInitOnlyOnOverride, overridingMemberLocation, overridingProperty, overriddenProperty); } } } // If the overriding property is sealed, then the overridden accessors cannot be inaccessible, since we // have to override them to make them sealed in metadata. // CONSIDER: It might be nice if this had its own error code(s) since it's an implementation restriction, // rather than a language restriction as above. if (overridingProperty.IsSealed) { MethodSymbol ownOrInheritedGetMethod = overridingProperty.GetOwnOrInheritedGetMethod(); var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, overridingProperty.ContainingAssembly); if (overridingProperty.GetMethod != ownOrInheritedGetMethod && !AccessCheck.IsSymbolAccessible(ownOrInheritedGetMethod, overridingType, ref useSiteInfo)) { diagnostics.Add(ErrorCode.ERR_NoGetToOverride, overridingMemberLocation, overridingProperty, overriddenProperty); } MethodSymbol ownOrInheritedSetMethod = overridingProperty.GetOwnOrInheritedSetMethod(); if (overridingProperty.SetMethod != ownOrInheritedSetMethod && !AccessCheck.IsSymbolAccessible(ownOrInheritedSetMethod, overridingType, ref useSiteInfo)) { diagnostics.Add(ErrorCode.ERR_NoSetToOverride, overridingMemberLocation, overridingProperty, overriddenProperty); } diagnostics.Add(overridingMemberLocation, useSiteInfo); } } } static void checkValidNullableMethodOverride( Location overridingMemberLocation, MethodSymbol overriddenMethod, MethodSymbol overridingMethod, BindingDiagnosticBag diagnostics, bool checkReturnType, bool checkParameters) { CheckValidNullableMethodOverride(overridingMethod.DeclaringCompilation, overriddenMethod, overridingMethod, diagnostics, checkReturnType ? ReportBadReturn : null, checkParameters ? ReportBadParameter : null, overridingMemberLocation); } } internal static bool IsOrContainsErrorType(TypeSymbol typeSymbol) { return (object)typeSymbol.VisitType((currentTypeSymbol, unused1, unused2) => currentTypeSymbol.IsErrorType(), (object)null) != null; } /// <summary> /// Return true if <paramref name="overridingReturnType"/> is valid for the return type of an override method when the overridden method's return type is <paramref name="overriddenReturnType"/>. /// </summary> private bool IsValidOverrideReturnType(Symbol overridingSymbol, TypeWithAnnotations overridingReturnType, TypeWithAnnotations overriddenReturnType, BindingDiagnosticBag diagnostics) { if (overridingSymbol.ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses && DeclaringCompilation.LanguageVersion >= MessageID.IDS_FeatureCovariantReturnsForOverrides.RequiredVersion()) { var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); var result = DeclaringCompilation.Conversions.HasIdentityOrImplicitReferenceConversion(overridingReturnType.Type, overriddenReturnType.Type, ref useSiteInfo); Location symbolLocation = overridingSymbol.Locations.FirstOrDefault(); diagnostics.Add(symbolLocation, useSiteInfo); return result; } else { return overridingReturnType.Equals(overriddenReturnType, TypeCompareKind.AllIgnoreOptions); } } static readonly ReportMismatchInReturnType<Location> ReportBadReturn = (BindingDiagnosticBag diagnostics, MethodSymbol overriddenMethod, MethodSymbol overridingMethod, bool topLevel, Location location) => diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, location); static readonly ReportMismatchInParameterType<Location> ReportBadParameter = (BindingDiagnosticBag diagnostics, MethodSymbol overriddenMethod, MethodSymbol overridingMethod, ParameterSymbol overridingParameter, bool topLevel, Location location) => diagnostics.Add( topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, location, new FormattedSymbol(overridingParameter, SymbolDisplayFormat.ShortFormat)); /// <returns> /// <see langword="true"/> if a diagnostic was added. Otherwise, <see langword="false"/>. /// </returns> internal static bool CheckValidNullableMethodOverride<TArg>( CSharpCompilation compilation, MethodSymbol baseMethod, MethodSymbol overrideMethod, BindingDiagnosticBag diagnostics, ReportMismatchInReturnType<TArg> reportMismatchInReturnType, ReportMismatchInParameterType<TArg> reportMismatchInParameterType, TArg extraArgument, bool invokedAsExtensionMethod = false) { if (!PerformValidNullableOverrideCheck(compilation, baseMethod, overrideMethod)) { return false; } bool hasErrors = false; if ((baseMethod.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn && (overrideMethod.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) != FlowAnalysisAnnotations.DoesNotReturn) { diagnostics.Add(ErrorCode.WRN_DoesNotReturnMismatch, overrideMethod.Locations[0], new FormattedSymbol(overrideMethod, SymbolDisplayFormat.MinimallyQualifiedFormat)); hasErrors = true; } var conversions = compilation.Conversions.WithNullability(true); var baseParameters = baseMethod.Parameters; var overrideParameters = overrideMethod.Parameters; var overrideParameterOffset = invokedAsExtensionMethod ? 1 : 0; Debug.Assert(baseMethod.ParameterCount == overrideMethod.ParameterCount - overrideParameterOffset); if (reportMismatchInReturnType != null) { var overrideReturnType = getNotNullIfNotNullOutputType(overrideMethod.ReturnTypeWithAnnotations, overrideMethod.ReturnNotNullIfParameterNotNull); // check nested nullability if (!isValidNullableConversion( conversions, overrideMethod.RefKind, overrideReturnType.Type, baseMethod.ReturnTypeWithAnnotations.Type)) { reportMismatchInReturnType(diagnostics, baseMethod, overrideMethod, false, extraArgument); return true; } // check top-level nullability including flow analysis annotations if (!NullableWalker.AreParameterAnnotationsCompatible( overrideMethod.RefKind == RefKind.Ref ? RefKind.Ref : RefKind.Out, baseMethod.ReturnTypeWithAnnotations, baseMethod.ReturnTypeFlowAnalysisAnnotations, overrideReturnType, overrideMethod.ReturnTypeFlowAnalysisAnnotations)) { reportMismatchInReturnType(diagnostics, baseMethod, overrideMethod, true, extraArgument); return true; } } if (reportMismatchInParameterType != null) { for (int i = 0; i < baseParameters.Length; i++) { var baseParameter = baseParameters[i]; var baseParameterType = baseParameter.TypeWithAnnotations; var overrideParameter = overrideParameters[i + overrideParameterOffset]; var overrideParameterType = getNotNullIfNotNullOutputType(overrideParameter.TypeWithAnnotations, overrideParameter.NotNullIfParameterNotNull); // check nested nullability if (!isValidNullableConversion( conversions, overrideParameter.RefKind, baseParameterType.Type, overrideParameterType.Type)) { reportMismatchInParameterType(diagnostics, baseMethod, overrideMethod, overrideParameter, false, extraArgument); hasErrors = true; } // check top-level nullability including flow analysis annotations else if (!NullableWalker.AreParameterAnnotationsCompatible( overrideParameter.RefKind, baseParameterType, baseParameter.FlowAnalysisAnnotations, overrideParameterType, overrideParameter.FlowAnalysisAnnotations)) { reportMismatchInParameterType(diagnostics, baseMethod, overrideMethod, overrideParameter, true, extraArgument); hasErrors = true; } } } return hasErrors; TypeWithAnnotations getNotNullIfNotNullOutputType(TypeWithAnnotations outputType, ImmutableHashSet<string> notNullIfParameterNotNull) { if (!notNullIfParameterNotNull.IsEmpty) { for (var i = 0; i < baseParameters.Length; i++) { var overrideParam = overrideParameters[i + overrideParameterOffset]; var baseParam = baseParameters[i]; if (notNullIfParameterNotNull.Contains(overrideParam.Name) && NullableWalker.GetParameterState(baseParam.TypeWithAnnotations, baseParam.FlowAnalysisAnnotations).IsNotNull) { return outputType.AsNotAnnotated(); } } } return outputType; } static bool isValidNullableConversion( ConversionsBase conversions, RefKind refKind, TypeSymbol sourceType, TypeSymbol targetType) { switch (refKind) { case RefKind.Ref: // ref variables are invariant return sourceType.Equals( targetType, TypeCompareKind.AllIgnoreOptions & ~(TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); case RefKind.Out: // out variables have inverted variance (sourceType, targetType) = (targetType, sourceType); break; default: break; } Debug.Assert(conversions.IncludeNullability); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return conversions.ClassifyImplicitConversionFromType(sourceType, targetType, ref discardedUseSiteInfo).Kind != ConversionKind.NoConversion; } } private static bool PerformValidNullableOverrideCheck( CSharpCompilation compilation, Symbol overriddenMember, Symbol overridingMember) { // Don't do any validation if the nullable feature is not enabled or // the override is not written directly in source return overriddenMember is object && overridingMember is object && compilation is object && compilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes); } internal static void CheckValidNullableEventOverride<TArg>( CSharpCompilation compilation, EventSymbol overriddenEvent, EventSymbol overridingEvent, BindingDiagnosticBag diagnostics, Action<BindingDiagnosticBag, EventSymbol, EventSymbol, TArg> reportMismatch, TArg extraArgument) { if (!PerformValidNullableOverrideCheck(compilation, overriddenEvent, overridingEvent)) { return; } var conversions = compilation.Conversions.WithNullability(true); if (!conversions.HasAnyNullabilityImplicitConversion(overriddenEvent.TypeWithAnnotations, overridingEvent.TypeWithAnnotations)) { reportMismatch(diagnostics, overriddenEvent, overridingEvent, extraArgument); } } private static void CheckNonOverrideMember( Symbol hidingMember, bool hidingMemberIsNew, OverriddenOrHiddenMembersResult overriddenOrHiddenMembers, BindingDiagnosticBag diagnostics, out bool suppressAccessors) { suppressAccessors = false; var hidingMemberLocation = hidingMember.Locations[0]; Debug.Assert(overriddenOrHiddenMembers != null); Debug.Assert(!overriddenOrHiddenMembers.OverriddenMembers.Any()); //since hidingMethod.IsOverride is false var hiddenMembers = overriddenOrHiddenMembers.HiddenMembers; Debug.Assert(!hiddenMembers.IsDefault); if (hiddenMembers.Length == 0) { if (hidingMemberIsNew && !hidingMember.IsAccessor()) { diagnostics.Add(ErrorCode.WRN_NewNotRequired, hidingMemberLocation, hidingMember); } } else { var diagnosticAdded = false; //for interfaces, we always report WRN_NewRequired //if we went into the loop, the pseudo-abstract nature of interfaces would throw off the other checks if (!hidingMember.ContainingType.IsInterface) { foreach (var hiddenMember in hiddenMembers) { diagnosticAdded |= AddHidingAbstractDiagnostic(hidingMember, hidingMemberLocation, hiddenMember, diagnostics, ref suppressAccessors); //can actually get both, so don't use else if if (!hidingMemberIsNew && hiddenMember.Kind == hidingMember.Kind && !hidingMember.IsAccessor() && (hiddenMember.IsAbstract || hiddenMember.IsVirtual || hiddenMember.IsOverride) && !IsShadowingSynthesizedRecordMember(hidingMember)) { diagnostics.Add(ErrorCode.WRN_NewOrOverrideExpected, hidingMemberLocation, hidingMember, hiddenMember); diagnosticAdded = true; } if (diagnosticAdded) { break; } } } if (!hidingMemberIsNew && !IsShadowingSynthesizedRecordMember(hidingMember) && !diagnosticAdded && !hidingMember.IsAccessor() && !hidingMember.IsOperator()) { diagnostics.Add(ErrorCode.WRN_NewRequired, hidingMemberLocation, hidingMember, hiddenMembers[0]); } } } private static bool IsShadowingSynthesizedRecordMember(Symbol hidingMember) { return hidingMember is SynthesizedRecordEquals || hidingMember is SynthesizedRecordDeconstruct || hidingMember is SynthesizedRecordClone; } /// <summary> /// If necessary, report a diagnostic for a hidden abstract member. /// </summary> /// <returns>True if a diagnostic was reported.</returns> private static bool AddHidingAbstractDiagnostic(Symbol hidingMember, Location hidingMemberLocation, Symbol hiddenMember, BindingDiagnosticBag diagnostics, ref bool suppressAccessors) { switch (hiddenMember.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: break; // Can result in diagnostic default: return false; // Cannot result in diagnostic } // If the hidden member isn't abstract, the diagnostic doesn't apply. // If the hiding member is in a non-abstract type, then suppress this cascading error. if (!hiddenMember.IsAbstract || !hidingMember.ContainingType.IsAbstract) { return false; } switch (hidingMember.DeclaredAccessibility) { case Accessibility.Internal: case Accessibility.Private: case Accessibility.ProtectedAndInternal: break; case Accessibility.Public: case Accessibility.ProtectedOrInternal: case Accessibility.Protected: { // At this point we know we're going to report ERR_HidingAbstractMethod, we just have to // figure out the substitutions. switch (hidingMember.Kind) { case SymbolKind.Method: var associatedPropertyOrEvent = ((MethodSymbol)hidingMember).AssociatedSymbol; if ((object)associatedPropertyOrEvent != null) { //Dev10 reports that the property/event is doing the hiding, rather than the method diagnostics.Add(ErrorCode.ERR_HidingAbstractMethod, associatedPropertyOrEvent.Locations[0], associatedPropertyOrEvent, hiddenMember); break; } goto default; case SymbolKind.Property: case SymbolKind.Event: // NOTE: We used to let the accessors take care of this case, but then we weren't handling the case // where a hiding and hidden properties did not have any accessors in common. // CONSIDER: Dev10 actually reports an error for each accessor of a hidden property/event, but that seems unnecessary. suppressAccessors = true; goto default; default: diagnostics.Add(ErrorCode.ERR_HidingAbstractMethod, hidingMemberLocation, hidingMember, hiddenMember); break; } return true; } default: throw ExceptionUtilities.UnexpectedValue(hidingMember.DeclaredAccessibility); } return false; } private static bool OverrideHasCorrectAccessibility(Symbol overridden, Symbol overriding) { // Check declared accessibility rather than effective accessibility since there's a different // check (CS0560) that determines whether the containing types have compatible accessibility. if (!overriding.ContainingAssembly.HasInternalAccessTo(overridden.ContainingAssembly) && overridden.DeclaredAccessibility == Accessibility.ProtectedOrInternal) { return overriding.DeclaredAccessibility == Accessibility.Protected; } else { return overridden.DeclaredAccessibility == overriding.DeclaredAccessibility; } } #nullable enable /// <summary> /// It is invalid for a type to directly (vs through a base class) implement two interfaces that /// unify (i.e. are the same for some substitution of type parameters). /// </summary> /// <remarks> /// CONSIDER: check this while building up InterfacesAndTheirBaseInterfaces (only in the SourceNamedTypeSymbol case). /// </remarks> private void CheckInterfaceUnification(BindingDiagnosticBag diagnostics) { if (!this.IsGenericType) { return; } // CONSIDER: filtering the list to only include generic types would save iterations. int numInterfaces = this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.Count; if (numInterfaces < 2) { return; } // NOTE: a typical approach to finding duplicates in less than quadratic time // is to use a HashSet with an appropriate comparer. Unfortunately, this approach // does not apply (at least, not straightforwardly), because CanUnifyWith is not // transitive and, thus, is not an equivalence relation. NamedTypeSymbol[] interfaces = this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.Keys.ToArray(); for (int i1 = 0; i1 < numInterfaces; i1++) { for (int i2 = i1 + 1; i2 < numInterfaces; i2++) { NamedTypeSymbol interface1 = interfaces[i1]; NamedTypeSymbol interface2 = interfaces[i2]; // CanUnifyWith is the real check - the others just short-circuit if (interface1.IsGenericType && interface2.IsGenericType && TypeSymbol.Equals(interface1.OriginalDefinition, interface2.OriginalDefinition, TypeCompareKind.ConsiderEverything2) && interface1.CanUnifyWith(interface2)) { if (GetImplementsLocationOrFallback(interface1).SourceSpan.Start > GetImplementsLocationOrFallback(interface2).SourceSpan.Start) { // Mention interfaces in order of their appearance in the base list, for consistency. var temp = interface1; interface1 = interface2; interface2 = temp; } diagnostics.Add(ErrorCode.ERR_UnifyingInterfaceInstantiations, this.Locations[0], this, interface1, interface2); } } } } /// <summary> /// Though there is a method that C# considers to be an implementation of the interface method, that /// method may not be considered an implementation by the CLR. In particular, implicit implementation /// methods that are non-virtual or that have different (usually fewer) custom modifiers than the /// interface method, will not be considered CLR overrides. To address this problem, we either make /// them virtual (in metadata, not in C#), or we introduce an explicit interface implementation that /// delegates to the implicit implementation. /// </summary> /// <param name="implementingMemberAndDiagnostics">Returned from FindImplementationForInterfaceMemberWithDiagnostics.</param> /// <param name="interfaceMember">The interface method or property that is being implemented.</param> /// <returns> /// A synthesized forwarding method for the implementation, or information about MethodImpl entry that should be emitted, /// or default if neither needed. /// </returns> private (SynthesizedExplicitImplementationForwardingMethod? ForwardingMethod, (MethodSymbol Body, MethodSymbol Implemented)? MethodImpl) SynthesizeInterfaceMemberImplementation(SymbolAndDiagnostics implementingMemberAndDiagnostics, Symbol interfaceMember) { foreach (Diagnostic diagnostic in implementingMemberAndDiagnostics.Diagnostics.Diagnostics) { if (diagnostic.Severity == DiagnosticSeverity.Error && diagnostic.Code is not (int)ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember) { return default; } } Symbol implementingMember = implementingMemberAndDiagnostics.Symbol; //don't worry about properties or events - we'll catch them through their accessors if ((object)implementingMember == null || implementingMember.Kind != SymbolKind.Method) { return default; } MethodSymbol interfaceMethod = (MethodSymbol)interfaceMember; MethodSymbol implementingMethod = (MethodSymbol)implementingMember; //explicit implementations are always respected by the CLR if (implementingMethod.ExplicitInterfaceImplementations.Contains(interfaceMethod, ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance)) { return default; } if (!interfaceMethod.IsStatic) { MethodSymbol implementingMethodOriginalDefinition = implementingMethod.OriginalDefinition; bool needSynthesizedImplementation = true; // If the implementing method is from a source file in the same module and the // override is correct from the runtime's perspective (esp the custom modifiers // match), then we can just twiddle the metadata virtual bit. Otherwise, we need // to create an explicit implementation that delegates to the real implementation. if (MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(implementingMethod, interfaceMethod) && IsOverrideOfPossibleImplementationUnderRuntimeRules(implementingMethod, @interfaceMethod.ContainingType)) { if (ReferenceEquals(this.ContainingModule, implementingMethodOriginalDefinition.ContainingModule)) { if (implementingMethodOriginalDefinition is SourceMemberMethodSymbol sourceImplementMethodOriginalDefinition) { sourceImplementMethodOriginalDefinition.EnsureMetadataVirtual(); needSynthesizedImplementation = false; } } else if (implementingMethod.IsMetadataVirtual(ignoreInterfaceImplementationChanges: true)) { // If the signatures match and the implementation method is definitely virtual, then we're set. needSynthesizedImplementation = false; } } if (!needSynthesizedImplementation) { return default; } } else { if (implementingMethod.ContainingType != (object)this) { if (implementingMethod.Equals(this.BaseTypeNoUseSiteDiagnostics?.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMethod).Symbol, TypeCompareKind.CLRSignatureCompareOptions)) { return default; } } else if (MemberSignatureComparer.RuntimeExplicitImplementationSignatureComparer.Equals(implementingMethod, interfaceMethod)) { return (null, (implementingMethod, interfaceMethod)); } } return (new SynthesizedExplicitImplementationForwardingMethod(interfaceMethod, implementingMethod, this), null); } #nullable disable /// <summary> /// The CLR will only look for an implementation of an interface method in a type that /// 1) declares that it implements that interface; or /// 2) is a base class of a type that declares that it implements the interface but not /// a subtype of a class that declares that it implements the interface. /// /// For example, /// /// interface I /// class A /// class B : A, I /// class C : B /// class D : C, I /// /// Suppose the runtime is looking for D's implementation of a member of I. It will look in /// D because of (1), will not look in C, will look in B because of (1), and will look in A /// because of (2). /// /// The key point is that it does not look in C, which C# *does*. /// </summary> private static bool IsPossibleImplementationUnderRuntimeRules(MethodSymbol implementingMethod, NamedTypeSymbol @interface) { NamedTypeSymbol type = implementingMethod.ContainingType; if (type.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.ContainsKey(@interface)) { return true; } NamedTypeSymbol baseType = type.BaseTypeNoUseSiteDiagnostics; return (object)baseType == null || !baseType.AllInterfacesNoUseSiteDiagnostics.Contains(@interface); } /// <summary> /// If C# picks a different implementation than the CLR (see IsPossibleImplementationUnderClrRules), then we might /// still be okay, but dynamic dispatch might result in C#'s choice getting called anyway. /// </summary> /// <remarks> /// This is based on SymbolPreparer::IsCLRMethodImplSame in the native compiler. /// /// ACASEY: What the native compiler actually does is compute the C# answer, compute the CLR answer, /// and then confirm that they override the same method. What I've done here is check for the situations /// where the answers could disagree. I believe the results will be equivalent. If in doubt, a more conservative /// check would be implementingMethod.ContainingType.InterfacesAndTheirBaseInterfaces.Contains(@interface). /// </remarks> private static bool IsOverrideOfPossibleImplementationUnderRuntimeRules(MethodSymbol implementingMethod, NamedTypeSymbol @interface) { MethodSymbol curr = implementingMethod; while ((object)curr != null) { if (IsPossibleImplementationUnderRuntimeRules(curr, @interface)) { return true; } curr = curr.OverriddenMethod; } return false; } internal sealed override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() { return CalculateInterfacesToEmit(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal delegate void ReportMismatchInReturnType<TArg>(BindingDiagnosticBag bag, MethodSymbol overriddenMethod, MethodSymbol overridingMethod, bool topLevel, TArg arg); internal delegate void ReportMismatchInParameterType<TArg>(BindingDiagnosticBag bag, MethodSymbol overriddenMethod, MethodSymbol overridingMethod, ParameterSymbol parameter, bool topLevel, TArg arg); internal partial class SourceMemberContainerTypeSymbol { /// <summary> /// In some circumstances (e.g. implicit implementation of an interface method by a non-virtual method in a /// base type from another assembly) it is necessary for the compiler to generate explicit implementations for /// some interface methods. They don't go in the symbol table, but if we are emitting, then we should /// generate code for them. /// </summary> internal SynthesizedExplicitImplementations GetSynthesizedExplicitImplementations( CancellationToken cancellationToken) { if (_lazySynthesizedExplicitImplementations is null) { var diagnostics = BindingDiagnosticBag.GetInstance(); try { cancellationToken.ThrowIfCancellationRequested(); CheckMembersAgainstBaseType(diagnostics, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); CheckAbstractClassImplementations(diagnostics); cancellationToken.ThrowIfCancellationRequested(); CheckInterfaceUnification(diagnostics); if (this.IsInterface) { cancellationToken.ThrowIfCancellationRequested(); this.CheckInterfaceVarianceSafety(diagnostics); } if (Interlocked.CompareExchange( ref _lazySynthesizedExplicitImplementations, ComputeInterfaceImplementations(diagnostics, cancellationToken), null) is null) { // Do not cancel from this point on. We've assigned the member, so we must add // the diagnostics. AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.SynthesizedExplicitImplementations); } } finally { diagnostics.Free(); } } return _lazySynthesizedExplicitImplementations; } internal sealed override IEnumerable<(MethodSymbol Body, MethodSymbol Implemented)> SynthesizedInterfaceMethodImpls() { SynthesizedExplicitImplementations synthesizedImplementations = GetSynthesizedExplicitImplementations(cancellationToken: default); foreach (var methodImpl in synthesizedImplementations.MethodImpls) { yield return methodImpl; } foreach (var forwardingMethod in synthesizedImplementations.ForwardingMethods) { yield return (forwardingMethod.ImplementingMethod, forwardingMethod.ExplicitInterfaceImplementations.Single()); } } private void CheckAbstractClassImplementations(BindingDiagnosticBag diagnostics) { NamedTypeSymbol baseType = this.BaseTypeNoUseSiteDiagnostics; if (this.IsAbstract || (object)baseType == null || !baseType.IsAbstract) { return; } // CONSIDER: We know that no-one will ask for NotOverriddenAbstractMembers again // (since this class is concrete), so we could just call the construction method // directly to avoid storing the result. foreach (var abstractMember in this.AbstractMembers) { // Dev10 reports failure to implement properties/events in terms of the accessors if (abstractMember.Kind == SymbolKind.Method && abstractMember is not SynthesizedRecordOrdinaryMethod) { diagnostics.Add(ErrorCode.ERR_UnimplementedAbstractMethod, this.Locations[0], this, abstractMember); } } } private SynthesizedExplicitImplementations ComputeInterfaceImplementations( BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) { var forwardingMethods = ArrayBuilder<SynthesizedExplicitImplementationForwardingMethod>.GetInstance(); var methodImpls = ArrayBuilder<(MethodSymbol Body, MethodSymbol Implemented)>.GetInstance(); // NOTE: We can't iterator over this collection directly, since it is not ordered. Instead we // iterate over AllInterfaces and filter out the interfaces that are not in this set. This is // preferable to doing the DFS ourselves because both AllInterfaces and // InterfacesAndTheirBaseInterfaces are cached and used in multiple places. MultiDictionary<NamedTypeSymbol, NamedTypeSymbol> interfacesAndTheirBases = this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics; foreach (var @interface in this.AllInterfacesNoUseSiteDiagnostics) { cancellationToken.ThrowIfCancellationRequested(); if (!interfacesAndTheirBases[@interface].Contains(@interface)) { continue; } HasBaseTypeDeclaringInterfaceResult? hasBaseClassDeclaringInterface = null; foreach (var interfaceMember in @interface.GetMembers()) { cancellationToken.ThrowIfCancellationRequested(); // Only require implementations for members that can be implemented in C#. SymbolKind interfaceMemberKind = interfaceMember.Kind; switch (interfaceMemberKind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: if (!interfaceMember.IsImplementableInterfaceMember()) { continue; } break; default: continue; } SymbolAndDiagnostics implementingMemberAndDiagnostics; if (this.IsInterface) { MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = this.GetExplicitImplementationForInterfaceMember(interfaceMember); switch (explicitImpl.Count) { case 0: continue; // There is no requirement to implement anything in an interface case 1: implementingMemberAndDiagnostics = new SymbolAndDiagnostics(explicitImpl.Single(), ImmutableBindingDiagnostic<AssemblySymbol>.Empty); break; default: Diagnostic diag = new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_DuplicateExplicitImpl, interfaceMember), this.Locations[0]); implementingMemberAndDiagnostics = new SymbolAndDiagnostics(null, new ImmutableBindingDiagnostic<AssemblySymbol>(ImmutableArray.Create(diag), default)); break; } } else { implementingMemberAndDiagnostics = this.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMember); } var implementingMember = implementingMemberAndDiagnostics.Symbol; var synthesizedImplementation = this.SynthesizeInterfaceMemberImplementation(implementingMemberAndDiagnostics, interfaceMember); bool wasImplementingMemberFound = (object)implementingMember != null; if (synthesizedImplementation.ForwardingMethod is SynthesizedExplicitImplementationForwardingMethod forwardingMethod) { if (forwardingMethod.IsVararg) { diagnostics.Add( ErrorCode.ERR_InterfaceImplementedImplicitlyByVariadic, GetImplicitImplementationDiagnosticLocation(interfaceMember, this, implementingMember), implementingMember, interfaceMember, this); } else { forwardingMethods.Add(forwardingMethod); } } if (synthesizedImplementation.MethodImpl is { } methodImpl) { Debug.Assert(methodImpl is { Body: not null, Implemented: not null }); methodImpls.Add(methodImpl); } if (wasImplementingMemberFound && interfaceMemberKind == SymbolKind.Event) { // NOTE: unlike dev11, we're including a related location for the implementing type, because // otherwise the only error location will be in the containing type of the implementing event // (i.e. no indication of which type's interface list is actually problematic). EventSymbol interfaceEvent = (EventSymbol)interfaceMember; EventSymbol implementingEvent = (EventSymbol)implementingMember; EventSymbol maybeWinRTEvent; EventSymbol maybeRegularEvent; if (interfaceEvent.IsWindowsRuntimeEvent) { maybeWinRTEvent = interfaceEvent; // Definitely WinRT. maybeRegularEvent = implementingEvent; // Maybe regular. } else { maybeWinRTEvent = implementingEvent; // Maybe WinRT. maybeRegularEvent = interfaceEvent; // Definitely regular. } if (interfaceEvent.IsWindowsRuntimeEvent != implementingEvent.IsWindowsRuntimeEvent) { // At this point (and not before), we know that maybeWinRTEvent is definitely a WinRT event and maybeRegularEvent is definitely a regular event. var args = new object[] { implementingEvent, interfaceEvent, maybeWinRTEvent, maybeRegularEvent }; var info = new CSDiagnosticInfo(ErrorCode.ERR_MixingWinRTEventWithRegular, args, ImmutableArray<Symbol>.Empty, ImmutableArray.Create<Location>(this.Locations[0])); diagnostics.Add(info, implementingEvent.Locations[0]); } } // Dev10: If a whole property is missing, report the property. If the property is present, but an accessor // is missing, report just the accessor. var associatedPropertyOrEvent = interfaceMemberKind == SymbolKind.Method ? ((MethodSymbol)interfaceMember).AssociatedSymbol : null; if ((object)associatedPropertyOrEvent == null || ReportAccessorOfInterfacePropertyOrEvent(associatedPropertyOrEvent) || (wasImplementingMemberFound && !implementingMember.IsAccessor())) { //we're here because //(a) the interface member is not an accessor, or //(b) the interface member is an accessor of an interesting (see ReportAccessorOfInterfacePropertyOrEvent) property or event, or //(c) the implementing member exists and is not an accessor. bool reportedAnError = false; if (implementingMemberAndDiagnostics.Diagnostics.Diagnostics.Any()) { diagnostics.AddRange(implementingMemberAndDiagnostics.Diagnostics); reportedAnError = implementingMemberAndDiagnostics.Diagnostics.Diagnostics.Any(d => d.Severity == DiagnosticSeverity.Error); } if (!reportedAnError) { if (!wasImplementingMemberFound || (!implementingMember.ContainingType.Equals(this, TypeCompareKind.ConsiderEverything) && implementingMember.GetExplicitInterfaceImplementations().Contains(interfaceMember, ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance))) { // NOTE: An alternative approach would be to keep track of this while searching for the implementing member. // In some cases, we might even be able to stop looking and just accept that a base type has things covered // (though we'd have to be careful about losing diagnostics and we might produce fewer bridge methods). // However, this approach has the advantage that there is no cost unless we encounter a base type that // claims to implement an interface, but we can't figure out how (i.e. free in nearly all cases). hasBaseClassDeclaringInterface = hasBaseClassDeclaringInterface ?? HasBaseClassDeclaringInterface(@interface); HasBaseTypeDeclaringInterfaceResult matchResult = hasBaseClassDeclaringInterface.GetValueOrDefault(); if (matchResult != HasBaseTypeDeclaringInterfaceResult.ExactMatch && wasImplementingMemberFound && implementingMember.ContainingType.IsInterface) { HasBaseInterfaceDeclaringInterface(implementingMember.ContainingType, @interface, ref matchResult); } // If a base type from metadata declares that it implements the interface, we'll just trust it. // (See fFoundImport in SymbolPreparer::CheckInterfaceMethodImplementation.) switch (matchResult) { case HasBaseTypeDeclaringInterfaceResult.NoMatch: { // CONSIDER: Dev10 does not emit this diagnostic for interface properties if the // derived type attempts to implement an accessor directly as a method. // Suppress for bogus properties and events and for indexed properties. if (!interfaceMember.MustCallMethodsDirectly() && !interfaceMember.IsIndexedProperty()) { DiagnosticInfo useSiteDiagnostic = interfaceMember.GetUseSiteInfo().DiagnosticInfo; if (useSiteDiagnostic != null && useSiteDiagnostic.DefaultSeverity == DiagnosticSeverity.Error) { diagnostics.Add(useSiteDiagnostic, GetImplementsLocationOrFallback(@interface)); } else { diagnostics.Add(ErrorCode.ERR_UnimplementedInterfaceMember, GetImplementsLocationOrFallback(@interface), this, interfaceMember); } } } break; case HasBaseTypeDeclaringInterfaceResult.ExactMatch: break; case HasBaseTypeDeclaringInterfaceResult.IgnoringNullableMatch: diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, GetImplementsLocationOrFallback(@interface), this, interfaceMember); break; default: throw ExceptionUtilities.UnexpectedValue(matchResult); } } if (wasImplementingMemberFound && interfaceMemberKind == SymbolKind.Method) { // Don't report use site errors on properties - we'll report them on each of their accessors. // Don't report use site errors for implementations in other types unless // a synthesized implementation is needed that invokes the base method. // We can do so only if there are no use-site errors. if (synthesizedImplementation.ForwardingMethod is not null || TypeSymbol.Equals(implementingMember.ContainingType, this, TypeCompareKind.ConsiderEverything2)) { UseSiteInfo<AssemblySymbol> useSiteInfo = interfaceMember.GetUseSiteInfo(); // Don't report a use site error with a location in another compilation. For example, // if the error is that a base type in another assembly implemented an interface member // on our behalf and the use site error is that the current assembly does not reference // some required assembly, then we want to report the error in the current assembly - // not in the implementing assembly. Location location = implementingMember.IsFromCompilation(this.DeclaringCompilation) ? implementingMember.Locations[0] : this.Locations[0]; diagnostics.Add(useSiteInfo, location); } } } } } } return SynthesizedExplicitImplementations.Create(forwardingMethods.ToImmutableAndFree(), methodImpls.ToImmutableAndFree()); } protected abstract Location GetCorrespondingBaseListLocation(NamedTypeSymbol @base); #nullable enable private Location GetImplementsLocationOrFallback(NamedTypeSymbol implementedInterface) { return GetImplementsLocation(implementedInterface) ?? this.Locations[0]; } internal Location? GetImplementsLocation(NamedTypeSymbol implementedInterface) #nullable disable { // We ideally want to identify the interface location in the base list with an exact match but // will fall back and use the first derived interface if exact interface is not present. // this is the similar logic as the VB implementation. Debug.Assert(this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[implementedInterface].Contains(implementedInterface)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; NamedTypeSymbol directInterface = null; foreach (var iface in this.InterfacesNoUseSiteDiagnostics()) { if (TypeSymbol.Equals(iface, implementedInterface, TypeCompareKind.ConsiderEverything2)) { directInterface = iface; break; } else if ((object)directInterface == null && iface.ImplementsInterface(implementedInterface, ref discardedUseSiteInfo)) { directInterface = iface; } } Debug.Assert((object)directInterface != null); return GetCorrespondingBaseListLocation(directInterface); } /// <summary> /// It's not interesting to report diagnostics on implementation of interface accessors /// if the corresponding events or properties are not implemented (i.e. we want to suppress /// cascading diagnostics). /// Caveat: Indexed property accessors are always interesting. /// Caveat: It's also uninteresting if a WinRT event is implemented by a non-WinRT event, /// or vice versa. /// </summary> private bool ReportAccessorOfInterfacePropertyOrEvent(Symbol interfacePropertyOrEvent) { Debug.Assert((object)interfacePropertyOrEvent != null); // Accessors of indexed properties are always interesting. if (interfacePropertyOrEvent.IsIndexedProperty()) { return true; } Symbol implementingPropertyOrEvent; if (this.IsInterface) { MultiDictionary<Symbol, Symbol>.ValueSet explicitImpl = this.GetExplicitImplementationForInterfaceMember(interfacePropertyOrEvent); switch (explicitImpl.Count) { case 0: return true; case 1: implementingPropertyOrEvent = explicitImpl.Single(); break; default: implementingPropertyOrEvent = null; break; } } else { implementingPropertyOrEvent = this.FindImplementationForInterfaceMemberInNonInterface(interfacePropertyOrEvent); } // If the property or event wasn't implemented, then we'd prefer to report diagnostics about that. if ((object)implementingPropertyOrEvent == null) { return false; } // If the property or event was an event and was implemented, but the WinRT-ness didn't agree, // then we'd prefer to report diagnostics about that. if (interfacePropertyOrEvent.Kind == SymbolKind.Event && implementingPropertyOrEvent.Kind == SymbolKind.Event && ((EventSymbol)interfacePropertyOrEvent).IsWindowsRuntimeEvent != ((EventSymbol)implementingPropertyOrEvent).IsWindowsRuntimeEvent) { return false; } return true; } private enum HasBaseTypeDeclaringInterfaceResult { NoMatch, IgnoringNullableMatch, ExactMatch, } private HasBaseTypeDeclaringInterfaceResult HasBaseClassDeclaringInterface(NamedTypeSymbol @interface) { HasBaseTypeDeclaringInterfaceResult result = HasBaseTypeDeclaringInterfaceResult.NoMatch; for (NamedTypeSymbol currType = this.BaseTypeNoUseSiteDiagnostics; (object)currType != null; currType = currType.BaseTypeNoUseSiteDiagnostics) { if (DeclaresBaseInterface(currType, @interface, ref result)) { break; } } return result; } private static bool DeclaresBaseInterface(NamedTypeSymbol currType, NamedTypeSymbol @interface, ref HasBaseTypeDeclaringInterfaceResult result) { MultiDictionary<NamedTypeSymbol, NamedTypeSymbol>.ValueSet set = currType.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics[@interface]; if (set.Count != 0) { if (set.Contains(@interface)) { result = HasBaseTypeDeclaringInterfaceResult.ExactMatch; return true; } else if (result == HasBaseTypeDeclaringInterfaceResult.NoMatch && set.Contains(@interface, Symbols.SymbolEqualityComparer.IgnoringNullable)) { result = HasBaseTypeDeclaringInterfaceResult.IgnoringNullableMatch; } } return false; } private void HasBaseInterfaceDeclaringInterface(NamedTypeSymbol baseInterface, NamedTypeSymbol @interface, ref HasBaseTypeDeclaringInterfaceResult matchResult) { // Let's check for the trivial case first if (DeclaresBaseInterface(baseInterface, @interface, ref matchResult)) { return; } foreach (var interfaceType in this.AllInterfacesNoUseSiteDiagnostics) { if ((object)interfaceType == baseInterface) { continue; } if (interfaceType.Equals(baseInterface, TypeCompareKind.CLRSignatureCompareOptions) && DeclaresBaseInterface(interfaceType, @interface, ref matchResult)) { return; } } } private void CheckMembersAgainstBaseType( BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) { switch (this.TypeKind) { // These checks don't make sense for enums and delegates: case TypeKind.Enum: case TypeKind.Delegate: return; case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.Submission: // we have to check that "override" is not used break; default: throw ExceptionUtilities.UnexpectedValue(this.TypeKind); } foreach (var member in this.GetMembersUnordered()) { cancellationToken.ThrowIfCancellationRequested(); bool suppressAccessors; switch (member.Kind) { case SymbolKind.Method: var method = (MethodSymbol)member; if (MethodSymbol.CanOverrideOrHide(method.MethodKind) && !method.IsAccessor()) { if (member.IsOverride) { CheckOverrideMember(method, method.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } else { var sourceMethod = method as SourceMemberMethodSymbol; if ((object)sourceMethod != null) // skip submission initializer { var isNew = sourceMethod.IsNew; CheckNonOverrideMember(method, isNew, method.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } } } else if (method.MethodKind == MethodKind.Destructor) { // NOTE: Normal finalize methods CanOverrideOrHide and will go through the normal code path. // First is fine, since there should only be one, since there are no parameters. MethodSymbol overridden = method.GetFirstRuntimeOverriddenMethodIgnoringNewSlot(out _); // NOTE: Dev11 doesn't expose symbols, so it can treat destructors as override and let them go through the normal // checks. Roslyn can't, since the language says they are not virtual/override and that's what we need to expose // in the symbol model. Having said that, Dev11 doesn't seem to produce override errors other than this one // (see SymbolPreparer::prepareOperator). if ((object)overridden != null && overridden.IsMetadataFinal) { diagnostics.Add(ErrorCode.ERR_CantOverrideSealed, method.Locations[0], method, overridden); } } break; case SymbolKind.Property: var property = (PropertySymbol)member; var getMethod = property.GetMethod; var setMethod = property.SetMethod; // Handle the accessors here, instead of in the loop, so that we can ensure that // they're checked *after* the corresponding property. if (member.IsOverride) { CheckOverrideMember(property, property.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); if (!suppressAccessors) { if ((object)getMethod != null) { CheckOverrideMember(getMethod, getMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } if ((object)setMethod != null) { CheckOverrideMember(setMethod, setMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } } } else if (property is SourcePropertySymbolBase sourceProperty) { var isNewProperty = sourceProperty.IsNew; CheckNonOverrideMember(property, isNewProperty, property.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); if (!suppressAccessors) { if ((object)getMethod != null) { CheckNonOverrideMember(getMethod, isNewProperty, getMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } if ((object)setMethod != null) { CheckNonOverrideMember(setMethod, isNewProperty, setMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } } } break; case SymbolKind.Event: var @event = (EventSymbol)member; var addMethod = @event.AddMethod; var removeMethod = @event.RemoveMethod; // Handle the accessors here, instead of in the loop, so that we can ensure that // they're checked *after* the corresponding event. if (member.IsOverride) { CheckOverrideMember(@event, @event.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); if (!suppressAccessors) { if ((object)addMethod != null) { CheckOverrideMember(addMethod, addMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } if ((object)removeMethod != null) { CheckOverrideMember(removeMethod, removeMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } } } else { var isNewEvent = ((SourceEventSymbol)@event).IsNew; CheckNonOverrideMember(@event, isNewEvent, @event.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); if (!suppressAccessors) { if ((object)addMethod != null) { CheckNonOverrideMember(addMethod, isNewEvent, addMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } if ((object)removeMethod != null) { CheckNonOverrideMember(removeMethod, isNewEvent, removeMethod.OverriddenOrHiddenMembers, diagnostics, out suppressAccessors); } } } break; case SymbolKind.Field: var sourceField = member as SourceFieldSymbol; var isNewField = (object)sourceField != null && sourceField.IsNew; // We don't want to report diagnostics for field-like event backing fields (redundant), // but that shouldn't be an issue since they shouldn't be in the member list. Debug.Assert((object)sourceField == null || (object)sourceField.AssociatedSymbol == null || sourceField.AssociatedSymbol.Kind != SymbolKind.Event); CheckNewModifier(member, isNewField, diagnostics); break; case SymbolKind.NamedType: CheckNewModifier(member, ((SourceMemberContainerTypeSymbol)member).IsNew, diagnostics); break; } } } private void CheckNewModifier(Symbol symbol, bool isNew, BindingDiagnosticBag diagnostics) { Debug.Assert(symbol.Kind == SymbolKind.Field || symbol.Kind == SymbolKind.NamedType); // Do not give warnings about missing 'new' modifier for implicitly declared members, // e.g. backing fields for auto-properties if (symbol.IsImplicitlyDeclared) { return; } if (symbol.ContainingType.IsInterface) { CheckNonOverrideMember(symbol, isNew, OverriddenOrHiddenMembersHelpers.MakeInterfaceOverriddenOrHiddenMembers(symbol, memberIsFromSomeCompilation: true), diagnostics, out _); return; } // for error cases if ((object)this.BaseTypeNoUseSiteDiagnostics == null) { return; } int symbolArity = symbol.GetMemberArity(); Location symbolLocation = symbol.Locations.FirstOrDefault(); bool unused = false; NamedTypeSymbol currType = this.BaseTypeNoUseSiteDiagnostics; while ((object)currType != null) { foreach (var hiddenMember in currType.GetMembers(symbol.Name)) { if (hiddenMember.Kind == SymbolKind.Method && !((MethodSymbol)hiddenMember).CanBeHiddenByMemberKind(symbol.Kind)) { continue; } var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); bool isAccessible = AccessCheck.IsSymbolAccessible(hiddenMember, this, ref useSiteInfo); diagnostics.Add(symbolLocation, useSiteInfo); if (isAccessible && hiddenMember.GetMemberArity() == symbolArity) { if (!isNew) { diagnostics.Add(ErrorCode.WRN_NewRequired, symbolLocation, symbol, hiddenMember); } AddHidingAbstractDiagnostic(symbol, symbolLocation, hiddenMember, diagnostics, ref unused); return; } } currType = currType.BaseTypeNoUseSiteDiagnostics; } if (isNew) { diagnostics.Add(ErrorCode.WRN_NewNotRequired, symbolLocation, symbol); } } private void CheckOverrideMember( Symbol overridingMember, OverriddenOrHiddenMembersResult overriddenOrHiddenMembers, BindingDiagnosticBag diagnostics, out bool suppressAccessors) { Debug.Assert((object)overridingMember != null); Debug.Assert(overriddenOrHiddenMembers != null); suppressAccessors = false; var overridingMemberIsMethod = overridingMember.Kind == SymbolKind.Method; var overridingMemberIsProperty = overridingMember.Kind == SymbolKind.Property; var overridingMemberIsEvent = overridingMember.Kind == SymbolKind.Event; Debug.Assert(overridingMemberIsMethod ^ overridingMemberIsProperty ^ overridingMemberIsEvent); var overridingMemberLocation = overridingMember.Locations[0]; var overriddenMembers = overriddenOrHiddenMembers.OverriddenMembers; Debug.Assert(!overriddenMembers.IsDefault); if (overriddenMembers.Length == 0) { var hiddenMembers = overriddenOrHiddenMembers.HiddenMembers; Debug.Assert(!hiddenMembers.IsDefault); if (hiddenMembers.Any()) { ErrorCode errorCode = overridingMemberIsMethod ? ErrorCode.ERR_CantOverrideNonFunction : overridingMemberIsProperty ? ErrorCode.ERR_CantOverrideNonProperty : ErrorCode.ERR_CantOverrideNonEvent; diagnostics.Add(errorCode, overridingMemberLocation, overridingMember, hiddenMembers[0]); } else { Symbol associatedPropertyOrEvent = null; if (overridingMemberIsMethod) { associatedPropertyOrEvent = ((MethodSymbol)overridingMember).AssociatedSymbol; } if ((object)associatedPropertyOrEvent == null) { bool suppressError = false; if (overridingMemberIsMethod || overridingMember.IsIndexer()) { var parameterTypes = overridingMemberIsMethod ? ((MethodSymbol)overridingMember).ParameterTypesWithAnnotations : ((PropertySymbol)overridingMember).ParameterTypesWithAnnotations; foreach (var parameterType in parameterTypes) { if (IsOrContainsErrorType(parameterType.Type)) { suppressError = true; // The parameter type must be fixed before the override can be found, so suppress error break; } } } if (!suppressError) { diagnostics.Add(ErrorCode.ERR_OverrideNotExpected, overridingMemberLocation, overridingMember); } } else if (associatedPropertyOrEvent.Kind == SymbolKind.Property) //no specific errors for event accessors { PropertySymbol associatedProperty = (PropertySymbol)associatedPropertyOrEvent; PropertySymbol overriddenProperty = associatedProperty.OverriddenProperty; if ((object)overriddenProperty == null) { //skip remaining checks } else if (associatedProperty.GetMethod == overridingMember && (object)overriddenProperty.GetMethod == null) { diagnostics.Add(ErrorCode.ERR_NoGetToOverride, overridingMemberLocation, overridingMember, overriddenProperty); } else if (associatedProperty.SetMethod == overridingMember && (object)overriddenProperty.SetMethod == null) { diagnostics.Add(ErrorCode.ERR_NoSetToOverride, overridingMemberLocation, overridingMember, overriddenProperty); } else { diagnostics.Add(ErrorCode.ERR_OverrideNotExpected, overridingMemberLocation, overridingMember); } } } } else { NamedTypeSymbol overridingType = overridingMember.ContainingType; if (overriddenMembers.Length > 1) { diagnostics.Add(ErrorCode.ERR_AmbigOverride, overridingMemberLocation, overriddenMembers[0].OriginalDefinition, overriddenMembers[1].OriginalDefinition, overridingType); suppressAccessors = true; } else { checkSingleOverriddenMember(overridingMember, overriddenMembers[0], diagnostics, ref suppressAccessors); } } // Both `ref` and `out` parameters (and `in` too) are implemented as references and are not distinguished by the runtime // when resolving overrides. Similarly, distinctions between types that would map together because of generic substitution // in the derived type where the override appears are the same from the runtime's point of view. In these cases we will // need to produce a methodimpl to disambiguate. See the call to `RequiresExplicitOverride` below. It produces a boolean // `warnAmbiguous` if the methodimpl could be misinterpreted due to a bug in the runtime // (https://github.com/dotnet/runtime/issues/38119) in which case we produce a warning regarding that ambiguity. // See https://github.com/dotnet/roslyn/issues/45453 for details. if (!this.ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses && overridingMember is MethodSymbol overridingMethod) { overridingMethod.RequiresExplicitOverride(out bool warnAmbiguous); if (warnAmbiguous) { var ambiguousMethod = overridingMethod.OverriddenMethod; diagnostics.Add(ErrorCode.WRN_MultipleRuntimeOverrideMatches, ambiguousMethod.Locations[0], ambiguousMethod, overridingMember); suppressAccessors = true; } } return; void checkSingleOverriddenMember(Symbol overridingMember, Symbol overriddenMember, BindingDiagnosticBag diagnostics, ref bool suppressAccessors) { var overridingMemberLocation = overridingMember.Locations[0]; var overridingMemberIsMethod = overridingMember.Kind == SymbolKind.Method; var overridingMemberIsProperty = overridingMember.Kind == SymbolKind.Property; var overridingMemberIsEvent = overridingMember.Kind == SymbolKind.Event; var overridingType = overridingMember.ContainingType; //otherwise, it would have been excluded during lookup #if DEBUG { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; Debug.Assert(AccessCheck.IsSymbolAccessible(overriddenMember, overridingType, ref discardedUseSiteInfo)); } #endif Debug.Assert(overriddenMember.Kind == overridingMember.Kind); if (overriddenMember.MustCallMethodsDirectly()) { diagnostics.Add(ErrorCode.ERR_CantOverrideBogusMethod, overridingMemberLocation, overridingMember, overriddenMember); suppressAccessors = true; } else if (!overriddenMember.IsVirtual && !overriddenMember.IsAbstract && !overriddenMember.IsOverride && !(overridingMemberIsMethod && ((MethodSymbol)overriddenMember).MethodKind == MethodKind.Destructor)) //destructors are metadata virtual { // CONSIDER: To match Dev10, skip the error for properties, and don't suppressAccessors diagnostics.Add(ErrorCode.ERR_CantOverrideNonVirtual, overridingMemberLocation, overridingMember, overriddenMember); suppressAccessors = true; } else if (overriddenMember.IsSealed) { // CONSIDER: To match Dev10, skip the error for properties, and don't suppressAccessors diagnostics.Add(ErrorCode.ERR_CantOverrideSealed, overridingMemberLocation, overridingMember, overriddenMember); suppressAccessors = true; } else if (!OverrideHasCorrectAccessibility(overriddenMember, overridingMember)) { var accessibility = SyntaxFacts.GetText(overriddenMember.DeclaredAccessibility); diagnostics.Add(ErrorCode.ERR_CantChangeAccessOnOverride, overridingMemberLocation, overridingMember, accessibility, overriddenMember); suppressAccessors = true; } else if (overridingMember.ContainsTupleNames() && MemberSignatureComparer.ConsideringTupleNamesCreatesDifference(overridingMember, overriddenMember)) { // it is ok to override with no tuple names, for compatibility with C# 6, but otherwise names should match diagnostics.Add(ErrorCode.ERR_CantChangeTupleNamesOnOverride, overridingMemberLocation, overridingMember, overriddenMember); } else { // As in dev11, we don't compare obsoleteness to the immediately-overridden member, // but to the least-overridden member. var leastOverriddenMember = overriddenMember.GetLeastOverriddenMember(overriddenMember.ContainingType); overridingMember.ForceCompleteObsoleteAttribute(); leastOverriddenMember.ForceCompleteObsoleteAttribute(); Debug.Assert(overridingMember.ObsoleteState != ThreeState.Unknown); Debug.Assert(leastOverriddenMember.ObsoleteState != ThreeState.Unknown); bool overridingMemberIsObsolete = overridingMember.ObsoleteState == ThreeState.True; bool leastOverriddenMemberIsObsolete = leastOverriddenMember.ObsoleteState == ThreeState.True; if (overridingMemberIsObsolete != leastOverriddenMemberIsObsolete) { ErrorCode code = overridingMemberIsObsolete ? ErrorCode.WRN_ObsoleteOverridingNonObsolete : ErrorCode.WRN_NonObsoleteOverridingObsolete; diagnostics.Add(code, overridingMemberLocation, overridingMember, leastOverriddenMember); } if (overridingMemberIsProperty) { checkOverriddenProperty((PropertySymbol)overridingMember, (PropertySymbol)overriddenMember, diagnostics, ref suppressAccessors); } else if (overridingMemberIsEvent) { EventSymbol overridingEvent = (EventSymbol)overridingMember; EventSymbol overriddenEvent = (EventSymbol)overriddenMember; TypeWithAnnotations overridingMemberType = overridingEvent.TypeWithAnnotations; TypeWithAnnotations overriddenMemberType = overriddenEvent.TypeWithAnnotations; // Ignore custom modifiers because this diagnostic is based on the C# semantics. if (!overridingMemberType.Equals(overriddenMemberType, TypeCompareKind.AllIgnoreOptions)) { // if the type is or contains an error type, the type must be fixed before the override can be found, so suppress error if (!IsOrContainsErrorType(overridingMemberType.Type)) { diagnostics.Add(ErrorCode.ERR_CantChangeTypeOnOverride, overridingMemberLocation, overridingMember, overriddenMember, overriddenMemberType.Type); } suppressAccessors = true; //we get really unhelpful errors from the accessor if the type is mismatched } else { CheckValidNullableEventOverride(overridingEvent.DeclaringCompilation, overriddenEvent, overridingEvent, diagnostics, (diagnostics, overriddenEvent, overridingEvent, location) => diagnostics.Add(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, location), overridingMemberLocation); } } else { Debug.Assert(overridingMemberIsMethod); var overridingMethod = (MethodSymbol)overridingMember; var overriddenMethod = (MethodSymbol)overriddenMember; if (overridingMethod.IsGenericMethod) { overriddenMethod = overriddenMethod.Construct(TypeMap.TypeParametersAsTypeSymbolsWithIgnoredAnnotations(overridingMethod.TypeParameters)); } // Check for mismatched byref returns and return type. Ignore custom modifiers, because this diagnostic is based on the C# semantics. if (overridingMethod.RefKind != overriddenMethod.RefKind) { diagnostics.Add(ErrorCode.ERR_CantChangeRefReturnOnOverride, overridingMemberLocation, overridingMember, overriddenMember); } else if (!IsValidOverrideReturnType(overridingMethod, overridingMethod.ReturnTypeWithAnnotations, overriddenMethod.ReturnTypeWithAnnotations, diagnostics)) { // if the Return type is or contains an error type, the return type must be fixed before the override can be found, so suppress error if (!IsOrContainsErrorType(overridingMethod.ReturnType)) { // If the return type would be a valid covariant return, suggest using covariant return feature. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if (DeclaringCompilation.Conversions.HasIdentityOrImplicitReferenceConversion(overridingMethod.ReturnTypeWithAnnotations.Type, overriddenMethod.ReturnTypeWithAnnotations.Type, ref discardedUseSiteInfo)) { if (!overridingMethod.ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses, overridingMemberLocation, overridingMember, overriddenMember, overriddenMethod.ReturnType); } else if (MessageID.IDS_FeatureCovariantReturnsForOverrides.GetFeatureAvailabilityDiagnosticInfo(this.DeclaringCompilation) is { } diagnosticInfo) { diagnostics.Add(diagnosticInfo, overridingMemberLocation); } else { throw ExceptionUtilities.Unreachable; } } else { // error CS0508: return type must be 'C<V>' to match overridden member 'M<T>()' diagnostics.Add(ErrorCode.ERR_CantChangeReturnTypeOnOverride, overridingMemberLocation, overridingMember, overriddenMember, overriddenMethod.ReturnType); } } } else if (overriddenMethod.IsRuntimeFinalizer()) { diagnostics.Add(ErrorCode.ERR_OverrideFinalizeDeprecated, overridingMemberLocation); } else if (!overridingMethod.IsAccessor()) { // Accessors will have already been checked above checkValidNullableMethodOverride( overridingMemberLocation, overriddenMethod, overridingMethod, diagnostics, checkReturnType: true, checkParameters: true); } } // NOTE: this error may be redundant (if an error has already been reported // for the return type or parameter type in question), but the scenario is // too rare to justify complicated checks. if (Binder.ReportUseSite(overriddenMember, diagnostics, overridingMember.Locations[0])) { suppressAccessors = true; } } void checkOverriddenProperty(PropertySymbol overridingProperty, PropertySymbol overriddenProperty, BindingDiagnosticBag diagnostics, ref bool suppressAccessors) { var overridingMemberLocation = overridingProperty.Locations[0]; var overridingType = overridingProperty.ContainingType; TypeWithAnnotations overridingMemberType = overridingProperty.TypeWithAnnotations; TypeWithAnnotations overriddenMemberType = overriddenProperty.TypeWithAnnotations; // Check for mismatched byref returns and return type. Ignore custom modifiers, because this diagnostic is based on the C# semantics. if (overridingProperty.RefKind != overriddenProperty.RefKind) { diagnostics.Add(ErrorCode.ERR_CantChangeRefReturnOnOverride, overridingMemberLocation, overridingProperty, overriddenProperty); suppressAccessors = true; //we get really unhelpful errors from the accessor if the ref kind is mismatched } else if (overridingProperty.SetMethod is null ? !IsValidOverrideReturnType(overridingProperty, overridingMemberType, overriddenMemberType, diagnostics) : !overridingMemberType.Equals(overriddenMemberType, TypeCompareKind.AllIgnoreOptions)) { // if the type is or contains an error type, the type must be fixed before the override can be found, so suppress error if (!IsOrContainsErrorType(overridingMemberType.Type)) { // If the type would be a valid covariant return, suggest using covariant return feature. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if (overridingProperty.SetMethod is null && DeclaringCompilation.Conversions.HasIdentityOrImplicitReferenceConversion(overridingMemberType.Type, overriddenMemberType.Type, ref discardedUseSiteInfo)) { if (!overridingProperty.ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses) { diagnostics.Add(ErrorCode.ERR_RuntimeDoesNotSupportCovariantPropertiesOfClasses, overridingMemberLocation, overridingMember, overriddenMember, overriddenMemberType.Type); } else { var diagnosticInfo = MessageID.IDS_FeatureCovariantReturnsForOverrides.GetFeatureAvailabilityDiagnosticInfo(this.DeclaringCompilation); Debug.Assert(diagnosticInfo is { }); diagnostics.Add(diagnosticInfo, overridingMemberLocation); } } else { // error CS1715: 'Derived.M': type must be 'object' to match overridden member 'Base.M' diagnostics.Add(ErrorCode.ERR_CantChangeTypeOnOverride, overridingMemberLocation, overridingMember, overriddenMember, overriddenMemberType.Type); // https://github.com/dotnet/roslyn/issues/44207 when overriddenMemberType.Type is an inheritable reference type and the covariant return // feature is enabled, and the platform supports it, and there is no setter, we can say it has to be 'object' **or a derived type**. // That would probably be a new error code. } } suppressAccessors = true; //we get really unhelpful errors from the accessor if the type is mismatched } else { if (overridingProperty.GetMethod is object) { MethodSymbol overriddenGetMethod = overriddenProperty.GetOwnOrInheritedGetMethod(); checkValidNullableMethodOverride( overridingProperty.GetMethod.Locations[0], overriddenGetMethod, overridingProperty.GetMethod, diagnostics, checkReturnType: true, // Don't check parameters on the getter if there is a setter // because they will be a subset of the setter checkParameters: overridingProperty.SetMethod is null || overriddenGetMethod?.AssociatedSymbol != overriddenProperty || overriddenProperty.GetOwnOrInheritedSetMethod()?.AssociatedSymbol != overriddenProperty); } if (overridingProperty.SetMethod is object) { var ownOrInheritedOverriddenSetMethod = overriddenProperty.GetOwnOrInheritedSetMethod(); checkValidNullableMethodOverride( overridingProperty.SetMethod.Locations[0], ownOrInheritedOverriddenSetMethod, overridingProperty.SetMethod, diagnostics, checkReturnType: false, checkParameters: true); if (ownOrInheritedOverriddenSetMethod is object && overridingProperty.SetMethod.IsInitOnly != ownOrInheritedOverriddenSetMethod.IsInitOnly) { diagnostics.Add(ErrorCode.ERR_CantChangeInitOnlyOnOverride, overridingMemberLocation, overridingProperty, overriddenProperty); } } } // If the overriding property is sealed, then the overridden accessors cannot be inaccessible, since we // have to override them to make them sealed in metadata. // CONSIDER: It might be nice if this had its own error code(s) since it's an implementation restriction, // rather than a language restriction as above. if (overridingProperty.IsSealed) { MethodSymbol ownOrInheritedGetMethod = overridingProperty.GetOwnOrInheritedGetMethod(); var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, overridingProperty.ContainingAssembly); if (overridingProperty.GetMethod != ownOrInheritedGetMethod && !AccessCheck.IsSymbolAccessible(ownOrInheritedGetMethod, overridingType, ref useSiteInfo)) { diagnostics.Add(ErrorCode.ERR_NoGetToOverride, overridingMemberLocation, overridingProperty, overriddenProperty); } MethodSymbol ownOrInheritedSetMethod = overridingProperty.GetOwnOrInheritedSetMethod(); if (overridingProperty.SetMethod != ownOrInheritedSetMethod && !AccessCheck.IsSymbolAccessible(ownOrInheritedSetMethod, overridingType, ref useSiteInfo)) { diagnostics.Add(ErrorCode.ERR_NoSetToOverride, overridingMemberLocation, overridingProperty, overriddenProperty); } diagnostics.Add(overridingMemberLocation, useSiteInfo); } } } static void checkValidNullableMethodOverride( Location overridingMemberLocation, MethodSymbol overriddenMethod, MethodSymbol overridingMethod, BindingDiagnosticBag diagnostics, bool checkReturnType, bool checkParameters) { CheckValidNullableMethodOverride(overridingMethod.DeclaringCompilation, overriddenMethod, overridingMethod, diagnostics, checkReturnType ? ReportBadReturn : null, checkParameters ? ReportBadParameter : null, overridingMemberLocation); } } internal static bool IsOrContainsErrorType(TypeSymbol typeSymbol) { return (object)typeSymbol.VisitType((currentTypeSymbol, unused1, unused2) => currentTypeSymbol.IsErrorType(), (object)null) != null; } /// <summary> /// Return true if <paramref name="overridingReturnType"/> is valid for the return type of an override method when the overridden method's return type is <paramref name="overriddenReturnType"/>. /// </summary> private bool IsValidOverrideReturnType(Symbol overridingSymbol, TypeWithAnnotations overridingReturnType, TypeWithAnnotations overriddenReturnType, BindingDiagnosticBag diagnostics) { if (overridingSymbol.ContainingAssembly.RuntimeSupportsCovariantReturnsOfClasses && DeclaringCompilation.LanguageVersion >= MessageID.IDS_FeatureCovariantReturnsForOverrides.RequiredVersion()) { var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, ContainingAssembly); var result = DeclaringCompilation.Conversions.HasIdentityOrImplicitReferenceConversion(overridingReturnType.Type, overriddenReturnType.Type, ref useSiteInfo); Location symbolLocation = overridingSymbol.Locations.FirstOrDefault(); diagnostics.Add(symbolLocation, useSiteInfo); return result; } else { return overridingReturnType.Equals(overriddenReturnType, TypeCompareKind.AllIgnoreOptions); } } static readonly ReportMismatchInReturnType<Location> ReportBadReturn = (BindingDiagnosticBag diagnostics, MethodSymbol overriddenMethod, MethodSymbol overridingMethod, bool topLevel, Location location) => diagnostics.Add(topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride : ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, location); static readonly ReportMismatchInParameterType<Location> ReportBadParameter = (BindingDiagnosticBag diagnostics, MethodSymbol overriddenMethod, MethodSymbol overridingMethod, ParameterSymbol overridingParameter, bool topLevel, Location location) => diagnostics.Add( topLevel ? ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride : ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, location, new FormattedSymbol(overridingParameter, SymbolDisplayFormat.ShortFormat)); /// <returns> /// <see langword="true"/> if a diagnostic was added. Otherwise, <see langword="false"/>. /// </returns> internal static bool CheckValidNullableMethodOverride<TArg>( CSharpCompilation compilation, MethodSymbol baseMethod, MethodSymbol overrideMethod, BindingDiagnosticBag diagnostics, ReportMismatchInReturnType<TArg> reportMismatchInReturnType, ReportMismatchInParameterType<TArg> reportMismatchInParameterType, TArg extraArgument, bool invokedAsExtensionMethod = false) { if (!PerformValidNullableOverrideCheck(compilation, baseMethod, overrideMethod)) { return false; } bool hasErrors = false; if ((baseMethod.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) == FlowAnalysisAnnotations.DoesNotReturn && (overrideMethod.FlowAnalysisAnnotations & FlowAnalysisAnnotations.DoesNotReturn) != FlowAnalysisAnnotations.DoesNotReturn) { diagnostics.Add(ErrorCode.WRN_DoesNotReturnMismatch, overrideMethod.Locations[0], new FormattedSymbol(overrideMethod, SymbolDisplayFormat.MinimallyQualifiedFormat)); hasErrors = true; } var conversions = compilation.Conversions.WithNullability(true); var baseParameters = baseMethod.Parameters; var overrideParameters = overrideMethod.Parameters; var overrideParameterOffset = invokedAsExtensionMethod ? 1 : 0; Debug.Assert(baseMethod.ParameterCount == overrideMethod.ParameterCount - overrideParameterOffset); if (reportMismatchInReturnType != null) { var overrideReturnType = getNotNullIfNotNullOutputType(overrideMethod.ReturnTypeWithAnnotations, overrideMethod.ReturnNotNullIfParameterNotNull); // check nested nullability if (!isValidNullableConversion( conversions, overrideMethod.RefKind, overrideReturnType.Type, baseMethod.ReturnTypeWithAnnotations.Type)) { reportMismatchInReturnType(diagnostics, baseMethod, overrideMethod, false, extraArgument); return true; } // check top-level nullability including flow analysis annotations if (!NullableWalker.AreParameterAnnotationsCompatible( overrideMethod.RefKind == RefKind.Ref ? RefKind.Ref : RefKind.Out, baseMethod.ReturnTypeWithAnnotations, baseMethod.ReturnTypeFlowAnalysisAnnotations, overrideReturnType, overrideMethod.ReturnTypeFlowAnalysisAnnotations)) { reportMismatchInReturnType(diagnostics, baseMethod, overrideMethod, true, extraArgument); return true; } } if (reportMismatchInParameterType != null) { for (int i = 0; i < baseParameters.Length; i++) { var baseParameter = baseParameters[i]; var baseParameterType = baseParameter.TypeWithAnnotations; var overrideParameter = overrideParameters[i + overrideParameterOffset]; var overrideParameterType = getNotNullIfNotNullOutputType(overrideParameter.TypeWithAnnotations, overrideParameter.NotNullIfParameterNotNull); // check nested nullability if (!isValidNullableConversion( conversions, overrideParameter.RefKind, baseParameterType.Type, overrideParameterType.Type)) { reportMismatchInParameterType(diagnostics, baseMethod, overrideMethod, overrideParameter, false, extraArgument); hasErrors = true; } // check top-level nullability including flow analysis annotations else if (!NullableWalker.AreParameterAnnotationsCompatible( overrideParameter.RefKind, baseParameterType, baseParameter.FlowAnalysisAnnotations, overrideParameterType, overrideParameter.FlowAnalysisAnnotations)) { reportMismatchInParameterType(diagnostics, baseMethod, overrideMethod, overrideParameter, true, extraArgument); hasErrors = true; } } } return hasErrors; TypeWithAnnotations getNotNullIfNotNullOutputType(TypeWithAnnotations outputType, ImmutableHashSet<string> notNullIfParameterNotNull) { if (!notNullIfParameterNotNull.IsEmpty) { for (var i = 0; i < baseParameters.Length; i++) { var overrideParam = overrideParameters[i + overrideParameterOffset]; var baseParam = baseParameters[i]; if (notNullIfParameterNotNull.Contains(overrideParam.Name) && NullableWalker.GetParameterState(baseParam.TypeWithAnnotations, baseParam.FlowAnalysisAnnotations).IsNotNull) { return outputType.AsNotAnnotated(); } } } return outputType; } static bool isValidNullableConversion( ConversionsBase conversions, RefKind refKind, TypeSymbol sourceType, TypeSymbol targetType) { switch (refKind) { case RefKind.Ref: // ref variables are invariant return sourceType.Equals( targetType, TypeCompareKind.AllIgnoreOptions & ~(TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); case RefKind.Out: // out variables have inverted variance (sourceType, targetType) = (targetType, sourceType); break; default: break; } Debug.Assert(conversions.IncludeNullability); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return conversions.ClassifyImplicitConversionFromType(sourceType, targetType, ref discardedUseSiteInfo).Kind != ConversionKind.NoConversion; } } private static bool PerformValidNullableOverrideCheck( CSharpCompilation compilation, Symbol overriddenMember, Symbol overridingMember) { // Don't do any validation if the nullable feature is not enabled or // the override is not written directly in source return overriddenMember is object && overridingMember is object && compilation is object && compilation.IsFeatureEnabled(MessageID.IDS_FeatureNullableReferenceTypes); } internal static void CheckValidNullableEventOverride<TArg>( CSharpCompilation compilation, EventSymbol overriddenEvent, EventSymbol overridingEvent, BindingDiagnosticBag diagnostics, Action<BindingDiagnosticBag, EventSymbol, EventSymbol, TArg> reportMismatch, TArg extraArgument) { if (!PerformValidNullableOverrideCheck(compilation, overriddenEvent, overridingEvent)) { return; } var conversions = compilation.Conversions.WithNullability(true); if (!conversions.HasAnyNullabilityImplicitConversion(overriddenEvent.TypeWithAnnotations, overridingEvent.TypeWithAnnotations)) { reportMismatch(diagnostics, overriddenEvent, overridingEvent, extraArgument); } } private static void CheckNonOverrideMember( Symbol hidingMember, bool hidingMemberIsNew, OverriddenOrHiddenMembersResult overriddenOrHiddenMembers, BindingDiagnosticBag diagnostics, out bool suppressAccessors) { suppressAccessors = false; var hidingMemberLocation = hidingMember.Locations[0]; Debug.Assert(overriddenOrHiddenMembers != null); Debug.Assert(!overriddenOrHiddenMembers.OverriddenMembers.Any()); //since hidingMethod.IsOverride is false var hiddenMembers = overriddenOrHiddenMembers.HiddenMembers; Debug.Assert(!hiddenMembers.IsDefault); if (hiddenMembers.Length == 0) { if (hidingMemberIsNew && !hidingMember.IsAccessor()) { diagnostics.Add(ErrorCode.WRN_NewNotRequired, hidingMemberLocation, hidingMember); } } else { var diagnosticAdded = false; //for interfaces, we always report WRN_NewRequired //if we went into the loop, the pseudo-abstract nature of interfaces would throw off the other checks if (!hidingMember.ContainingType.IsInterface) { foreach (var hiddenMember in hiddenMembers) { diagnosticAdded |= AddHidingAbstractDiagnostic(hidingMember, hidingMemberLocation, hiddenMember, diagnostics, ref suppressAccessors); //can actually get both, so don't use else if if (!hidingMemberIsNew && hiddenMember.Kind == hidingMember.Kind && !hidingMember.IsAccessor() && (hiddenMember.IsAbstract || hiddenMember.IsVirtual || hiddenMember.IsOverride) && !IsShadowingSynthesizedRecordMember(hidingMember)) { diagnostics.Add(ErrorCode.WRN_NewOrOverrideExpected, hidingMemberLocation, hidingMember, hiddenMember); diagnosticAdded = true; } if (diagnosticAdded) { break; } } } if (!hidingMemberIsNew && !IsShadowingSynthesizedRecordMember(hidingMember) && !diagnosticAdded && !hidingMember.IsAccessor() && !hidingMember.IsOperator()) { diagnostics.Add(ErrorCode.WRN_NewRequired, hidingMemberLocation, hidingMember, hiddenMembers[0]); } } } private static bool IsShadowingSynthesizedRecordMember(Symbol hidingMember) { return hidingMember is SynthesizedRecordEquals || hidingMember is SynthesizedRecordDeconstruct || hidingMember is SynthesizedRecordClone; } /// <summary> /// If necessary, report a diagnostic for a hidden abstract member. /// </summary> /// <returns>True if a diagnostic was reported.</returns> private static bool AddHidingAbstractDiagnostic(Symbol hidingMember, Location hidingMemberLocation, Symbol hiddenMember, BindingDiagnosticBag diagnostics, ref bool suppressAccessors) { switch (hiddenMember.Kind) { case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: break; // Can result in diagnostic default: return false; // Cannot result in diagnostic } // If the hidden member isn't abstract, the diagnostic doesn't apply. // If the hiding member is in a non-abstract type, then suppress this cascading error. if (!hiddenMember.IsAbstract || !hidingMember.ContainingType.IsAbstract) { return false; } switch (hidingMember.DeclaredAccessibility) { case Accessibility.Internal: case Accessibility.Private: case Accessibility.ProtectedAndInternal: break; case Accessibility.Public: case Accessibility.ProtectedOrInternal: case Accessibility.Protected: { // At this point we know we're going to report ERR_HidingAbstractMethod, we just have to // figure out the substitutions. switch (hidingMember.Kind) { case SymbolKind.Method: var associatedPropertyOrEvent = ((MethodSymbol)hidingMember).AssociatedSymbol; if ((object)associatedPropertyOrEvent != null) { //Dev10 reports that the property/event is doing the hiding, rather than the method diagnostics.Add(ErrorCode.ERR_HidingAbstractMethod, associatedPropertyOrEvent.Locations[0], associatedPropertyOrEvent, hiddenMember); break; } goto default; case SymbolKind.Property: case SymbolKind.Event: // NOTE: We used to let the accessors take care of this case, but then we weren't handling the case // where a hiding and hidden properties did not have any accessors in common. // CONSIDER: Dev10 actually reports an error for each accessor of a hidden property/event, but that seems unnecessary. suppressAccessors = true; goto default; default: diagnostics.Add(ErrorCode.ERR_HidingAbstractMethod, hidingMemberLocation, hidingMember, hiddenMember); break; } return true; } default: throw ExceptionUtilities.UnexpectedValue(hidingMember.DeclaredAccessibility); } return false; } private static bool OverrideHasCorrectAccessibility(Symbol overridden, Symbol overriding) { // Check declared accessibility rather than effective accessibility since there's a different // check (CS0560) that determines whether the containing types have compatible accessibility. if (!overriding.ContainingAssembly.HasInternalAccessTo(overridden.ContainingAssembly) && overridden.DeclaredAccessibility == Accessibility.ProtectedOrInternal) { return overriding.DeclaredAccessibility == Accessibility.Protected; } else { return overridden.DeclaredAccessibility == overriding.DeclaredAccessibility; } } #nullable enable /// <summary> /// It is invalid for a type to directly (vs through a base class) implement two interfaces that /// unify (i.e. are the same for some substitution of type parameters). /// </summary> /// <remarks> /// CONSIDER: check this while building up InterfacesAndTheirBaseInterfaces (only in the SourceNamedTypeSymbol case). /// </remarks> private void CheckInterfaceUnification(BindingDiagnosticBag diagnostics) { if (!this.IsGenericType) { return; } // CONSIDER: filtering the list to only include generic types would save iterations. int numInterfaces = this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.Count; if (numInterfaces < 2) { return; } // NOTE: a typical approach to finding duplicates in less than quadratic time // is to use a HashSet with an appropriate comparer. Unfortunately, this approach // does not apply (at least, not straightforwardly), because CanUnifyWith is not // transitive and, thus, is not an equivalence relation. NamedTypeSymbol[] interfaces = this.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.Keys.ToArray(); for (int i1 = 0; i1 < numInterfaces; i1++) { for (int i2 = i1 + 1; i2 < numInterfaces; i2++) { NamedTypeSymbol interface1 = interfaces[i1]; NamedTypeSymbol interface2 = interfaces[i2]; // CanUnifyWith is the real check - the others just short-circuit if (interface1.IsGenericType && interface2.IsGenericType && TypeSymbol.Equals(interface1.OriginalDefinition, interface2.OriginalDefinition, TypeCompareKind.ConsiderEverything2) && interface1.CanUnifyWith(interface2)) { if (GetImplementsLocationOrFallback(interface1).SourceSpan.Start > GetImplementsLocationOrFallback(interface2).SourceSpan.Start) { // Mention interfaces in order of their appearance in the base list, for consistency. var temp = interface1; interface1 = interface2; interface2 = temp; } diagnostics.Add(ErrorCode.ERR_UnifyingInterfaceInstantiations, this.Locations[0], this, interface1, interface2); } } } } /// <summary> /// Though there is a method that C# considers to be an implementation of the interface method, that /// method may not be considered an implementation by the CLR. In particular, implicit implementation /// methods that are non-virtual or that have different (usually fewer) custom modifiers than the /// interface method, will not be considered CLR overrides. To address this problem, we either make /// them virtual (in metadata, not in C#), or we introduce an explicit interface implementation that /// delegates to the implicit implementation. /// </summary> /// <param name="implementingMemberAndDiagnostics">Returned from FindImplementationForInterfaceMemberWithDiagnostics.</param> /// <param name="interfaceMember">The interface method or property that is being implemented.</param> /// <returns> /// A synthesized forwarding method for the implementation, or information about MethodImpl entry that should be emitted, /// or default if neither needed. /// </returns> private (SynthesizedExplicitImplementationForwardingMethod? ForwardingMethod, (MethodSymbol Body, MethodSymbol Implemented)? MethodImpl) SynthesizeInterfaceMemberImplementation(SymbolAndDiagnostics implementingMemberAndDiagnostics, Symbol interfaceMember) { foreach (Diagnostic diagnostic in implementingMemberAndDiagnostics.Diagnostics.Diagnostics) { if (diagnostic.Severity == DiagnosticSeverity.Error && diagnostic.Code is not (int)ErrorCode.ERR_ImplicitImplementationOfNonPublicInterfaceMember) { return default; } } Symbol implementingMember = implementingMemberAndDiagnostics.Symbol; //don't worry about properties or events - we'll catch them through their accessors if ((object)implementingMember == null || implementingMember.Kind != SymbolKind.Method) { return default; } MethodSymbol interfaceMethod = (MethodSymbol)interfaceMember; MethodSymbol implementingMethod = (MethodSymbol)implementingMember; //explicit implementations are always respected by the CLR if (implementingMethod.ExplicitInterfaceImplementations.Contains(interfaceMethod, ExplicitInterfaceImplementationTargetMemberEqualityComparer.Instance)) { return default; } if (!interfaceMethod.IsStatic) { MethodSymbol implementingMethodOriginalDefinition = implementingMethod.OriginalDefinition; bool needSynthesizedImplementation = true; // If the implementing method is from a source file in the same module and the // override is correct from the runtime's perspective (esp the custom modifiers // match), then we can just twiddle the metadata virtual bit. Otherwise, we need // to create an explicit implementation that delegates to the real implementation. if (MemberSignatureComparer.RuntimeImplicitImplementationComparer.Equals(implementingMethod, interfaceMethod) && IsOverrideOfPossibleImplementationUnderRuntimeRules(implementingMethod, @interfaceMethod.ContainingType)) { if (ReferenceEquals(this.ContainingModule, implementingMethodOriginalDefinition.ContainingModule)) { if (implementingMethodOriginalDefinition is SourceMemberMethodSymbol sourceImplementMethodOriginalDefinition) { sourceImplementMethodOriginalDefinition.EnsureMetadataVirtual(); needSynthesizedImplementation = false; } } else if (implementingMethod.IsMetadataVirtual(ignoreInterfaceImplementationChanges: true)) { // If the signatures match and the implementation method is definitely virtual, then we're set. needSynthesizedImplementation = false; } } if (!needSynthesizedImplementation) { return default; } } else { if (implementingMethod.ContainingType != (object)this) { if (implementingMethod.Equals(this.BaseTypeNoUseSiteDiagnostics?.FindImplementationForInterfaceMemberInNonInterfaceWithDiagnostics(interfaceMethod).Symbol, TypeCompareKind.CLRSignatureCompareOptions)) { return default; } } else if (MemberSignatureComparer.RuntimeExplicitImplementationSignatureComparer.Equals(implementingMethod, interfaceMethod)) { return (null, (implementingMethod, interfaceMethod)); } } return (new SynthesizedExplicitImplementationForwardingMethod(interfaceMethod, implementingMethod, this), null); } #nullable disable /// <summary> /// The CLR will only look for an implementation of an interface method in a type that /// 1) declares that it implements that interface; or /// 2) is a base class of a type that declares that it implements the interface but not /// a subtype of a class that declares that it implements the interface. /// /// For example, /// /// interface I /// class A /// class B : A, I /// class C : B /// class D : C, I /// /// Suppose the runtime is looking for D's implementation of a member of I. It will look in /// D because of (1), will not look in C, will look in B because of (1), and will look in A /// because of (2). /// /// The key point is that it does not look in C, which C# *does*. /// </summary> private static bool IsPossibleImplementationUnderRuntimeRules(MethodSymbol implementingMethod, NamedTypeSymbol @interface) { NamedTypeSymbol type = implementingMethod.ContainingType; if (type.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.ContainsKey(@interface)) { return true; } NamedTypeSymbol baseType = type.BaseTypeNoUseSiteDiagnostics; return (object)baseType == null || !baseType.AllInterfacesNoUseSiteDiagnostics.Contains(@interface); } /// <summary> /// If C# picks a different implementation than the CLR (see IsPossibleImplementationUnderClrRules), then we might /// still be okay, but dynamic dispatch might result in C#'s choice getting called anyway. /// </summary> /// <remarks> /// This is based on SymbolPreparer::IsCLRMethodImplSame in the native compiler. /// /// ACASEY: What the native compiler actually does is compute the C# answer, compute the CLR answer, /// and then confirm that they override the same method. What I've done here is check for the situations /// where the answers could disagree. I believe the results will be equivalent. If in doubt, a more conservative /// check would be implementingMethod.ContainingType.InterfacesAndTheirBaseInterfaces.Contains(@interface). /// </remarks> private static bool IsOverrideOfPossibleImplementationUnderRuntimeRules(MethodSymbol implementingMethod, NamedTypeSymbol @interface) { MethodSymbol curr = implementingMethod; while ((object)curr != null) { if (IsPossibleImplementationUnderRuntimeRules(curr, @interface)) { return true; } curr = curr.OverriddenMethod; } return false; } internal sealed override ImmutableArray<NamedTypeSymbol> GetInterfacesToEmit() { return CalculateInterfacesToEmit(); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/Core/Portable/SourceGeneration/Nodes/IIncrementalGeneratorOutputNode.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Text; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Internal representation of an incremental output /// </summary> internal interface IIncrementalGeneratorOutputNode { IncrementalGeneratorOutputKind Kind { get; } void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken); } /// <summary> /// Represents the various output kinds of an <see cref="IIncrementalGenerator"/>. /// </summary> /// <remarks> /// Can be passed as a bit field when creating a <see cref="GeneratorDriver"/> to selectively disable outputs. /// </remarks> [Flags] public enum IncrementalGeneratorOutputKind { /// <summary> /// Represents no output kinds. Can be used when creating a driver to indicate that no outputs should be disabled. /// </summary> None = 0, /// <summary> /// A regular source output, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// or <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValuesProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// </summary> Source = 0b1, /// <summary> /// A post-initialization output, which will be visible to later phases, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(Action{IncrementalGeneratorPostInitializationContext})"/> /// </summary> PostInit = 0b10, /// <summary> /// An Implementation only source output, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// or <see cref="IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput{TSource}(IncrementalValuesProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// </summary> Implementation = 0b100 } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Text; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Internal representation of an incremental output /// </summary> internal interface IIncrementalGeneratorOutputNode { IncrementalGeneratorOutputKind Kind { get; } void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken); } /// <summary> /// Represents the various output kinds of an <see cref="IIncrementalGenerator"/>. /// </summary> /// <remarks> /// Can be passed as a bit field when creating a <see cref="GeneratorDriver"/> to selectively disable outputs. /// </remarks> [Flags] public enum IncrementalGeneratorOutputKind { /// <summary> /// Represents no output kinds. Can be used when creating a driver to indicate that no outputs should be disabled. /// </summary> None = 0, /// <summary> /// A regular source output, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// or <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValuesProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// </summary> Source = 0b1, /// <summary> /// A post-initialization output, which will be visible to later phases, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(Action{IncrementalGeneratorPostInitializationContext})"/> /// </summary> PostInit = 0b10, /// <summary> /// An Implementation only source output, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// or <see cref="IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput{TSource}(IncrementalValuesProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// </summary> Implementation = 0b100 } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/EditorFeatures/Test2/FindReferences/FindReferencesTests.Literals.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInt32Literals1(host As TestHost) As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = [|$$0|]; var i = [|0|]; var i = [|00|]; var i = [|0x0|]; var i = [|0b0|]; var i = 1; var i = 0.0; } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document> class C dim i = [|0|] dim i = [|0|] dim i = [|&amp;H0|] dim i = 1 dim i = 0.0 end class </Document> </Project> </Workspace> Await TestStreamingFeature(test, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCharLiterals1(host As TestHost) As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = [|$$'c'|]; var i = [|'c'|]; var i = [|'\u0063'|]; var i = 99; // 'c' in decimal var i = "c"; var i = 'd'; } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document> class C dim i = [|"c"c|] dim i = [|"c"c|] dim i = 99 dim i = "d"c end class </Document> </Project> </Workspace> Await TestStreamingFeature(test, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestDoubleLiterals1(host As TestHost) As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = [|$$0.0|]; var i = [|0D|]; var i = 0; var i = 0F; var i = '\u0000'; var i = 00; var i = 0x0; var i = 0b0; var i = 1; var i = [|0.00|]; var i = [|0e0|]; } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document> class C dim i = [|0.0|] dim i = 0 dim i = [|0.00|] end class </Document> </Project> </Workspace> Await TestStreamingFeature(test, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestFloatLiterals1(host As TestHost) As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = [|$$0F|]; var i = 0D; var i = 0; var i = '\u0000'; var i = 00; var i = 0x0; var i = 0b0; var i = 1; var i = [|0.0f|]; var i = [|0.00f|]; var i = [|0e0f|]; } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document> class C dim i = [|0.0F|] dim i = 0 dim i = [|0.00F|] end class </Document> </Project> </Workspace> Await TestStreamingFeature(test, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestStringLiterals1(host As TestHost) As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = [|$$"goo"|]; var i = [|"goo"|]; var i = [|@"goo"|]; var i = "fo"; var i = "gooo"; var i = 'f'; var i = 00; var i = 0x0; var i = 0b0; var i = 1; var i = 0.0f; var i = 0.00f; var i = 0e0f; } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document> class C dim i = [|"goo"|] dim i = [|"goo"|] dim i = "fo" dim i = "gooo" end class </Document> </Project> </Workspace> Await TestStreamingFeature(test, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestStringLiterals2(host As TestHost) As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = [|$$"goo\nbar"|]; var i = @"goo bar"; var i = "goo\r\nbar"; } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document> class C dim i = "goo bar" dim i = "goobar" end class </Document> </Project> </Workspace> Await TestStreamingFeature(test, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestStringLiterals3(host As TestHost) As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = [|$$"goo\r\nbar"|]; var i = [|@"goo bar"|]; var i = "goo\nbar"; } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document> class C dim i = [|"goo bar"|] dim i = "goobar" end class </Document> </Project> </Workspace> Await TestStreamingFeature(test, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestDecimalLiterals1(host As TestHost) As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = $$1M; // Decimals not currently supported var i = 1M; } } </Document> </Project> </Workspace> Await TestStreamingFeature(test, host) End Function <WpfFact, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInt32LiteralsUsedInSourceGeneratedDocument() As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = [|$$0|]; } } </Document> <DocumentFromSourceGenerator> class D { void M() { var i = [|0|]; } } </DocumentFromSourceGenerator> </Project> </Workspace> Await TestStreamingFeature(test, TestHost.InProcess) ' TODO: support out of proc in tests: https://github.com/dotnet/roslyn/issues/50494 End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading.Tasks Imports Microsoft.CodeAnalysis.Remote.Testing Namespace Microsoft.CodeAnalysis.Editor.UnitTests.FindReferences Partial Public Class FindReferencesTests <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInt32Literals1(host As TestHost) As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = [|$$0|]; var i = [|0|]; var i = [|00|]; var i = [|0x0|]; var i = [|0b0|]; var i = 1; var i = 0.0; } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document> class C dim i = [|0|] dim i = [|0|] dim i = [|&amp;H0|] dim i = 1 dim i = 0.0 end class </Document> </Project> </Workspace> Await TestStreamingFeature(test, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestCharLiterals1(host As TestHost) As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = [|$$'c'|]; var i = [|'c'|]; var i = [|'\u0063'|]; var i = 99; // 'c' in decimal var i = "c"; var i = 'd'; } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document> class C dim i = [|"c"c|] dim i = [|"c"c|] dim i = 99 dim i = "d"c end class </Document> </Project> </Workspace> Await TestStreamingFeature(test, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestDoubleLiterals1(host As TestHost) As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = [|$$0.0|]; var i = [|0D|]; var i = 0; var i = 0F; var i = '\u0000'; var i = 00; var i = 0x0; var i = 0b0; var i = 1; var i = [|0.00|]; var i = [|0e0|]; } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document> class C dim i = [|0.0|] dim i = 0 dim i = [|0.00|] end class </Document> </Project> </Workspace> Await TestStreamingFeature(test, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestFloatLiterals1(host As TestHost) As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = [|$$0F|]; var i = 0D; var i = 0; var i = '\u0000'; var i = 00; var i = 0x0; var i = 0b0; var i = 1; var i = [|0.0f|]; var i = [|0.00f|]; var i = [|0e0f|]; } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document> class C dim i = [|0.0F|] dim i = 0 dim i = [|0.00F|] end class </Document> </Project> </Workspace> Await TestStreamingFeature(test, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestStringLiterals1(host As TestHost) As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = [|$$"goo"|]; var i = [|"goo"|]; var i = [|@"goo"|]; var i = "fo"; var i = "gooo"; var i = 'f'; var i = 00; var i = 0x0; var i = 0b0; var i = 1; var i = 0.0f; var i = 0.00f; var i = 0e0f; } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document> class C dim i = [|"goo"|] dim i = [|"goo"|] dim i = "fo" dim i = "gooo" end class </Document> </Project> </Workspace> Await TestStreamingFeature(test, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestStringLiterals2(host As TestHost) As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = [|$$"goo\nbar"|]; var i = @"goo bar"; var i = "goo\r\nbar"; } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document> class C dim i = "goo bar" dim i = "goobar" end class </Document> </Project> </Workspace> Await TestStreamingFeature(test, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestStringLiterals3(host As TestHost) As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = [|$$"goo\r\nbar"|]; var i = [|@"goo bar"|]; var i = "goo\nbar"; } } </Document> </Project> <Project Language="Visual Basic" CommonReferences="true"> <Document> class C dim i = [|"goo bar"|] dim i = "goobar" end class </Document> </Project> </Workspace> Await TestStreamingFeature(test, host) End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestDecimalLiterals1(host As TestHost) As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = $$1M; // Decimals not currently supported var i = 1M; } } </Document> </Project> </Workspace> Await TestStreamingFeature(test, host) End Function <WpfFact, CombinatorialData, Trait(Traits.Feature, Traits.Features.FindReferences)> Public Async Function TestInt32LiteralsUsedInSourceGeneratedDocument() As Task Dim test = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { var i = [|$$0|]; } } </Document> <DocumentFromSourceGenerator> class D { void M() { var i = [|0|]; } } </DocumentFromSourceGenerator> </Project> </Workspace> Await TestStreamingFeature(test, TestHost.InProcess) ' TODO: support out of proc in tests: https://github.com/dotnet/roslyn/issues/50494 End Function End Class End Namespace
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/VisualBasic/Portable/Binding/Binder_Invocation.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ' Binding of method/property invocation is implemented in this part. Partial Friend Class Binder Private Function CreateBoundMethodGroup( node As SyntaxNode, lookupResult As LookupResult, lookupOptionsUsed As LookupOptions, withDependencies As Boolean, receiver As BoundExpression, typeArgumentsOpt As BoundTypeArguments, qualKind As QualificationKind, Optional hasError As Boolean = False ) As BoundMethodGroup Dim pendingExtensionMethods As ExtensionMethodGroup = Nothing Debug.Assert(lookupResult.Kind = LookupResultKind.Good OrElse lookupResult.Kind = LookupResultKind.Inaccessible) ' Name lookup does not look for extension methods if it found a suitable ' instance method. So, if the first symbol we have is not a reduced extension ' method, we might need to look for extension methods later, on demand. Debug.Assert((lookupOptionsUsed And LookupOptions.EagerlyLookupExtensionMethods) = 0) If lookupResult.IsGood AndAlso Not lookupResult.Symbols(0).IsReducedExtensionMethod() Then pendingExtensionMethods = New ExtensionMethodGroup(Me, lookupOptionsUsed, withDependencies) End If Return New BoundMethodGroup( node, typeArgumentsOpt, lookupResult.Symbols.ToDowncastedImmutable(Of MethodSymbol), pendingExtensionMethods, lookupResult.Kind, receiver, qualKind, hasErrors:=hasError) End Function ''' <summary> ''' Returns if all the rules for a "Me.New" or "MyBase.New" constructor call are satisfied: ''' a) In instance constructor body ''' b) First statement of that constructor ''' c) "Me", "MyClass", or "MyBase" is the receiver. ''' </summary> Private Function IsConstructorCallAllowed(invocationExpression As InvocationExpressionSyntax, boundMemberGroup As BoundMethodOrPropertyGroup) As Boolean If Me.ContainingMember.Kind = SymbolKind.Method AndAlso DirectCast(Me.ContainingMember, MethodSymbol).MethodKind = MethodKind.Constructor Then ' (a) we are in an instance constructor body Dim node As VisualBasicSyntaxNode = invocationExpression.Parent If node Is Nothing OrElse (node.Kind <> SyntaxKind.CallStatement AndAlso node.Kind <> SyntaxKind.ExpressionStatement) Then Return False End If Dim nodeParent As VisualBasicSyntaxNode = node.Parent If nodeParent Is Nothing OrElse nodeParent.Kind <> SyntaxKind.ConstructorBlock Then Return False End If If DirectCast(nodeParent, ConstructorBlockSyntax).Statements(0) Is node Then ' (b) call statement we are binding is 'the first' statement of the constructor Dim receiver As BoundExpression = boundMemberGroup.ReceiverOpt If receiver IsNot Nothing AndAlso (receiver.Kind = BoundKind.MeReference OrElse receiver.Kind = BoundKind.MyBaseReference OrElse receiver.Kind = BoundKind.MyClassReference) Then ' (c) receiver is 'Me'/'MyClass'/'MyBase' Return True End If End If End If Return False End Function Friend Class ConstructorCallArgumentsBinder Inherits Binder Public Sub New(containingBinder As Binder) MyBase.New(containingBinder) End Sub Protected Overrides ReadOnly Property IsInsideChainedConstructorCallArguments As Boolean Get Return True End Get End Property End Class ''' <summary> ''' Bind a Me.New(...), MyBase.New (...), MyClass.New(...) constructor call. ''' (NOT a normal constructor call like New Type(...)). ''' </summary> Private Function BindDirectConstructorCall(node As InvocationExpressionSyntax, group As BoundMethodGroup, diagnostics As BindingDiagnosticBag) As BoundExpression Dim boundArguments As ImmutableArray(Of BoundExpression) = Nothing Dim argumentNames As ImmutableArray(Of String) = Nothing Dim argumentNamesLocations As ImmutableArray(Of Location) = Nothing Dim argumentList As ArgumentListSyntax = node.ArgumentList Debug.Assert(IsGroupOfConstructors(group)) ' Direct constructor call is only allowed if: (a) we are in an instance constructor body, ' and (b) call statement we are binding is 'the first' statement of the constructor, ' and (c) receiver is 'Me'/'MyClass'/'MyBase' If IsConstructorCallAllowed(node, group) Then ' Bind arguments with special binder that prevents use of Me. Dim argumentsBinder As Binder = New ConstructorCallArgumentsBinder(Me) argumentsBinder.BindArgumentsAndNames(argumentList, boundArguments, argumentNames, argumentNamesLocations, diagnostics) ' Bind constructor call, errors will be generated if needed Return BindInvocationExpression(node, node.Expression, ExtractTypeCharacter(node.Expression), group, boundArguments, argumentNames, diagnostics, allowConstructorCall:=True, callerInfoOpt:=group.Syntax) Else ' Error case -- constructor call in wrong location. ' Report error BC30282 about invalid constructor call ' For semantic model / IDE purposes, we still bind it even if in a location that wasn't allowed. If Not group.HasErrors Then ReportDiagnostic(diagnostics, group.Syntax, ERRID.ERR_InvalidConstructorCall) End If BindArgumentsAndNames(argumentList, boundArguments, argumentNames, argumentNamesLocations, diagnostics) ' Bind constructor call, ignore errors by putting into discarded bag. Dim expr = BindInvocationExpression(node, node.Expression, ExtractTypeCharacter(node.Expression), group, boundArguments, argumentNames, BindingDiagnosticBag.Discarded, allowConstructorCall:=True, callerInfoOpt:=group.Syntax) If expr.Kind = BoundKind.Call Then ' Set HasErrors to prevent cascading errors. Dim callExpr = DirectCast(expr, BoundCall) expr = New BoundCall( callExpr.Syntax, callExpr.Method, callExpr.MethodGroupOpt, callExpr.ReceiverOpt, callExpr.Arguments, callExpr.DefaultArguments, callExpr.ConstantValueOpt, isLValue:=False, suppressObjectClone:=False, type:=callExpr.Type, hasErrors:=True) End If Return expr End If End Function Private Function BindInvocationExpression(node As InvocationExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression ' Set "IsInvocationsOrAddressOf" to prevent binding to return value variable. Dim target As BoundExpression If node.Expression Is Nothing Then ' Must be conditional case Dim conditionalAccess As ConditionalAccessExpressionSyntax = node.GetCorrespondingConditionalAccessExpression() If conditionalAccess IsNot Nothing Then target = GetConditionalAccessReceiver(conditionalAccess) Else target = ReportDiagnosticAndProduceBadExpression(diagnostics, node, ERRID.ERR_Syntax).MakeCompilerGenerated() End If Else target = BindExpression(node.Expression, diagnostics:=diagnostics, isInvocationOrAddressOf:=True, isOperandOfConditionalBranch:=False, eventContext:=False) End If ' If 'target' is a bound constructor group, we need to do special checks and special processing of arguments. If target.Kind = BoundKind.MethodGroup Then Dim group = DirectCast(target, BoundMethodGroup) If IsGroupOfConstructors(group) Then Return BindDirectConstructorCall(node, group, diagnostics) End If End If Dim boundArguments As ImmutableArray(Of BoundExpression) = Nothing Dim argumentNames As ImmutableArray(Of String) = Nothing Dim argumentNamesLocations As ImmutableArray(Of Location) = Nothing Me.BindArgumentsAndNames(node.ArgumentList, boundArguments, argumentNames, argumentNamesLocations, diagnostics) If target.Kind = BoundKind.MethodGroup OrElse target.Kind = BoundKind.PropertyGroup Then Return BindInvocationExpressionPossiblyWithoutArguments( node, ExtractTypeCharacter(node.Expression), DirectCast(target, BoundMethodOrPropertyGroup), boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments:=True, diagnostics:=diagnostics) End If If target.Kind = BoundKind.NamespaceExpression Then Dim namespaceExp As BoundNamespaceExpression = DirectCast(target, BoundNamespaceExpression) Dim diagInfo = ErrorFactory.ErrorInfo(ERRID.ERR_NamespaceNotExpression1, namespaceExp.NamespaceSymbol) ReportDiagnostic(diagnostics, node.Expression, diagInfo) ElseIf target.Kind = BoundKind.TypeExpression Then Dim typeExp As BoundTypeExpression = DirectCast(target, BoundTypeExpression) If Not IsCallStatementContext(node) Then ' Try default instance property through DefaultInstanceAlias Dim instance As BoundExpression = TryDefaultInstanceProperty(typeExp, diagnostics) If instance IsNot Nothing Then Return BindIndexedInvocationExpression( node, instance, boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments:=False, hasIndexableTarget:=False, diagnostics:=diagnostics) End If End If Dim diagInfo = ErrorFactory.ErrorInfo(GetTypeNotExpressionErrorId(typeExp.Type), typeExp.Type) ReportDiagnostic(diagnostics, node.Expression, diagInfo) Else Return BindIndexedInvocationExpression( node, target, boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments:=True, hasIndexableTarget:=False, diagnostics:=diagnostics) End If Return GenerateBadExpression(node, target, boundArguments) End Function ''' <summary> ''' Bind an invocation expression representing an array access, ''' delegate invocation, or default member. ''' </summary> Private Function BindIndexedInvocationExpression( node As InvocationExpressionSyntax, target As BoundExpression, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), argumentNamesLocations As ImmutableArray(Of Location), allowBindingWithoutArguments As Boolean, <Out()> ByRef hasIndexableTarget As Boolean, diagnostics As BindingDiagnosticBag) As BoundExpression Debug.Assert(target.Kind <> BoundKind.NamespaceExpression) Debug.Assert(target.Kind <> BoundKind.TypeExpression) Debug.Assert(target.Kind <> BoundKind.MethodGroup) Debug.Assert(target.Kind <> BoundKind.PropertyGroup) hasIndexableTarget = False If Not target.IsLValue AndAlso target.Kind <> BoundKind.LateMemberAccess Then target = MakeRValue(target, diagnostics) End If Dim targetType As TypeSymbol = target.Type ' there are values or variables like "Nothing" which have no type If targetType IsNot Nothing Then ' this method is also called for e.g. Arrays because they are also InvocationExpressions ' if target is an array, then call BindArrayAccess only if target is not a direct successor ' of a call statement If targetType.IsArrayType Then hasIndexableTarget = True ' only bind to an array if this method was called outside of a call statement context If Not IsCallStatementContext(node) Then Return BindArrayAccess(node, target, boundArguments, argumentNames, diagnostics) End If ElseIf targetType.Kind = SymbolKind.NamedType AndAlso targetType.TypeKind = TypeKind.Delegate Then hasIndexableTarget = True ' an invocation of a delegate actually calls the delegate's Invoke method. Dim delegateInvoke = DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod If delegateInvoke Is Nothing Then If Not target.HasErrors Then ReportDiagnostic(diagnostics, target.Syntax, ERRID.ERR_DelegateNoInvoke1, target.Type) End If ElseIf ReportDelegateInvokeUseSite(diagnostics, target.Syntax, targetType, delegateInvoke) Then delegateInvoke = Nothing End If If delegateInvoke IsNot Nothing Then Dim methodGroup = New BoundMethodGroup( If(node.Expression, node), Nothing, ImmutableArray.Create(Of MethodSymbol)(delegateInvoke), LookupResultKind.Good, target, QualificationKind.QualifiedViaValue).MakeCompilerGenerated() Return BindInvocationExpression( node, If(node.Expression, node), ExtractTypeCharacter(node.Expression), methodGroup, boundArguments, argumentNames, diagnostics, callerInfoOpt:=node, representCandidateInDiagnosticsOpt:=targetType) Else Dim badExpressionChildren = ArrayBuilder(Of BoundExpression).GetInstance() badExpressionChildren.Add(target) badExpressionChildren.AddRange(boundArguments) Return BadExpression(node, badExpressionChildren.ToImmutableAndFree(), ErrorTypeSymbol.UnknownResultType) End If End If End If If target.Kind = BoundKind.BadExpression Then ' Error already reported for a bad expression, so don't report another error ElseIf Not IsCallStatementContext(node) Then ' If the invocation is outside of a call statement ' context, bind to the default property group if any. If target.Type.SpecialType = SpecialType.System_Object OrElse target.Type.SpecialType = SpecialType.System_Array Then hasIndexableTarget = True Return BindLateBoundInvocation(node, Nothing, target, boundArguments, argumentNames, diagnostics, suppressLateBindingResolutionDiagnostics:=(target.Kind = BoundKind.LateMemberAccess)) End If If Not target.HasErrors Then ' Bind to the default property group. Dim defaultPropertyGroup As BoundExpression = BindDefaultPropertyGroup(If(node.Expression, node), target, diagnostics) If defaultPropertyGroup IsNot Nothing Then Debug.Assert(defaultPropertyGroup.Kind = BoundKind.PropertyGroup OrElse defaultPropertyGroup.Kind = BoundKind.MethodGroup OrElse defaultPropertyGroup.HasErrors) hasIndexableTarget = True If defaultPropertyGroup.Kind = BoundKind.PropertyGroup OrElse defaultPropertyGroup.Kind = BoundKind.MethodGroup Then Return BindInvocationExpressionPossiblyWithoutArguments( node, TypeCharacter.None, DirectCast(defaultPropertyGroup, BoundMethodOrPropertyGroup), boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments, diagnostics) End If Else ReportNoDefaultProperty(target, diagnostics) End If End If ElseIf target.Kind = BoundKind.LateMemberAccess Then hasIndexableTarget = True Dim lateMember = DirectCast(target, BoundLateMemberAccess) Return BindLateBoundInvocation(node, Nothing, lateMember, boundArguments, argumentNames, diagnostics) ElseIf Not target.HasErrors Then ' "Expression is not a method." Dim diagInfo = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedProcedure) ReportDiagnostic(diagnostics, If(node.Expression, node), diagInfo) End If Return GenerateBadExpression(node, target, boundArguments) End Function Private Function BindInvocationExpressionPossiblyWithoutArguments( node As InvocationExpressionSyntax, typeChar As TypeCharacter, group As BoundMethodOrPropertyGroup, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), argumentNamesLocations As ImmutableArray(Of Location), allowBindingWithoutArguments As Boolean, diagnostics As BindingDiagnosticBag) As BoundExpression ' Spec §11.8 Invocation Expressions ' ... ' If the method group only contains one accessible method, including both instance and ' extension methods, and that method takes no arguments and is a function, then the method ' group is interpreted as an invocation expression with an empty argument list and the result ' is used as the target of an invocation expression with the provided argument list(s). If allowBindingWithoutArguments AndAlso boundArguments.Length > 0 AndAlso Not IsCallStatementContext(node) AndAlso ShouldBindWithoutArguments(node, group, diagnostics) Then Dim tmpDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics) Dim result As BoundExpression = Nothing Debug.Assert(node.Expression IsNot Nothing) ' NOTE: when binding without arguments, we pass node.Expression as the first parameter ' so that the new bound node references it instead of invocation expression Dim withoutArgs = BindInvocationExpression( node.Expression, node.Expression, typeChar, group, ImmutableArray(Of BoundExpression).Empty, Nothing, tmpDiagnostics, callerInfoOpt:=group.Syntax) If withoutArgs.Kind = BoundKind.Call OrElse withoutArgs.Kind = BoundKind.PropertyAccess Then ' We were able to bind the method group or property access without arguments, ' possibly with some diagnostic. diagnostics.AddRange(tmpDiagnostics) tmpDiagnostics.Clear() If withoutArgs.Kind = BoundKind.PropertyAccess Then Dim receiverOpt As BoundExpression = DirectCast(withoutArgs, BoundPropertyAccess).ReceiverOpt If receiverOpt?.Syntax Is withoutArgs.Syntax AndAlso Not receiverOpt.WasCompilerGenerated Then withoutArgs.MakeCompilerGenerated() End If withoutArgs = MakeRValue(withoutArgs, diagnostics) Else Dim receiverOpt As BoundExpression = DirectCast(withoutArgs, BoundCall).ReceiverOpt If receiverOpt?.Syntax Is withoutArgs.Syntax AndAlso Not receiverOpt.WasCompilerGenerated Then withoutArgs.MakeCompilerGenerated() End If End If If withoutArgs.Kind = BoundKind.BadExpression Then result = GenerateBadExpression(node, withoutArgs, boundArguments) Else Dim hasIndexableTarget = False ' Bind the invocation with arguments as an indexed invocation. Dim withArgs = BindIndexedInvocationExpression( node, withoutArgs, boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments:=False, hasIndexableTarget:=hasIndexableTarget, diagnostics:=tmpDiagnostics) If hasIndexableTarget Then diagnostics.AddRange(tmpDiagnostics) result = withArgs Else ' Report BC32016 if something wrong. ReportDiagnostic(diagnostics, node.Expression, ERRID.ERR_FunctionResultCannotBeIndexed1, withoutArgs.ExpressionSymbol) ' If result of binding with no args was not indexable after all, then instead ' of just producing a bad expression, bind the invocation expression normally, ' but without reporting any more diagnostics. This produces more accurate ' bound nodes for semantic model questions and may allow the type of the ' expression to be computed, thus leading to fewer errors later. result = BindInvocationExpression( node, node.Expression, typeChar, group, boundArguments, argumentNames, BindingDiagnosticBag.Discarded, callerInfoOpt:=group.Syntax) End If End If End If tmpDiagnostics.Free() If result IsNot Nothing Then Return result End If End If Return BindInvocationExpression( node, If(node.Expression, group.Syntax), typeChar, group, boundArguments, argumentNames, diagnostics, callerInfoOpt:=group.Syntax) End Function ''' <summary> ''' Returns a BoundPropertyGroup if the expression represents a valid ''' default property access. If there is a default property but the property ''' access is invalid, a BoundBadExpression is returned. If there is no ''' default property for the expression type, Nothing is returned. ''' ''' Note, that default Query Indexer may be a method, not a property. ''' </summary> Private Function BindDefaultPropertyGroup(node As VisualBasicSyntaxNode, target As BoundExpression, diagnostics As BindingDiagnosticBag) As BoundExpression Dim result = LookupResult.GetInstance() Dim defaultMemberGroup As BoundExpression = Nothing Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) MemberLookup.LookupDefaultProperty(result, target.Type, Me, useSiteInfo) ' We're not reporting any diagnostic if there are no symbols. Debug.Assert(result.HasSymbol OrElse Not result.HasDiagnostic) If result.HasSymbol Then defaultMemberGroup = BindSymbolAccess(node, result, LookupOptions.Default, target, Nothing, QualificationKind.QualifiedViaValue, diagnostics) Debug.Assert(defaultMemberGroup IsNot Nothing) Debug.Assert((defaultMemberGroup.Kind = BoundKind.BadExpression) OrElse (defaultMemberGroup.Kind = BoundKind.PropertyGroup)) Else ' All queryable sources have default indexer, which maps to an ElementAtOrDefault method or property on the source. Dim tempDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics) target = MakeRValue(target, tempDiagnostics) Dim controlVariableType As TypeSymbol = Nothing target = ConvertToQueryableType(target, tempDiagnostics, controlVariableType) If controlVariableType IsNot Nothing Then result.Clear() Const options As LookupOptions = LookupOptions.AllMethodsOfAnyArity ' overload resolution filters methods by arity. LookupMember(result, target.Type, StringConstants.ElementAtMethod, 0, options, useSiteInfo) If result.IsGood Then Dim kind As SymbolKind = result.Symbols(0).Kind If kind = SymbolKind.Method OrElse kind = SymbolKind.Property Then diagnostics.AddRange(tempDiagnostics) defaultMemberGroup = BindSymbolAccess(node, result, options, target, Nothing, QualificationKind.QualifiedViaValue, diagnostics) End If End If End If tempDiagnostics.Free() End If diagnostics.Add(node, useSiteInfo) result.Free() ' We don't want the default property GROUP to override the meaning of the item it's being ' accessed off of, so mark it as compiler generated. If defaultMemberGroup IsNot Nothing Then defaultMemberGroup.SetWasCompilerGenerated() End If Return defaultMemberGroup End Function ''' <summary> ''' Tests whether or not the method or property group should be bound without arguments. ''' In case of method group it may also update the group by filtering out all subs ''' </summary> Private Function ShouldBindWithoutArguments(node As VisualBasicSyntaxNode, ByRef group As BoundMethodOrPropertyGroup, diagnostics As BindingDiagnosticBag) As Boolean Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) Dim result = ShouldBindWithoutArguments(group, useSiteInfo) diagnostics.Add(node, useSiteInfo) Return result End Function Private Function ShouldBindWithoutArguments(ByRef group As BoundMethodOrPropertyGroup, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As Boolean If group.Kind = BoundKind.MethodGroup Then Dim newMethods As ArrayBuilder(Of MethodSymbol) = ArrayBuilder(Of MethodSymbol).GetInstance() ' check method group members Dim methodGroup = DirectCast(group, BoundMethodGroup) Debug.Assert(methodGroup.Methods.Length > 0) ' any sub should be removed from a group in case we try binding without arguments Dim shouldUpdateGroup As Boolean = False Dim atLeastOneFunction As Boolean = False ' Dev10 behavior: ' For instance methods - ' Check if all functions from the group (ignoring subs) ' have the same arity as specified in the call and 0 parameters. ' However, the part that handles arity check is rather inconsistent between methods ' overloaded within the same type and in derived type. Also, language spec doesn't mention ' any restrictions for arity. So, we will not try to duplicate Dev10 logic around arity ' because the logic is close to impossible to match and behavior change will not be a breaking ' change. ' In presence of extension methods the rules are more constrained- ' If group contains an extension method, it must be the only method in the group, ' it must have no parameters, must have no type parameters and must be a Function. ' Note, we should avoid requesting AdditionalExtensionMethods whenever possible because ' lookup of extension methods might be very expensive. Dim extensionMethod As MethodSymbol = Nothing For Each method In methodGroup.Methods If method.IsReducedExtensionMethod Then extensionMethod = method Exit For End If If (method.IsSub) Then If method.CanBeCalledWithNoParameters() Then ' If its a sub that could be called parameterlessly, it might hide the function. So it is included ' in the group for further processing in overload resolution (which will process possible hiding). ' If overload resolution does select the Sub, we'll get an error about return type not indexable. ' See Roslyn bug 14019 for example. newMethods.Add(method) Else ' ignore other subs entirely shouldUpdateGroup = True End If ElseIf method.ParameterCount > 0 Then ' any function with more than 0 parameters newMethods.Free() Return False Else newMethods.Add(method) atLeastOneFunction = True End If Next If extensionMethod Is Nothing Then Dim additionalExtensionMethods As ImmutableArray(Of MethodSymbol) = methodGroup.AdditionalExtensionMethods(useSiteInfo) If additionalExtensionMethods.Length > 0 Then Debug.Assert(methodGroup.Methods.Length > 0) ' We have at least one extension method in the group and it is not the only one method in the ' group. Cannot apply default property transformation. newMethods.Free() Return False End If Else newMethods.Free() Debug.Assert(extensionMethod IsNot Nothing) ' This method must have no parameters, must have no type parameters and must not be a Sub. Return methodGroup.Methods.Length = 1 AndAlso methodGroup.TypeArgumentsOpt Is Nothing AndAlso extensionMethod.ParameterCount = 0 AndAlso extensionMethod.Arity = 0 AndAlso Not extensionMethod.IsSub AndAlso methodGroup.AdditionalExtensionMethods(useSiteInfo).Length = 0 End If If Not atLeastOneFunction Then newMethods.Free() Return False End If If shouldUpdateGroup Then ' at least one sub was removed If newMethods.IsEmpty Then ' no functions left newMethods.Free() Return False End If ' there are some functions, update the group group = methodGroup.Update(methodGroup.TypeArgumentsOpt, newMethods.ToImmutable(), Nothing, methodGroup.ResultKind, methodGroup.ReceiverOpt, methodGroup.QualificationKind) End If newMethods.Free() Return True Else ' check property group members Dim propertyGroup = DirectCast(group, BoundPropertyGroup) Debug.Assert(propertyGroup.Properties.Length > 0) For Each prop In propertyGroup.Properties If (prop.ParameterCount > 0) Then Return False End If Next ' assuming property group was not empty Return True End If End Function Private Shared Function IsGroupOfConstructors(group As BoundMethodOrPropertyGroup) As Boolean If group.Kind = BoundKind.MethodGroup Then Dim methodGroup = DirectCast(group, BoundMethodGroup) Debug.Assert(methodGroup.Methods.Length > 0) Return methodGroup.Methods(0).MethodKind = MethodKind.Constructor End If Return False End Function Friend Function BindInvocationExpression( node As SyntaxNode, target As SyntaxNode, typeChar As TypeCharacter, group As BoundMethodOrPropertyGroup, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional allowConstructorCall As Boolean = False, Optional suppressAbstractCallDiagnostics As Boolean = False, Optional isDefaultMemberAccess As Boolean = False, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing, Optional forceExpandedForm As Boolean = False ) As BoundExpression Debug.Assert(group IsNot Nothing) Debug.Assert(allowConstructorCall OrElse Not IsGroupOfConstructors(group)) Debug.Assert(group.ResultKind = LookupResultKind.Good OrElse group.ResultKind = LookupResultKind.Inaccessible) ' It is possible to get here with method group with ResultKind = LookupResultKind.Inaccessible. ' When this happens, it is worth trying to do overload resolution on the "bad" set ' to report better errors. Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) Dim results As OverloadResolution.OverloadResolutionResult = OverloadResolution.MethodOrPropertyInvocationOverloadResolution(group, boundArguments, argumentNames, Me, callerInfoOpt, useSiteInfo, forceExpandedForm:=forceExpandedForm) If diagnostics.Add(node, useSiteInfo) Then If group.ResultKind <> LookupResultKind.Inaccessible Then ' Suppress additional diagnostics diagnostics = BindingDiagnosticBag.Discarded End If End If If Not results.BestResult.HasValue Then If results.ResolutionIsLateBound Then Debug.Assert(OptionStrict <> VisualBasic.OptionStrict.On) ' Did we have extension methods among candidates? If group.Kind = BoundKind.MethodGroup Then Dim haveAnExtensionMethod As Boolean = False Dim methodGroup = DirectCast(group, BoundMethodGroup) For Each method As MethodSymbol In methodGroup.Methods If method.ReducedFrom IsNot Nothing Then haveAnExtensionMethod = True Exit For End If Next If Not haveAnExtensionMethod Then useSiteInfo = New CompoundUseSiteInfo(Of AssemblySymbol)(useSiteInfo) haveAnExtensionMethod = Not methodGroup.AdditionalExtensionMethods(useSiteInfo).IsEmpty diagnostics.Add(node, useSiteInfo) End If If haveAnExtensionMethod Then ReportDiagnostic(diagnostics, GetLocationForOverloadResolutionDiagnostic(node, group), ERRID.ERR_ExtensionMethodCannotBeLateBound) Dim builder = ArrayBuilder(Of BoundExpression).GetInstance() builder.Add(group) If Not boundArguments.IsEmpty Then builder.AddRange(boundArguments) End If Return New BoundBadExpression(node, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, builder.ToImmutableAndFree(), ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If End If Return BindLateBoundInvocation(node, group, isDefaultMemberAccess, boundArguments, argumentNames, diagnostics) End If ' Create and report the diagnostic. If results.Candidates.Length = 0 Then results = OverloadResolution.MethodOrPropertyInvocationOverloadResolution(group, boundArguments, argumentNames, Me, includeEliminatedCandidates:=True, callerInfoOpt:=callerInfoOpt, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded, forceExpandedForm:=forceExpandedForm) End If Return ReportOverloadResolutionFailureAndProduceBoundNode(node, group, boundArguments, argumentNames, results, diagnostics, callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else Return CreateBoundCallOrPropertyAccess( node, target, typeChar, group, boundArguments, results.BestResult.Value, results.AsyncLambdaSubToFunctionMismatch, diagnostics, suppressAbstractCallDiagnostics) End If End Function Private Function CreateBoundCallOrPropertyAccess( node As SyntaxNode, target As SyntaxNode, typeChar As TypeCharacter, group As BoundMethodOrPropertyGroup, boundArguments As ImmutableArray(Of BoundExpression), bestResult As OverloadResolution.CandidateAnalysisResult, asyncLambdaSubToFunctionMismatch As ImmutableArray(Of BoundExpression), diagnostics As BindingDiagnosticBag, Optional suppressAbstractCallDiagnostics As Boolean = False ) As BoundExpression Dim candidate = bestResult.Candidate Dim methodOrProperty = candidate.UnderlyingSymbol Dim returnType = candidate.ReturnType If group.ResultKind = LookupResultKind.Inaccessible Then ReportDiagnostic(diagnostics, target, GetInaccessibleErrorInfo(bestResult.Candidate.UnderlyingSymbol)) Else Debug.Assert(group.ResultKind = LookupResultKind.Good) CheckMemberTypeAccessibility(diagnostics, node, methodOrProperty) End If If bestResult.TypeArgumentInferenceDiagnosticsOpt IsNot Nothing Then diagnostics.AddRange(bestResult.TypeArgumentInferenceDiagnosticsOpt) End If Dim argumentInfo As (Arguments As ImmutableArray(Of BoundExpression), DefaultArguments As BitVector) = PassArguments(node, bestResult, boundArguments, diagnostics) boundArguments = argumentInfo.Arguments Debug.Assert(Not boundArguments.IsDefault) Dim hasErrors As Boolean = False Dim receiver As BoundExpression = group.ReceiverOpt If group.ResultKind = LookupResultKind.Good Then hasErrors = CheckSharedSymbolAccess(target, methodOrProperty.IsShared, receiver, group.QualificationKind, diagnostics) ' give diagnostics if sharedness is wrong. End If ReportDiagnosticsIfObsoleteOrNotSupported(diagnostics, methodOrProperty, node) hasErrors = hasErrors Or group.HasErrors If Not returnType.IsErrorType() Then VerifyTypeCharacterConsistency(node, returnType, typeChar, diagnostics) End If Dim resolvedTypeOrValueReceiver As BoundExpression = Nothing If receiver IsNot Nothing AndAlso Not hasErrors Then receiver = AdjustReceiverTypeOrValue(receiver, receiver.Syntax, methodOrProperty.IsShared, diagnostics, resolvedTypeOrValueReceiver) End If If Not suppressAbstractCallDiagnostics AndAlso receiver IsNot Nothing AndAlso (receiver.IsMyBaseReference OrElse receiver.IsMyClassReference) Then If methodOrProperty.IsMustOverride Then ' Generate an error, but continue processing ReportDiagnostic(diagnostics, group.Syntax, If(receiver.IsMyBaseReference, ERRID.ERR_MyBaseAbstractCall1, ERRID.ERR_MyClassAbstractCall1), methodOrProperty) End If End If If Not asyncLambdaSubToFunctionMismatch.IsEmpty Then For Each lambda In asyncLambdaSubToFunctionMismatch Dim errorLocation As SyntaxNode = lambda.Syntax Dim lambdaNode = TryCast(errorLocation, LambdaExpressionSyntax) If lambdaNode IsNot Nothing Then errorLocation = lambdaNode.SubOrFunctionHeader End If ReportDiagnostic(diagnostics, errorLocation, ERRID.WRN_AsyncSubCouldBeFunction) Next End If If methodOrProperty.Kind = SymbolKind.Method Then Dim method = DirectCast(methodOrProperty, MethodSymbol) Dim reducedFrom = method.ReducedFrom Dim constantValue As ConstantValue = Nothing If reducedFrom Is Nothing Then If receiver IsNot Nothing AndAlso receiver.IsPropertyOrXmlPropertyAccess() Then receiver = MakeRValue(receiver, diagnostics) End If If method.IsUserDefinedOperator() AndAlso Me.ContainingMember Is method Then ReportDiagnostic(diagnostics, target, ERRID.WRN_RecursiveOperatorCall, method) End If ' replace call with literal if possible (Chr, ChrW, Asc, AscW) constantValue = OptimizeLibraryCall(method, boundArguments, node, hasErrors, diagnostics) Else ' We are calling an extension method, prepare the receiver to be ' passed as the first parameter. receiver = UpdateReceiverForExtensionMethodOrPropertyGroup(receiver, method.ReceiverType, reducedFrom.Parameters(0), diagnostics) End If ' Remove receiver from the method group ' NOTE: we only remove it if we pass it to a new BoundCall node, ' otherwise we keep it in the group to support semantic queries Dim methodGroup = DirectCast(group, BoundMethodGroup) Dim newReceiver As BoundExpression = If(receiver IsNot Nothing, Nothing, If(resolvedTypeOrValueReceiver, methodGroup.ReceiverOpt)) methodGroup = methodGroup.Update(methodGroup.TypeArgumentsOpt, methodGroup.Methods, methodGroup.PendingExtensionMethodsOpt, methodGroup.ResultKind, newReceiver, methodGroup.QualificationKind) Return New BoundCall( node, method, methodGroup, receiver, boundArguments, constantValue, returnType, suppressObjectClone:=False, hasErrors:=hasErrors, defaultArguments:=argumentInfo.DefaultArguments) Else Dim [property] = DirectCast(methodOrProperty, PropertySymbol) Dim reducedFrom = [property].ReducedFromDefinition Debug.Assert(Not boundArguments.Any(Function(a) a.Kind = BoundKind.ByRefArgumentWithCopyBack)) If reducedFrom Is Nothing Then If receiver IsNot Nothing AndAlso receiver.IsPropertyOrXmlPropertyAccess() Then receiver = MakeRValue(receiver, diagnostics) End If Else receiver = UpdateReceiverForExtensionMethodOrPropertyGroup(receiver, [property].ReceiverType, reducedFrom.Parameters(0), diagnostics) End If ' Remove receiver from the property group ' NOTE: we only remove it if we pass it to a new BoundPropertyAccess node, ' otherwise we keep it in the group to support semantic queries Dim propertyGroup = DirectCast(group, BoundPropertyGroup) Dim newReceiver As BoundExpression = If(receiver IsNot Nothing, Nothing, If(resolvedTypeOrValueReceiver, propertyGroup.ReceiverOpt)) propertyGroup = propertyGroup.Update(propertyGroup.Properties, propertyGroup.ResultKind, newReceiver, propertyGroup.QualificationKind) Return New BoundPropertyAccess( node, [property], propertyGroup, PropertyAccessKind.Unknown, [property].IsWritable(receiver, Me, isKnownTargetOfObjectMemberInitializer:=False), receiver, boundArguments, argumentInfo.DefaultArguments, hasErrors:=hasErrors) End If End Function Friend Sub WarnOnRecursiveAccess(propertyAccess As BoundPropertyAccess, accessKind As PropertyAccessKind, diagnostics As BindingDiagnosticBag) Dim [property] As PropertySymbol = propertyAccess.PropertySymbol If [property].ReducedFromDefinition Is Nothing AndAlso [property].ParameterCount = 0 AndAlso ([property].IsShared OrElse (propertyAccess.ReceiverOpt IsNot Nothing AndAlso propertyAccess.ReceiverOpt.Kind = BoundKind.MeReference)) Then Dim reportRecursiveCall As Boolean = False If [property].GetMethod Is ContainingMember Then If (accessKind And PropertyAccessKind.Get) <> 0 AndAlso (propertyAccess.AccessKind And PropertyAccessKind.Get) = 0 Then reportRecursiveCall = True End If ElseIf [property].SetMethod Is ContainingMember Then If (accessKind And PropertyAccessKind.Set) <> 0 AndAlso (propertyAccess.AccessKind And PropertyAccessKind.Set) = 0 Then reportRecursiveCall = True End If End If If reportRecursiveCall Then ReportDiagnostic(diagnostics, propertyAccess.Syntax, ERRID.WRN_RecursivePropertyCall, [property]) End If End If End Sub Friend Sub WarnOnRecursiveAccess(node As BoundExpression, accessKind As PropertyAccessKind, diagnostics As BindingDiagnosticBag) Select Case node.Kind Case BoundKind.XmlMemberAccess ' Nothing to do Case BoundKind.PropertyAccess WarnOnRecursiveAccess(DirectCast(node, BoundPropertyAccess), accessKind, diagnostics) Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Sub Private Function UpdateReceiverForExtensionMethodOrPropertyGroup( receiver As BoundExpression, targetType As TypeSymbol, thisParameterDefinition As ParameterSymbol, diagnostics As BindingDiagnosticBag ) As BoundExpression If receiver IsNot Nothing AndAlso receiver.IsValue AndAlso Not targetType.IsErrorType() AndAlso Not receiver.Type.IsErrorType() Then Dim oldReceiver As BoundExpression = receiver Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) receiver = PassArgument(receiver, Conversions.ClassifyConversion(receiver, targetType, Me, useSiteInfo), False, Conversions.ClassifyConversion(targetType, receiver.Type, useSiteInfo), targetType, thisParameterDefinition, diagnostics) diagnostics.Add(receiver, useSiteInfo) If oldReceiver.WasCompilerGenerated AndAlso receiver IsNot oldReceiver Then Select Case oldReceiver.Kind Case BoundKind.MeReference, BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder receiver.SetWasCompilerGenerated() End Select End If End If Return receiver End Function Private Function IsWellKnownTypeMember(memberId As WellKnownMember, method As MethodSymbol) As Boolean Return Compilation.GetWellKnownTypeMember(memberId) Is method End Function ''' <summary> ''' Optimizes some runtime library calls through replacing them with a literal if possible. ''' VB Spec 11.2 defines the following runtime functions as being constant: ''' - Microsoft.VisualBasic.Strings.ChrW ''' - Microsoft.VisualBasic.Strings.Chr, if the constant value is between 0 and 128 ''' - Microsoft.VisualBasic.Strings.AscW, if the constant string is not empty ''' - Microsoft.VisualBasic.Strings.Asc, if the constant string is not empty ''' </summary> ''' <param name="method">The method.</param> ''' <param name="arguments">The arguments of the method call.</param> ''' <param name="syntax">The syntax node for report errors.</param> ''' <param name="diagnostics">The diagnostics.</param> ''' <param name="hasErrors">Set to true if there are conversion errors (e.g. Asc("")). Otherwise it's not written to.</param> ''' <returns>The constant value that replaces this node, or nothing.</returns> Private Function OptimizeLibraryCall( method As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), syntax As SyntaxNode, ByRef hasErrors As Boolean, diagnostics As BindingDiagnosticBag ) As ConstantValue ' cheapest way to filter out methods that do not match If arguments.Length = 1 AndAlso arguments(0).IsConstant AndAlso Not arguments(0).ConstantValueOpt.IsBad Then ' only continue checking if containing type is Microsoft.VisualBasic.Strings If Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_Strings) IsNot method.ContainingType Then Return Nothing End If ' AscW(char) / AscW(String) ' all values can be optimized as a literal, except an empty string that produces a diagnostic If IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscWCharInt32, method) OrElse IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscWStringInt32, method) Then Dim argumentConstantValue = arguments(0).ConstantValueOpt Dim argumentValue As String If argumentConstantValue.IsNull Then argumentValue = String.Empty ElseIf argumentConstantValue.IsChar Then argumentValue = argumentConstantValue.CharValue Else Debug.Assert(argumentConstantValue.IsString()) argumentValue = argumentConstantValue.StringValue End If If argumentValue.IsEmpty() Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_CannotConvertValue2, argumentValue, method.ReturnType) hasErrors = True Return Nothing End If Return ConstantValue.Create(AscW(argumentValue)) End If ' ChrW ' for -32768 < value or value > 65535 we show a diagnostic If IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrWInt32Char, method) Then Dim argumentValue = arguments(0).ConstantValueOpt.Int32Value If argumentValue < -32768 OrElse argumentValue > 65535 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_CannotConvertValue2, argumentValue, method.ReturnType) hasErrors = True Return Nothing End If Return ConstantValue.Create(ChrW(argumentValue)) End If ' Asc(Char) / Asc(String) ' all values from 0 to 127 can be optimized to a literal. If IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscCharInt32, method) OrElse IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscStringInt32, method) Then Dim constantValue = arguments(0).ConstantValueOpt Dim argumentValue As String If constantValue.IsNull Then argumentValue = String.Empty ElseIf constantValue.IsChar Then argumentValue = constantValue.CharValue Else Debug.Assert(constantValue.IsString()) argumentValue = constantValue.StringValue End If If argumentValue.IsEmpty() Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_CannotConvertValue2, argumentValue, method.ReturnType) hasErrors = True Return Nothing End If ' we are only folding 7bit ASCII chars, so it's ok to use AscW here, although this is the Asc folding. Dim charValue = AscW(argumentValue) If charValue < 128 Then Return ConstantValue.Create(charValue) End If Return Nothing End If ' Chr ' values from 0 to 127 can be optimized as a literal ' for -32768 < value or value > 65535 we show a diagnostic If IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrInt32Char, method) Then Dim argumentValue = arguments(0).ConstantValueOpt.Int32Value If argumentValue >= 0 AndAlso argumentValue < 128 Then Return ConstantValue.Create(ChrW(argumentValue)) ElseIf argumentValue < -32768 OrElse argumentValue > 65535 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_CannotConvertValue2, argumentValue, method.ReturnType) hasErrors = True Return Nothing End If End If End If Return Nothing End Function Private Function ReportOverloadResolutionFailureAndProduceBoundNode( node As SyntaxNode, group As BoundMethodOrPropertyGroup, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), <[In]> ByRef results As OverloadResolution.OverloadResolutionResult, diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional overrideCommonReturnType As TypeSymbol = Nothing, Optional queryMode As Boolean = False, Optional boundTypeExpression As BoundTypeExpression = Nothing, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing, Optional diagnosticLocationOpt As Location = Nothing ) As BoundExpression Return ReportOverloadResolutionFailureAndProduceBoundNode( node, group.ResultKind, boundArguments, argumentNames, results, diagnostics, callerInfoOpt, group, overrideCommonReturnType, queryMode, boundTypeExpression, representCandidateInDiagnosticsOpt, diagnosticLocationOpt) End Function Private Function ReportOverloadResolutionFailureAndProduceBoundNode( node As SyntaxNode, lookupResult As LookupResultKind, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), <[In]> ByRef results As OverloadResolution.OverloadResolutionResult, diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional groupOpt As BoundMethodOrPropertyGroup = Nothing, Optional overrideCommonReturnType As TypeSymbol = Nothing, Optional queryMode As Boolean = False, Optional boundTypeExpression As BoundTypeExpression = Nothing, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing, Optional diagnosticLocationOpt As Location = Nothing ) As BoundExpression Dim bestCandidates = ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult).GetInstance() Dim bestSymbols = ImmutableArray(Of Symbol).Empty Dim commonReturnType As TypeSymbol = GetSetOfTheBestCandidates(results, bestCandidates, bestSymbols) If overrideCommonReturnType IsNot Nothing Then commonReturnType = overrideCommonReturnType End If Dim result As BoundExpression = ReportOverloadResolutionFailureAndProduceBoundNode( node, lookupResult, bestCandidates, bestSymbols, commonReturnType, boundArguments, argumentNames, diagnostics, callerInfoOpt, groupOpt, Nothing, queryMode, boundTypeExpression, representCandidateInDiagnosticsOpt, diagnosticLocationOpt) bestCandidates.Free() Return result End Function Private Function ReportOverloadResolutionFailureAndProduceBoundNode( node As SyntaxNode, group As BoundMethodOrPropertyGroup, bestCandidates As ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult), bestSymbols As ImmutableArray(Of Symbol), commonReturnType As TypeSymbol, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional delegateSymbol As Symbol = Nothing, Optional queryMode As Boolean = False, Optional boundTypeExpression As BoundTypeExpression = Nothing, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing ) As BoundExpression Return ReportOverloadResolutionFailureAndProduceBoundNode( node, group.ResultKind, bestCandidates, bestSymbols, commonReturnType, boundArguments, argumentNames, diagnostics, callerInfoOpt, group, delegateSymbol, queryMode, boundTypeExpression, representCandidateInDiagnosticsOpt) End Function Public Shared Function GetLocationForOverloadResolutionDiagnostic(node As SyntaxNode, Optional groupOpt As BoundMethodOrPropertyGroup = Nothing) As Location Dim result As SyntaxNode If groupOpt IsNot Nothing Then If node.SyntaxTree Is groupOpt.Syntax.SyntaxTree AndAlso node.Span.Contains(groupOpt.Syntax.Span) Then result = groupOpt.Syntax If result Is node AndAlso (groupOpt.ReceiverOpt Is Nothing OrElse groupOpt.ReceiverOpt.Syntax Is result) Then Return result.GetLocation() End If Else Return node.GetLocation() End If ElseIf node.IsKind(SyntaxKind.InvocationExpression) Then result = If(DirectCast(node, InvocationExpressionSyntax).Expression, node) Else Return node.GetLocation() End If Select Case result.Kind Case SyntaxKind.QualifiedName Return DirectCast(result, QualifiedNameSyntax).Right.GetLocation() Case SyntaxKind.SimpleMemberAccessExpression If result.Parent IsNot Nothing AndAlso result.Parent.IsKind(SyntaxKind.AddressOfExpression) Then Return result.GetLocation() End If Return DirectCast(result, MemberAccessExpressionSyntax).Name.GetLocation() Case SyntaxKind.XmlElementAccessExpression, SyntaxKind.XmlDescendantAccessExpression, SyntaxKind.XmlAttributeAccessExpression Return DirectCast(result, XmlMemberAccessExpressionSyntax).Name.GetLocation() Case SyntaxKind.HandlesClauseItem Return DirectCast(result, HandlesClauseItemSyntax).EventMember.GetLocation() End Select Return result.GetLocation() End Function Private Function ReportOverloadResolutionFailureAndProduceBoundNode( node As SyntaxNode, lookupResult As LookupResultKind, bestCandidates As ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult), bestSymbols As ImmutableArray(Of Symbol), commonReturnType As TypeSymbol, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional groupOpt As BoundMethodOrPropertyGroup = Nothing, Optional delegateSymbol As Symbol = Nothing, Optional queryMode As Boolean = False, Optional boundTypeExpression As BoundTypeExpression = Nothing, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing, Optional diagnosticLocationOpt As Location = Nothing ) As BoundExpression Debug.Assert(commonReturnType IsNot Nothing AndAlso bestSymbols.Length > 0 AndAlso bestCandidates.Count >= bestSymbols.Length) Debug.Assert(groupOpt Is Nothing OrElse lookupResult = groupOpt.ResultKind) Dim state = OverloadResolution.CandidateAnalysisResultState.Count If bestCandidates.Count > 0 Then state = bestCandidates(0).State End If If boundArguments.IsDefault Then boundArguments = ImmutableArray(Of BoundExpression).Empty End If Dim singleCandidateAnalysisResult As OverloadResolution.CandidateAnalysisResult = Nothing Dim singleCandidate As OverloadResolution.Candidate = Nothing Dim allowUnexpandedParamArrayForm As Boolean = False Dim allowExpandedParamArrayForm As Boolean = False ' Figure out if we should report single candidate errors If bestSymbols.Length = 1 AndAlso bestCandidates.Count < 3 Then singleCandidateAnalysisResult = bestCandidates(0) singleCandidate = singleCandidateAnalysisResult.Candidate allowExpandedParamArrayForm = singleCandidateAnalysisResult.IsExpandedParamArrayForm allowUnexpandedParamArrayForm = Not allowExpandedParamArrayForm If bestCandidates.Count > 1 Then If bestCandidates(1).IsExpandedParamArrayForm Then allowExpandedParamArrayForm = True Else allowUnexpandedParamArrayForm = True End If End If End If If lookupResult = LookupResultKind.Inaccessible Then If singleCandidate IsNot Nothing Then ReportDiagnostic(diagnostics, If(groupOpt IsNot Nothing, groupOpt.Syntax, node), GetInaccessibleErrorInfo(singleCandidate.UnderlyingSymbol)) Else If Not queryMode Then ReportDiagnostic(diagnostics, If(groupOpt IsNot Nothing, groupOpt.Syntax, node), ERRID.ERR_NoViableOverloadCandidates1, bestSymbols(0).Name) End If ' Do not report more errors. GoTo ProduceBoundNode End If Else Debug.Assert(lookupResult = LookupResultKind.Good) End If If diagnosticLocationOpt Is Nothing Then diagnosticLocationOpt = GetLocationForOverloadResolutionDiagnostic(node, groupOpt) End If ' Report diagnostic according to the state of candidates Select Case state Case VisualBasic.OverloadResolution.CandidateAnalysisResultState.HasUseSiteError, OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata If singleCandidate IsNot Nothing Then ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocationOpt, lookupResult, singleCandidateAnalysisResult, boundArguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, True, False, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else ReportOverloadResolutionFailureForASetOfCandidates(node, diagnosticLocationOpt, lookupResult, ERRID.ERR_BadOverloadCandidates2, bestCandidates, boundArguments, argumentNames, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt) End If Case VisualBasic.OverloadResolution.CandidateAnalysisResultState.Ambiguous Dim candidate As Symbol = bestSymbols(0).OriginalDefinition Dim container As Symbol = candidate.ContainingSymbol ReportDiagnostic(diagnostics, diagnosticLocationOpt, ERRID.ERR_MetadataMembersAmbiguous3, candidate.Name, container.GetKindText(), container) Case OverloadResolution.CandidateAnalysisResultState.BadGenericArity Debug.Assert(groupOpt IsNot Nothing AndAlso groupOpt.Kind = BoundKind.MethodGroup) Dim mg = DirectCast(groupOpt, BoundMethodGroup) If singleCandidate IsNot Nothing Then Dim typeArguments = If(mg.TypeArgumentsOpt IsNot Nothing, mg.TypeArgumentsOpt.Arguments, ImmutableArray(Of TypeSymbol).Empty) If typeArguments.IsDefault Then typeArguments = ImmutableArray(Of TypeSymbol).Empty End If Dim singleSymbol As Symbol = singleCandidate.UnderlyingSymbol Dim isExtension As Boolean = singleCandidate.IsExtensionMethod If singleCandidate.Arity < typeArguments.Length Then If isExtension Then ReportDiagnostic(diagnostics, mg.TypeArgumentsOpt.Syntax, If(singleCandidate.Arity = 0, ERRID.ERR_TypeOrMemberNotGeneric2, ERRID.ERR_TooManyGenericArguments2), singleSymbol, singleSymbol.ContainingType) Else ReportDiagnostic(diagnostics, mg.TypeArgumentsOpt.Syntax, If(singleCandidate.Arity = 0, ERRID.ERR_TypeOrMemberNotGeneric1, ERRID.ERR_TooManyGenericArguments1), singleSymbol) End If Else Debug.Assert(singleCandidate.Arity > typeArguments.Length) If isExtension Then ReportDiagnostic(diagnostics, mg.TypeArgumentsOpt.Syntax, ERRID.ERR_TooFewGenericArguments2, singleSymbol, singleSymbol.ContainingType) Else ReportDiagnostic(diagnostics, mg.TypeArgumentsOpt.Syntax, ERRID.ERR_TooFewGenericArguments1, singleSymbol) End If End If Else ReportDiagnostic(diagnostics, diagnosticLocationOpt, ERRID.ERR_NoTypeArgumentCountOverloadCand1, CustomSymbolDisplayFormatter.ShortErrorName(bestSymbols(0))) End If Case OverloadResolution.CandidateAnalysisResultState.ArgumentCountMismatch If node.Kind = SyntaxKind.IdentifierName AndAlso node.Parent IsNot Nothing AndAlso node.Parent.Kind = SyntaxKind.NamedFieldInitializer AndAlso groupOpt IsNot Nothing AndAlso groupOpt.Kind = BoundKind.PropertyGroup Then ' report special diagnostics for a failed overload resolution because all available properties ' require arguments in case this method was called while binding a object member initializer. ReportDiagnostic(diagnostics, diagnosticLocationOpt, If(singleCandidate IsNot Nothing, ERRID.ERR_ParameterizedPropertyInAggrInit1, ERRID.ERR_NoZeroCountArgumentInitCandidates1), CustomSymbolDisplayFormatter.ShortErrorName(bestSymbols(0))) Else If singleCandidate IsNot Nothing AndAlso (Not queryMode OrElse singleCandidate.ParameterCount <= boundArguments.Length) Then ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocationOpt, lookupResult, singleCandidateAnalysisResult, boundArguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, True, False, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else ReportDiagnostic(diagnostics, diagnosticLocationOpt, ERRID.ERR_NoArgumentCountOverloadCandidates1, CustomSymbolDisplayFormatter.ShortErrorName(bestSymbols(0))) End If End If Case OverloadResolution.CandidateAnalysisResultState.ArgumentMismatch, OverloadResolution.CandidateAnalysisResultState.GenericConstraintsViolated Dim haveBadArgument As Boolean = False For i As Integer = 0 To boundArguments.Length - 1 Step 1 Dim type = boundArguments(i).Type If boundArguments(i).HasErrors OrElse (type IsNot Nothing AndAlso type.IsErrorType()) Then haveBadArgument = True Exit For End If Next If Not haveBadArgument Then If singleCandidate IsNot Nothing Then ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocationOpt, lookupResult, singleCandidateAnalysisResult, boundArguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, True, False, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else ReportOverloadResolutionFailureForASetOfCandidates(node, diagnosticLocationOpt, lookupResult, If(delegateSymbol Is Nothing, ERRID.ERR_NoCallableOverloadCandidates2, ERRID.ERR_DelegateBindingFailure3), bestCandidates, boundArguments, argumentNames, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt) End If End If Case OverloadResolution.CandidateAnalysisResultState.TypeInferenceFailed If singleCandidate IsNot Nothing Then ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocationOpt, lookupResult, singleCandidateAnalysisResult, boundArguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, True, False, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else ReportOverloadResolutionFailureForASetOfCandidates(node, diagnosticLocationOpt, lookupResult, ERRID.ERR_NoCallableOverloadCandidates2, bestCandidates, boundArguments, argumentNames, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt) End If Case OverloadResolution.CandidateAnalysisResultState.Applicable ' it is only possible to get overloading failure with a single candidate ' if we have a paramarray with equally specific virtual signatures Debug.Assert(singleCandidate Is Nothing OrElse singleCandidate.ParameterCount <> 0 AndAlso singleCandidate.Parameters(singleCandidate.ParameterCount - 1).IsParamArray) If bestCandidates(0).RequiresNarrowingConversion Then ReportOverloadResolutionFailureForASetOfCandidates(node, diagnosticLocationOpt, lookupResult, If(delegateSymbol Is Nothing, ERRID.ERR_NoNonNarrowingOverloadCandidates2, ERRID.ERR_DelegateBindingFailure3), bestCandidates, boundArguments, argumentNames, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt) Else ReportUnspecificProcedures(diagnosticLocationOpt, bestSymbols, diagnostics, (delegateSymbol IsNot Nothing)) End If Case Else ' Unexpected Throw ExceptionUtilities.UnexpectedValue(state) End Select ProduceBoundNode: Dim childBoundNodes As ImmutableArray(Of BoundExpression) If boundArguments.IsEmpty AndAlso boundTypeExpression Is Nothing Then If groupOpt Is Nothing Then childBoundNodes = ImmutableArray(Of BoundExpression).Empty Else childBoundNodes = ImmutableArray.Create(Of BoundExpression)(groupOpt) End If Else Dim builder = ArrayBuilder(Of BoundExpression).GetInstance() If groupOpt IsNot Nothing Then builder.Add(groupOpt) End If If Not boundArguments.IsEmpty Then builder.AddRange(boundArguments) End If If boundTypeExpression IsNot Nothing Then builder.Add(boundTypeExpression) End If childBoundNodes = builder.ToImmutableAndFree() End If Dim resultKind = LookupResultKind.OverloadResolutionFailure If lookupResult < resultKind Then resultKind = lookupResult End If Return New BoundBadExpression(node, resultKind, bestSymbols, childBoundNodes, commonReturnType, hasErrors:=True) End Function ''' <summary> '''Figure out the set of best candidates in the following preference order: ''' 1) Applicable ''' 2) ArgumentMismatch, GenericConstraintsViolated ''' 3) TypeInferenceFailed ''' 4) ArgumentCountMismatch ''' 5) BadGenericArity ''' 6) Ambiguous ''' 7) HasUseSiteError ''' 8) HasUnsupportedMetadata ''' ''' Also return the set of unique symbols behind the set. ''' ''' Returns type symbol for the common type, if any. ''' Otherwise returns ErrorTypeSymbol.UnknownResultType. ''' </summary> Private Shared Function GetSetOfTheBestCandidates( ByRef results As OverloadResolution.OverloadResolutionResult, bestCandidates As ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult), ByRef bestSymbols As ImmutableArray(Of Symbol) ) As TypeSymbol Const Applicable = OverloadResolution.CandidateAnalysisResultState.Applicable Const ArgumentMismatch = OverloadResolution.CandidateAnalysisResultState.ArgumentMismatch Const GenericConstraintsViolated = OverloadResolution.CandidateAnalysisResultState.GenericConstraintsViolated Const TypeInferenceFailed = OverloadResolution.CandidateAnalysisResultState.TypeInferenceFailed Const ArgumentCountMismatch = OverloadResolution.CandidateAnalysisResultState.ArgumentCountMismatch Const BadGenericArity = OverloadResolution.CandidateAnalysisResultState.BadGenericArity Const Ambiguous = OverloadResolution.CandidateAnalysisResultState.Ambiguous Const HasUseSiteError = OverloadResolution.CandidateAnalysisResultState.HasUseSiteError Const HasUnsupportedMetadata = OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata Dim preference(OverloadResolution.CandidateAnalysisResultState.Count - 1) As Integer preference(Applicable) = 1 preference(ArgumentMismatch) = 2 preference(GenericConstraintsViolated) = 2 preference(TypeInferenceFailed) = 3 preference(ArgumentCountMismatch) = 4 preference(BadGenericArity) = 5 preference(Ambiguous) = 6 preference(HasUseSiteError) = 7 preference(HasUnsupportedMetadata) = 8 For Each candidate In results.Candidates Dim prefNew = preference(candidate.State) If prefNew <> 0 Then If bestCandidates.Count = 0 Then bestCandidates.Add(candidate) Else Dim prefOld = preference(bestCandidates(0).State) If prefNew = prefOld Then bestCandidates.Add(candidate) ElseIf prefNew < prefOld Then bestCandidates.Clear() bestCandidates.Add(candidate) End If End If End If Next ' Collect unique best symbols. Dim bestSymbolsBuilder = ArrayBuilder(Of Symbol).GetInstance(bestCandidates.Count) Dim commonReturnType As TypeSymbol = Nothing If bestCandidates.Count = 1 Then ' For multiple candidates we never pick common type that refers to method's type parameter ' because each method has distinct type parameters. For single candidate case we need to ' ensure this explicitly. Dim underlyingSymbol As Symbol = bestCandidates(0).Candidate.UnderlyingSymbol bestSymbolsBuilder.Add(underlyingSymbol) commonReturnType = bestCandidates(0).Candidate.ReturnType If underlyingSymbol.Kind = SymbolKind.Method Then Dim method = DirectCast(underlyingSymbol, MethodSymbol) If method.IsGenericMethod AndAlso commonReturnType.ReferencesMethodsTypeParameter(method) Then Select Case CInt(bestCandidates(0).State) Case TypeInferenceFailed, HasUseSiteError, HasUnsupportedMetadata, BadGenericArity, ArgumentCountMismatch commonReturnType = Nothing End Select End If End If Else For i As Integer = 0 To bestCandidates.Count - 1 Step 1 If i = 0 OrElse Not bestSymbolsBuilder(bestSymbolsBuilder.Count - 1).Equals(bestCandidates(i).Candidate.UnderlyingSymbol) Then bestSymbolsBuilder.Add(bestCandidates(i).Candidate.UnderlyingSymbol) Dim returnType = bestCandidates(i).Candidate.ReturnType If commonReturnType Is Nothing Then commonReturnType = returnType ElseIf commonReturnType IsNot ErrorTypeSymbol.UnknownResultType AndAlso Not commonReturnType.IsSameTypeIgnoringAll(returnType) Then commonReturnType = ErrorTypeSymbol.UnknownResultType End If End If Next End If bestSymbols = bestSymbolsBuilder.ToImmutableAndFree() Return If(commonReturnType, ErrorTypeSymbol.UnknownResultType) End Function Private Shared Sub ReportUnspecificProcedures( diagnosticLocation As Location, bestSymbols As ImmutableArray(Of Symbol), diagnostics As BindingDiagnosticBag, isDelegateContext As Boolean ) Dim diagnosticInfos = ArrayBuilder(Of DiagnosticInfo).GetInstance(bestSymbols.Length) Dim notMostSpecificMessage = ErrorFactory.ErrorInfo(ERRID.ERR_NotMostSpecificOverload) Dim withContainingTypeInDiagnostics As Boolean = False If Not bestSymbols(0).IsReducedExtensionMethod Then Dim container As NamedTypeSymbol = bestSymbols(0).ContainingType For i As Integer = 1 To bestSymbols.Length - 1 Step 1 If Not TypeSymbol.Equals(bestSymbols(i).ContainingType, container, TypeCompareKind.ConsiderEverything) Then withContainingTypeInDiagnostics = True End If Next End If For i As Integer = 0 To bestSymbols.Length - 1 Step 1 ' in delegate context we just output for each candidates ' BC30794: No accessible 'goo' is most specific: ' Public Sub goo(p As Integer) ' Public Sub goo(p As Integer) ' ' in other contexts we give more information, e.g. ' BC30794: No accessible 'goo' is most specific: ' Public Sub goo(p As Integer): <reason> ' Public Sub goo(p As Integer): <reason> Dim bestSymbol As Symbol = bestSymbols(i) Dim bestSymbolIsExtension As Boolean = bestSymbol.IsReducedExtensionMethod If isDelegateContext Then If bestSymbolIsExtension Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOverloadCandidate2, bestSymbol, bestSymbol.ContainingType)) ElseIf withContainingTypeInDiagnostics Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate1, CustomSymbolDisplayFormatter.WithContainingType(bestSymbol))) Else diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate1, bestSymbol)) End If Else If bestSymbolIsExtension Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOverloadCandidate3, bestSymbol, bestSymbol.ContainingType, notMostSpecificMessage)) ElseIf withContainingTypeInDiagnostics Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate2, CustomSymbolDisplayFormatter.WithContainingType(bestSymbol), notMostSpecificMessage)) Else diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate2, bestSymbol, notMostSpecificMessage)) End If End If Next ReportDiagnostic(diagnostics, diagnosticLocation, ErrorFactory.ErrorInfo(If(isDelegateContext, ERRID.ERR_AmbiguousDelegateBinding2, ERRID.ERR_NoMostSpecificOverload2), CustomSymbolDisplayFormatter.ShortErrorName(bestSymbols(0)), New CompoundDiagnosticInfo(diagnosticInfos.ToArrayAndFree()) )) End Sub Private Sub ReportOverloadResolutionFailureForASetOfCandidates( node As SyntaxNode, diagnosticLocation As Location, lookupResult As LookupResultKind, errorNo As ERRID, candidates As ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult), arguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As BindingDiagnosticBag, delegateSymbol As Symbol, queryMode As Boolean, callerInfoOpt As SyntaxNode ) Dim diagnosticPerSymbol = ArrayBuilder(Of KeyValuePair(Of Symbol, ImmutableBindingDiagnostic(Of AssemblySymbol))).GetInstance(candidates.Count) If arguments.IsDefault Then arguments = ImmutableArray(Of BoundExpression).Empty End If For i As Integer = 0 To candidates.Count - 1 Step 1 ' See if we need to consider both expanded and unexpanded version of the same method. ' We want to report only one set of errors in this case. ' Note, that, when OverloadResolution collects candidates expanded form always ' immediately follows unexpanded form, if both should be considered. Dim allowExpandedParamArrayForm As Boolean = candidates(i).IsExpandedParamArrayForm Dim allowUnexpandedParamArrayForm As Boolean = Not allowExpandedParamArrayForm If allowUnexpandedParamArrayForm AndAlso i + 1 < candidates.Count AndAlso candidates(i + 1).IsExpandedParamArrayForm AndAlso candidates(i + 1).Candidate.UnderlyingSymbol.Equals(candidates(i).Candidate.UnderlyingSymbol) Then allowExpandedParamArrayForm = True i += 1 End If Dim candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics) ' Collect diagnostic for this candidate ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocation, lookupResult, candidates(i), arguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, False, errorNo = If(delegateSymbol Is Nothing, ERRID.ERR_NoNonNarrowingOverloadCandidates2, ERRID.ERR_DelegateBindingFailure3), candidateDiagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=Nothing) diagnosticPerSymbol.Add(KeyValuePairUtil.Create(candidates(i).Candidate.UnderlyingSymbol, candidateDiagnostics.ToReadOnlyAndFree())) Next ' See if there are errors that are reported for each candidate at the same location within a lambda argument. ' Report them and don't report remaining diagnostics for each symbol separately. If Not ReportCommonErrorsFromLambdas(diagnosticPerSymbol, arguments, diagnostics) Then Dim diagnosticInfos = ArrayBuilder(Of DiagnosticInfo).GetInstance(candidates.Count) For i As Integer = 0 To diagnosticPerSymbol.Count - 1 Dim symbol = diagnosticPerSymbol(i).Key Dim isExtension As Boolean = symbol.IsReducedExtensionMethod() Dim sealedCandidateDiagnostics = diagnosticPerSymbol(i).Value.Diagnostics ' When reporting errors for an AddressOf, Dev 10 shows different error messages depending on how many ' errors there are per candidate. ' One narrowing error will be shown like: ' 'Public Sub goo6(p As Integer, p2 As Byte)': Option Strict On disallows implicit conversions from 'Integer' to 'Byte'. ' More than one narrowing issues in the parameters are abbreviated with: ' 'Public Sub goo6(p As Byte, p2 As Byte)': Method does not have a signature compatible with the delegate. If delegateSymbol Is Nothing OrElse Not sealedCandidateDiagnostics.Skip(1).Any() Then If isExtension Then For Each iDiagnostic In sealedCandidateDiagnostics diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOverloadCandidate3, symbol, symbol.ContainingType, DirectCast(iDiagnostic, DiagnosticWithInfo).Info)) Next Else For Each iDiagnostic In sealedCandidateDiagnostics Dim msg = VisualBasicDiagnosticFormatter.Instance.Format(iDiagnostic.WithLocation(Location.None)) diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate2, symbol, DirectCast(iDiagnostic, DiagnosticWithInfo).Info)) Next End If Else If isExtension Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOverloadCandidate3, symbol, symbol.ContainingType, ErrorFactory.ErrorInfo(ERRID.ERR_DelegateBindingMismatch, symbol))) Else diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate2, symbol, ErrorFactory.ErrorInfo(ERRID.ERR_DelegateBindingMismatch, symbol))) End If End If Next Dim diagnosticCompoundInfos() As DiagnosticInfo = diagnosticInfos.ToArrayAndFree() If delegateSymbol Is Nothing Then ReportDiagnostic(diagnostics, diagnosticLocation, ErrorFactory.ErrorInfo(errorNo, CustomSymbolDisplayFormatter.ShortErrorName(candidates(0).Candidate.UnderlyingSymbol), New CompoundDiagnosticInfo(diagnosticCompoundInfos))) Else ReportDiagnostic(diagnostics, diagnosticLocation, ErrorFactory.ErrorInfo(errorNo, CustomSymbolDisplayFormatter.ShortErrorName(candidates(0).Candidate.UnderlyingSymbol), CustomSymbolDisplayFormatter.DelegateSignature(delegateSymbol), New CompoundDiagnosticInfo(diagnosticCompoundInfos))) End If End If diagnosticPerSymbol.Free() End Sub Private Shared Function ReportCommonErrorsFromLambdas( diagnosticPerSymbol As ArrayBuilder(Of KeyValuePair(Of Symbol, ImmutableBindingDiagnostic(Of AssemblySymbol))), arguments As ImmutableArray(Of BoundExpression), diagnostics As BindingDiagnosticBag ) As Boolean Dim haveCommonErrors As Boolean = False For Each diagnostic In diagnosticPerSymbol(0).Value.Diagnostics If diagnostic.Severity <> DiagnosticSeverity.Error Then Continue For End If For Each argument In arguments If argument.Syntax.SyntaxTree Is diagnostic.Location.SourceTree AndAlso argument.Kind = BoundKind.UnboundLambda Then If argument.Syntax.Span.Contains(diagnostic.Location.SourceSpan) Then Dim common As Boolean = True For i As Integer = 1 To diagnosticPerSymbol.Count - 1 If Not diagnosticPerSymbol(i).Value.Diagnostics.Contains(diagnostic) Then common = False Exit For End If Next If common Then haveCommonErrors = True diagnostics.Add(diagnostic) End If Exit For End If End If Next Next Return haveCommonErrors End Function ''' <summary> ''' Should be kept in sync with OverloadResolution.MatchArguments. Anything that ''' OverloadResolution.MatchArguments flags as an error should be detected by ''' this function as well. ''' </summary> Private Sub ReportOverloadResolutionFailureForASingleCandidate( node As SyntaxNode, diagnosticLocation As Location, lookupResult As LookupResultKind, ByRef candidateAnalysisResult As OverloadResolution.CandidateAnalysisResult, arguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), allowUnexpandedParamArrayForm As Boolean, allowExpandedParamArrayForm As Boolean, includeMethodNameInErrorMessages As Boolean, reportNarrowingConversions As Boolean, diagnostics As BindingDiagnosticBag, delegateSymbol As Symbol, queryMode As Boolean, callerInfoOpt As SyntaxNode, representCandidateInDiagnosticsOpt As Symbol ) Dim candidate As OverloadResolution.Candidate = candidateAnalysisResult.Candidate If arguments.IsDefault Then arguments = ImmutableArray(Of BoundExpression).Empty End If Debug.Assert(argumentNames.IsDefaultOrEmpty OrElse (argumentNames.Length > 0 AndAlso argumentNames.Length = arguments.Length)) Debug.Assert(allowUnexpandedParamArrayForm OrElse allowExpandedParamArrayForm) If candidateAnalysisResult.State = VisualBasic.OverloadResolution.CandidateAnalysisResultState.HasUseSiteError OrElse candidateAnalysisResult.State = VisualBasic.OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata Then If lookupResult <> LookupResultKind.Inaccessible Then Debug.Assert(lookupResult = LookupResultKind.Good) ReportUseSite(diagnostics, diagnosticLocation, candidate.UnderlyingSymbol.GetUseSiteInfo()) End If Return End If ' To simplify following code If Not argumentNames.IsDefault AndAlso argumentNames.Length = 0 Then argumentNames = Nothing End If Dim parameterToArgumentMap As ArrayBuilder(Of Integer) = ArrayBuilder(Of Integer).GetInstance(candidate.ParameterCount, -1) Dim paramArrayItems As ArrayBuilder(Of Integer) = ArrayBuilder(Of Integer).GetInstance() Try '§11.8.2 Applicable Methods '1. First, match each positional argument in order to the list of method parameters. 'If there are more positional arguments than parameters and the last parameter is not a paramarray, the method is not applicable. 'Otherwise, the paramarray parameter is expanded with parameters of the paramarray element type to match the number of positional arguments. 'If a positional argument is omitted, the method is not applicable. ' !!! Not sure about the last sentence: "If a positional argument is omitted, the method is not applicable." ' !!! Dev10 allows omitting positional argument as long as the corresponding parameter is optional. Dim positionalArguments As Integer = 0 Dim paramIndex = 0 Dim someArgumentsBad As Boolean = False Dim someParamArrayArgumentsBad As Boolean = False Dim seenOutOfPositionNamedArgIndex As Integer = -1 Dim candidateSymbol As Symbol = candidate.UnderlyingSymbol Dim candidateIsExtension As Boolean = candidate.IsExtensionMethod For i As Integer = 0 To arguments.Length - 1 Step 1 ' A named argument which is used in-position counts as positional If Not argumentNames.IsDefault AndAlso argumentNames(i) IsNot Nothing Then If Not candidate.TryGetNamedParamIndex(argumentNames(i), paramIndex) Then Exit For End If If paramIndex <> i Then ' all remaining arguments must be named seenOutOfPositionNamedArgIndex = i Exit For End If If paramIndex = candidate.ParameterCount - 1 AndAlso candidate.Parameters(paramIndex).IsParamArray Then Exit For End If Debug.Assert(parameterToArgumentMap(paramIndex) = -1) End If If paramIndex = candidate.ParameterCount Then If Not someArgumentsBad Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, arguments(i).Syntax, ERRID.ERR_TooManyArgs) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, arguments(i).Syntax, ERRID.ERR_TooManyArgs2, candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, arguments(i).Syntax, ERRID.ERR_TooManyArgs1, If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True End If ElseIf paramIndex = candidate.ParameterCount - 1 AndAlso candidate.Parameters(paramIndex).IsParamArray Then ' Collect ParamArray arguments While i < arguments.Length If Not argumentNames.IsDefault AndAlso argumentNames(i) IsNot Nothing Then ' First named argument Continue For End If If arguments(i).Kind = BoundKind.OmittedArgument Then ReportDiagnostic(diagnostics, arguments(i).Syntax, ERRID.ERR_OmittedParamArrayArgument) someParamArrayArgumentsBad = True Else paramArrayItems.Add(i) End If positionalArguments += 1 i += 1 End While Exit For Else parameterToArgumentMap(paramIndex) = i paramIndex += 1 End If positionalArguments += 1 Next Dim skippedSomeArguments As Boolean = False '§11.8.2 Applicable Methods '2. Next, match each named argument to a parameter with the given name. 'If one of the named arguments fails to match, matches a paramarray parameter, 'or matches an argument already matched with another positional or named argument, 'the method is not applicable. For i As Integer = positionalArguments To arguments.Length - 1 Step 1 Debug.Assert(argumentNames(i) Is Nothing OrElse argumentNames(i).Length > 0) If argumentNames(i) Is Nothing Then ' Unnamed argument follows out-of-position named arguments If Not someArgumentsBad Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(seenOutOfPositionNamedArgIndex).Syntax), ERRID.ERR_BadNonTrailingNamedArgument, argumentNames(seenOutOfPositionNamedArgIndex)) End If Return End If If Not candidate.TryGetNamedParamIndex(argumentNames(i), paramIndex) Then ' ERRID_NamedParamNotFound1 ' ERRID_NamedParamNotFound2 If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedParamNotFound1, argumentNames(i)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedParamNotFound3, argumentNames(i), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedParamNotFound2, argumentNames(i), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True Continue For End If If paramIndex = candidate.ParameterCount - 1 AndAlso candidate.Parameters(paramIndex).IsParamArray Then ' ERRID_NamedParamArrayArgument ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedParamArrayArgument) someArgumentsBad = True Continue For End If If parameterToArgumentMap(paramIndex) <> -1 AndAlso arguments(parameterToArgumentMap(paramIndex)).Kind <> BoundKind.OmittedArgument Then ' ERRID_NamedArgUsedTwice1 ' ERRID_NamedArgUsedTwice2 ' ERRID_NamedArgUsedTwice3 If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgUsedTwice1, argumentNames(i)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgUsedTwice3, argumentNames(i), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgUsedTwice2, argumentNames(i), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True Continue For End If ' It is an error for a named argument to specify ' a value for an explicitly omitted positional argument. If paramIndex < positionalArguments Then 'ERRID_NamedArgAlsoOmitted1 'ERRID_NamedArgAlsoOmitted2 'ERRID_NamedArgAlsoOmitted3 If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgAlsoOmitted1, argumentNames(i)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgAlsoOmitted3, argumentNames(i), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgAlsoOmitted2, argumentNames(i), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True End If parameterToArgumentMap(paramIndex) = i Next ' Check whether type inference failed If candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt IsNot Nothing Then diagnostics.AddRange(candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt) End If If candidate.IsGeneric AndAlso candidateAnalysisResult.State = OverloadResolution.CandidateAnalysisResultState.TypeInferenceFailed Then ' Bug 122092: AddressOf doesn't want detailed info on which parameters could not be ' inferred, just report the general type inference failed message in this case. If delegateSymbol IsNot Nothing Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_DelegateBindingTypeInferenceFails) Return End If If Not candidateAnalysisResult.SomeInferenceFailed Then Dim reportedAnError As Boolean = False For i As Integer = 0 To candidate.Arity - 1 Step 1 If candidateAnalysisResult.NotInferredTypeArguments(i) Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_UnboundTypeParam1, candidate.TypeParameters(i)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_UnboundTypeParam3, candidate.TypeParameters(i), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_UnboundTypeParam2, candidate.TypeParameters(i), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If reportedAnError = True End If Next If reportedAnError Then Return End If End If Dim inferenceErrorReasons As InferenceErrorReasons = candidateAnalysisResult.InferenceErrorReasons If (inferenceErrorReasons And InferenceErrorReasons.Ambiguous) <> 0 Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitAmbiguous1, ERRID.ERR_TypeInferenceFailureAmbiguous1)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitAmbiguous3, ERRID.ERR_TypeInferenceFailureAmbiguous3), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitAmbiguous2, ERRID.ERR_TypeInferenceFailureAmbiguous2), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If ElseIf (inferenceErrorReasons And InferenceErrorReasons.NoBest) <> 0 Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitNoBest1, ERRID.ERR_TypeInferenceFailureNoBest1)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitNoBest3, ERRID.ERR_TypeInferenceFailureNoBest3), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitNoBest2, ERRID.ERR_TypeInferenceFailureNoBest2), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If Else If candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt IsNot Nothing AndAlso candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt.HasAnyResolvedErrors Then ' Already reported some errors, let's not report a general inference error Return End If If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicit1, ERRID.ERR_TypeInferenceFailure1)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicit3, ERRID.ERR_TypeInferenceFailure3), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicit2, ERRID.ERR_TypeInferenceFailure2), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If End If Return End If ' Check generic constraints for method type arguments. If candidateAnalysisResult.State = OverloadResolution.CandidateAnalysisResultState.GenericConstraintsViolated Then Debug.Assert(candidate.IsGeneric) Debug.Assert(candidate.UnderlyingSymbol.Kind = SymbolKind.Method) Dim method = DirectCast(candidate.UnderlyingSymbol, MethodSymbol) ' TODO: Dev10 uses the location of the type parameter or argument that ' violated the constraint, rather than the entire invocation expression. Dim succeeded = method.CheckConstraints(diagnosticLocation, diagnostics, template:=GetNewCompoundUseSiteInfo(diagnostics)) Debug.Assert(Not succeeded) Return End If If candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt IsNot Nothing AndAlso candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt.HasAnyErrors Then Return End If ' Traverse the parameters, converting corresponding arguments ' as appropriate. Dim argIndex As Integer Dim candidateIsAProperty As Boolean = (candidateSymbol.Kind = SymbolKind.Property) For paramIndex = 0 To candidate.ParameterCount - 1 Step 1 Dim param As ParameterSymbol = candidate.Parameters(paramIndex) Dim isByRef As Boolean = param.IsByRef Dim targetType As TypeSymbol = param.Type Dim argument As BoundExpression = Nothing If param.IsParamArray AndAlso paramIndex = candidate.ParameterCount - 1 Then If targetType.Kind <> SymbolKind.ArrayType Then If targetType.Kind <> SymbolKind.ErrorType Then ' ERRID_ParamArrayWrongType ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_ParamArrayWrongType) End If someArgumentsBad = True Continue For ElseIf someParamArrayArgumentsBad Then Continue For End If If paramArrayItems.Count = 1 Then Dim paramArrayArgument = arguments(paramArrayItems(0)) '§11.8.2 Applicable Methods 'If the conversion from the type of the argument expression to the paramarray type is narrowing, 'then the method is only applicable in its expanded form. Dim arrayConversion As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing If allowUnexpandedParamArrayForm AndAlso Not (Not paramArrayArgument.HasErrors AndAlso OverloadResolution.CanPassToParamArray(paramArrayArgument, targetType, arrayConversion, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) Then allowUnexpandedParamArrayForm = False End If '§11.8.2 Applicable Methods 'If the argument expression is the literal Nothing, then the method is only applicable in its unexpanded form If allowExpandedParamArrayForm AndAlso paramArrayArgument.IsNothingLiteral() Then allowExpandedParamArrayForm = False End If Else ' Unexpanded form is not applicable: there are either more than one value or no values. If Not allowExpandedParamArrayForm Then If paramArrayItems.Count = 0 Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument1, CustomSymbolDisplayFormatter.ShortErrorName(param)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument3, CustomSymbolDisplayFormatter.ShortErrorName(param), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument2, CustomSymbolDisplayFormatter.ShortErrorName(param), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If Else If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_TooManyArgs) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_TooManyArgs2, candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_TooManyArgs1, If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If End If someArgumentsBad = True Continue For End If allowUnexpandedParamArrayForm = False End If If allowUnexpandedParamArrayForm Then argument = arguments(paramArrayItems(0)) ReportByValConversionErrors(param, argument, targetType, reportNarrowingConversions, diagnostics) ElseIf allowExpandedParamArrayForm Then Dim arrayType = DirectCast(targetType, ArrayTypeSymbol) If Not arrayType.IsSZArray Then ' ERRID_ParamArrayWrongType ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_ParamArrayWrongType) someArgumentsBad = True Continue For End If Dim arrayElementType = arrayType.ElementType For i As Integer = 0 To paramArrayItems.Count - 1 Step 1 argument = arguments(paramArrayItems(i)) ReportByValConversionErrors(param, argument, arrayElementType, reportNarrowingConversions, diagnostics) Next Else Debug.Assert(paramArrayItems.Count = 1) Dim paramArrayArgument = arguments(paramArrayItems(0)) ReportDiagnostic(diagnostics, paramArrayArgument.Syntax, ERRID.ERR_ParamArrayArgumentMismatch) End If Continue For End If argIndex = parameterToArgumentMap(paramIndex) argument = If(argIndex = -1, Nothing, arguments(argIndex)) ' Argument nothing when the argument syntax is missing or BoundKind.OmittedArgument when the argument list contains commas ' for the missing syntax so we have to test for both. If argument Is Nothing OrElse argument.Kind = BoundKind.OmittedArgument Then If argument Is Nothing AndAlso skippedSomeArguments Then someArgumentsBad = True Continue For End If 'See Section 3 of §11.8.2 Applicable Methods ' Deal with Optional arguments ' Need to handle optional arguments here, there could be conversion errors, etc. ' reducedExtensionReceiverOpt is used to determine the default value of a CallerArgumentExpression when it refers to the first parameter of an extension method. ' Don't bother with correctly determining the correct value for this case since we're in an error case anyway. argument = GetArgumentForParameterDefaultValue(param, node, diagnostics, callerInfoOpt, parameterToArgumentMap, arguments, reducedExtensionReceiverOpt:=Nothing) If argument Is Nothing Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument1, CustomSymbolDisplayFormatter.ShortErrorName(param)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument3, CustomSymbolDisplayFormatter.ShortErrorName(param), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument2, CustomSymbolDisplayFormatter.ShortErrorName(param), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True Continue For End If End If Debug.Assert(Not isByRef OrElse param.IsExplicitByRef OrElse targetType.IsStringType()) ' Arguments for properties are always passed with ByVal semantics. Even if ' parameter in metadata is defined ByRef, we always pass corresponding argument ' through a temp without copy-back. Unlike with method calls, we rely on CodeGen ' to introduce the temp (easy to do since there is no copy-back around it), ' this allows us to keep the BoundPropertyAccess node simpler and allows to avoid ' A LOT of complexity in UseTwiceRewriter, which we would otherwise have around ' the temps. ' Non-string arguments for implicitly ByRef string parameters of Declare functions ' are passed through a temp without copy-back. If isByRef AndAlso Not candidateIsAProperty AndAlso (param.IsExplicitByRef OrElse (argument.Type IsNot Nothing AndAlso argument.Type.IsStringType())) Then ReportByRefConversionErrors(candidate, param, argument, targetType, reportNarrowingConversions, diagnostics, diagnosticNode:=node, delegateSymbol:=delegateSymbol) Else ReportByValConversionErrors(param, argument, targetType, reportNarrowingConversions, diagnostics, diagnosticNode:=node, delegateSymbol:=delegateSymbol) End If Next Finally paramArrayItems.Free() parameterToArgumentMap.Free() End Try End Sub ''' <summary> ''' Should be in sync with OverloadResolution.MatchArgumentToByRefParameter ''' </summary> Private Sub ReportByRefConversionErrors( candidate As OverloadResolution.Candidate, param As ParameterSymbol, argument As BoundExpression, targetType As TypeSymbol, reportNarrowingConversions As Boolean, diagnostics As BindingDiagnosticBag, Optional diagnosticNode As SyntaxNode = Nothing, Optional delegateSymbol As Symbol = Nothing ) ' TODO: Do we need to do more thorough check for error types here, i.e. dig into generics, ' arrays, etc., detect types from unreferenced assemblies, ... ? If targetType.IsErrorType() OrElse argument.HasErrors Then ' UNDONE: should HasErrors really always cause argument mismatch [petergo, 3/9/2011] Return End If If argument.IsSupportingAssignment() Then If Not (argument.IsLValue() AndAlso targetType.IsSameTypeIgnoringAll(argument.Type)) Then If Not ReportByValConversionErrors(param, argument, targetType, reportNarrowingConversions, diagnostics, diagnosticNode:=diagnosticNode, delegateSymbol:=delegateSymbol) Then ' Check copy back conversion Dim boundTemp = New BoundRValuePlaceholder(argument.Syntax, targetType) Dim copyBackType = argument.GetTypeOfAssignmentTarget() Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(boundTemp, copyBackType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If Conversions.NoConversion(conv.Key) Then ' Possible only with user-defined conversions, I think. CreateConversionAndReportDiagnostic(argument.Syntax, boundTemp, conv, False, copyBackType, diagnostics, copybackConversionParamName:=param.Name) ElseIf Conversions.IsNarrowingConversion(conv.Key) Then Debug.Assert((conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0) If OptionStrict = VisualBasic.OptionStrict.On Then CreateConversionAndReportDiagnostic(argument.Syntax, boundTemp, conv, False, copyBackType, diagnostics, copybackConversionParamName:=param.Name) ElseIf reportNarrowingConversions Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_ArgumentCopyBackNarrowing3, CustomSymbolDisplayFormatter.ShortErrorName(param), targetType, copyBackType) End If End If End If End If Else ' No copy back needed ' If we are inside a lambda in a constructor and are passing ByRef a non-LValue field, which ' would be an LValue field, if it were referred to in the constructor outside of a lambda, ' we need to report an error because the operation will result in a simulated pass by ' ref (through a temp, without a copy back), which might be not the intent. If Report_ERRID_ReadOnlyInClosure(argument) Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_ReadOnlyInClosure) End If ReportByValConversionErrors(param, argument, targetType, reportNarrowingConversions, diagnostics, diagnosticNode:=diagnosticNode, delegateSymbol:=delegateSymbol) End If End Sub ''' <summary> ''' Should be in sync with OverloadResolution.MatchArgumentToByValParameter. ''' </summary> Private Function ReportByValConversionErrors( param As ParameterSymbol, argument As BoundExpression, targetType As TypeSymbol, reportNarrowingConversions As Boolean, diagnostics As BindingDiagnosticBag, Optional diagnosticNode As SyntaxNode = Nothing, Optional delegateSymbol As Symbol = Nothing ) As Boolean ' TODO: Do we need to do more thorough check for error types here, i.e. dig into generics, ' arrays, etc., detect types from unreferenced assemblies, ... ? If targetType.IsErrorType() OrElse argument.HasErrors Then ' UNDONE: should HasErrors really always cause argument mismatch [petergo, 3/9/2011] Return True End If Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(argument, targetType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If Conversions.NoConversion(conv.Key) Then If delegateSymbol Is Nothing Then CreateConversionAndReportDiagnostic(argument.Syntax, argument, conv, False, targetType, diagnostics) Else ' in case of delegates, use the operand of the AddressOf as location for this error CreateConversionAndReportDiagnostic(diagnosticNode, argument, conv, False, targetType, diagnostics) End If Return True End If Dim requiresNarrowingConversion As Boolean = False If Conversions.IsNarrowingConversion(conv.Key) Then If (conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0 Then If OptionStrict = VisualBasic.OptionStrict.On Then If delegateSymbol Is Nothing Then CreateConversionAndReportDiagnostic(argument.Syntax, argument, conv, False, targetType, diagnostics) Else ' in case of delegates, use the operand of the AddressOf as location for this error ' because delegates have different error messages in case there is one or more candidates for narrowing ' indicate this as well. CreateConversionAndReportDiagnostic(diagnosticNode, argument, conv, False, targetType, diagnostics) End If Return True End If End If requiresNarrowingConversion = True ElseIf (conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) <> 0 Then ' Dev10 overload resolution treats conversions that involve narrowing from numeric constant type ' as narrowing. requiresNarrowingConversion = True End If If reportNarrowingConversions AndAlso requiresNarrowingConversion Then Dim err As ERRID = ERRID.ERR_ArgumentNarrowing3 Dim targetDelegateType = targetType.DelegateOrExpressionDelegate(Me) If argument.Kind = BoundKind.QueryLambda AndAlso targetDelegateType IsNot Nothing Then Dim invoke As MethodSymbol = targetDelegateType.DelegateInvokeMethod If invoke IsNot Nothing AndAlso Not invoke.IsSub Then err = ERRID.ERR_NestedFunctionArgumentNarrowing3 argument = DirectCast(argument, BoundQueryLambda).Expression targetType = invoke.ReturnType End If End If If argument.Type Is Nothing Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_ArgumentNarrowing2, CustomSymbolDisplayFormatter.ShortErrorName(param), targetType) Else ReportDiagnostic(diagnostics, argument.Syntax, err, CustomSymbolDisplayFormatter.ShortErrorName(param), argument.Type, targetType) End If End If Return False End Function ''' <summary> ''' Should be kept in sync with OverloadResolution.MatchArguments, which populates ''' data this function operates on. ''' </summary> Private Function PassArguments( node As SyntaxNode, ByRef candidate As OverloadResolution.CandidateAnalysisResult, arguments As ImmutableArray(Of BoundExpression), diagnostics As BindingDiagnosticBag ) As (Arguments As ImmutableArray(Of BoundExpression), DefaultArguments As BitVector) Debug.Assert(candidate.State = OverloadResolution.CandidateAnalysisResultState.Applicable) If (arguments.IsDefault) Then arguments = ImmutableArray(Of BoundExpression).Empty End If Dim paramCount As Integer = candidate.Candidate.ParameterCount Dim parameterToArgumentMap = ArrayBuilder(Of Integer).GetInstance(paramCount, -1) Dim argumentsInOrder = ArrayBuilder(Of BoundExpression).GetInstance(paramCount) Dim defaultArguments = BitVector.Null Dim paramArrayItems As ArrayBuilder(Of Integer) = Nothing If candidate.IsExpandedParamArrayForm Then paramArrayItems = ArrayBuilder(Of Integer).GetInstance() End If Dim paramIndex As Integer ' For each parameter figure out matching argument. If candidate.ArgsToParamsOpt.IsDefaultOrEmpty Then Dim regularParamCount As Integer = paramCount If candidate.IsExpandedParamArrayForm Then regularParamCount -= 1 End If For i As Integer = 0 To Math.Min(regularParamCount, arguments.Length) - 1 Step 1 If arguments(i).Kind <> BoundKind.OmittedArgument Then parameterToArgumentMap(i) = i End If Next If candidate.IsExpandedParamArrayForm Then For i As Integer = regularParamCount To arguments.Length - 1 Step 1 paramArrayItems.Add(i) Next End If Else Dim argsToParams = candidate.ArgsToParamsOpt For i As Integer = 0 To argsToParams.Length - 1 Step 1 paramIndex = argsToParams(i) If arguments(i).Kind <> BoundKind.OmittedArgument Then If (candidate.IsExpandedParamArrayForm AndAlso paramIndex = candidate.Candidate.ParameterCount - 1) Then paramArrayItems.Add(i) Else parameterToArgumentMap(paramIndex) = i End If End If Next End If ' Traverse the parameters, converting corresponding arguments ' as appropriate. Dim candidateIsAProperty As Boolean = (candidate.Candidate.UnderlyingSymbol.Kind = SymbolKind.Property) For paramIndex = 0 To paramCount - 1 Step 1 Dim param As ParameterSymbol = candidate.Candidate.Parameters(paramIndex) Dim targetType As TypeSymbol = param.Type Dim argument As BoundExpression = Nothing Dim conversion As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.Identity Dim conversionBack As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.Identity If candidate.IsExpandedParamArrayForm AndAlso paramIndex = candidate.Candidate.ParameterCount - 1 Then Dim arrayElementType = DirectCast(targetType, ArrayTypeSymbol).ElementType Dim items = ArrayBuilder(Of BoundExpression).GetInstance(paramArrayItems.Count) For i As Integer = 0 To paramArrayItems.Count - 1 Step 1 items.Add(PassArgumentByVal(arguments(paramArrayItems(i)), If(candidate.ConversionsOpt.IsDefaultOrEmpty, Conversions.Identity, candidate.ConversionsOpt(paramArrayItems(i))), arrayElementType, diagnostics)) Next ' Create the bound array and ensure that it is marked as compiler generated. argument = New BoundArrayCreation(node, True, (New BoundExpression() {New BoundLiteral(node, ConstantValue.Create(items.Count), GetSpecialType(SpecialType.System_Int32, node, diagnostics)).MakeCompilerGenerated()}).AsImmutableOrNull(), New BoundArrayInitialization(node, items.ToImmutableAndFree(), targetType).MakeCompilerGenerated(), Nothing, Nothing, targetType).MakeCompilerGenerated() Else Dim argIndex As Integer argIndex = parameterToArgumentMap(paramIndex) argument = If(argIndex = -1, Nothing, arguments(argIndex)) If argument IsNot Nothing AndAlso paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso param.IsParamArray Then argument = ApplyImplicitConversion(argument.Syntax, targetType, argument, diagnostics) ' Leave both conversions at identity since we already applied the conversion ElseIf argIndex > -1 Then If Not candidate.ConversionsOpt.IsDefaultOrEmpty Then conversion = candidate.ConversionsOpt(argIndex) End If If Not candidate.ConversionsBackOpt.IsDefaultOrEmpty Then conversionBack = candidate.ConversionsBackOpt(argIndex) End If End If End If Dim argumentIsDefaultValue As Boolean = False If argument Is Nothing Then Debug.Assert(Not candidate.OptionalArguments.IsEmpty, "Optional arguments expected") If defaultArguments.IsNull Then defaultArguments = BitVector.Create(paramCount) End If ' Deal with Optional arguments Dim defaultArgument As OverloadResolution.OptionalArgument = candidate.OptionalArguments(paramIndex) argument = defaultArgument.DefaultValue diagnostics.AddDependencies(defaultArgument.Dependencies) argumentIsDefaultValue = True defaultArguments(paramIndex) = True Debug.Assert(argument IsNot Nothing) conversion = defaultArgument.Conversion Dim argType = argument.Type If argType IsNot Nothing Then ' Report usesiteerror if it exists. Dim useSiteInfo = argType.GetUseSiteInfo ReportUseSite(diagnostics, argument.Syntax, useSiteInfo) End If End If ' Arguments for properties are always passed with ByVal semantics. Even if ' parameter in metadata is defined ByRef, we always pass corresponding argument ' through a temp without copy-back. Unlike with method calls, we rely on CodeGen ' to introduce the temp (easy to do since there is no copy-back around it), ' this allows us to keep the BoundPropertyAccess node simpler and allows to avoid ' A LOT of complexity in UseTwiceRewriter, which we would otherwise have around ' the temps. Debug.Assert(Not argumentIsDefaultValue OrElse argument.WasCompilerGenerated) Dim adjustedArgument As BoundExpression = PassArgument(argument, conversion, candidateIsAProperty, conversionBack, targetType, param, diagnostics) ' Keep SemanticModel happy. If argumentIsDefaultValue AndAlso adjustedArgument IsNot argument Then adjustedArgument.SetWasCompilerGenerated() End If argumentsInOrder.Add(adjustedArgument) Next If paramArrayItems IsNot Nothing Then paramArrayItems.Free() End If parameterToArgumentMap.Free() Return (argumentsInOrder.ToImmutableAndFree(), defaultArguments) End Function Private Function PassArgument( argument As BoundExpression, conversionTo As KeyValuePair(Of ConversionKind, MethodSymbol), forceByValueSemantics As Boolean, conversionFrom As KeyValuePair(Of ConversionKind, MethodSymbol), targetType As TypeSymbol, param As ParameterSymbol, diagnostics As BindingDiagnosticBag ) As BoundExpression Debug.Assert(Not param.IsByRef OrElse param.IsExplicitByRef OrElse targetType.IsStringType()) ' Non-string arguments for implicitly ByRef string parameters of Declare functions ' are passed through a temp without copy-back. If param.IsByRef AndAlso Not forceByValueSemantics AndAlso (param.IsExplicitByRef OrElse (argument.Type IsNot Nothing AndAlso argument.Type.IsStringType())) Then Return PassArgumentByRef(param.IsOut, argument, conversionTo, conversionFrom, targetType, param.Name, diagnostics) Else Return PassArgumentByVal(argument, conversionTo, targetType, diagnostics) End If End Function Private Function PassArgumentByRef( isOutParameter As Boolean, argument As BoundExpression, conversionTo As KeyValuePair(Of ConversionKind, MethodSymbol), conversionFrom As KeyValuePair(Of ConversionKind, MethodSymbol), targetType As TypeSymbol, parameterName As String, diagnostics As BindingDiagnosticBag ) As BoundExpression #If DEBUG Then Dim checkAgainst As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(argument, targetType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Debug.Assert(conversionTo.Key = checkAgainst.Key) Debug.Assert(Equals(conversionTo.Value, checkAgainst.Value)) #End If ' TODO: Fields of MarshalByRef object are passed via temp. Dim isLValue As Boolean = argument.IsLValue() If isLValue AndAlso argument.Kind = BoundKind.PropertyAccess Then argument = argument.SetAccessKind(PropertyAccessKind.Get) End If If isLValue AndAlso Conversions.IsIdentityConversion(conversionTo.Key) Then 'Nothing to do Debug.Assert(Conversions.IsIdentityConversion(conversionFrom.Key)) Return argument ElseIf isLValue OrElse argument.IsSupportingAssignment() Then ' Need to allocate a temp of the target type, ' init it with argument's value, ' pass it ByRef, ' copy value back after the call. Dim inPlaceholder = New BoundByRefArgumentPlaceholder(argument.Syntax, isOutParameter, argument.Type, argument.HasErrors).MakeCompilerGenerated() Dim inConversion = CreateConversionAndReportDiagnostic(argument.Syntax, inPlaceholder, conversionTo, False, targetType, diagnostics) Dim outPlaceholder = New BoundRValuePlaceholder(argument.Syntax, targetType).MakeCompilerGenerated() Dim copyBackType = argument.GetTypeOfAssignmentTarget() #If DEBUG Then checkAgainst = Conversions.ClassifyConversion(outPlaceholder, copyBackType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Debug.Assert(conversionFrom.Key = checkAgainst.Key) Debug.Assert(Equals(conversionFrom.Value, checkAgainst.Value)) #End If Dim outConversion = CreateConversionAndReportDiagnostic(argument.Syntax, outPlaceholder, conversionFrom, False, copyBackType, diagnostics, copybackConversionParamName:=parameterName).MakeCompilerGenerated() ' since we are going to assign to a latebound invocation ' force its arguments to be rvalues. If argument.Kind = BoundKind.LateInvocation Then argument = MakeArgsRValues(DirectCast(argument, BoundLateInvocation), diagnostics) End If Dim copyBackExpression = BindAssignment(argument.Syntax, argument, outConversion, diagnostics) Debug.Assert(copyBackExpression.HasErrors OrElse (copyBackExpression.Kind = BoundKind.AssignmentOperator AndAlso DirectCast(copyBackExpression, BoundAssignmentOperator).Right Is outConversion)) If Not isLValue Then If argument.IsLateBound() Then argument = argument.SetLateBoundAccessKind(LateBoundAccessKind.Get Or LateBoundAccessKind.Set) Else ' Diagnostics for PropertyAccessKind.Set case has been reported when we called BindAssignment. WarnOnRecursiveAccess(argument, PropertyAccessKind.Get, diagnostics) argument = argument.SetAccessKind(PropertyAccessKind.Get Or PropertyAccessKind.Set) End If End If Return New BoundByRefArgumentWithCopyBack(argument.Syntax, argument, inConversion, inPlaceholder, outConversion, outPlaceholder, targetType, copyBackExpression.HasErrors).MakeCompilerGenerated() Else Dim propertyAccess = TryCast(argument, BoundPropertyAccess) If propertyAccess IsNot Nothing AndAlso propertyAccess.AccessKind <> PropertyAccessKind.Get AndAlso propertyAccess.PropertySymbol.SetMethod?.IsInitOnly Then Debug.Assert(Not propertyAccess.IsWriteable) ' Used to be writable prior to VB 16.9, which caused a use-site error while binding an assignment above. InternalSyntax.Parser.CheckFeatureAvailability(diagnostics, argument.Syntax.Location, DirectCast(argument.Syntax.SyntaxTree.Options, VisualBasicParseOptions).LanguageVersion, InternalSyntax.Feature.InitOnlySettersUsage) End If ' Need to allocate a temp of the target type, ' init it with argument's value, ' pass it ByRef. Code gen will do this. Return PassArgumentByVal(argument, conversionTo, targetType, diagnostics) End If End Function ' when latebound invocation acts as an LHS in an assignment ' its arguments are always passed ByVal since property parameters ' are always treated as ByVal ' This method is used to force the arguments to be RValues Private Function MakeArgsRValues(ByVal invocation As BoundLateInvocation, diagnostics As BindingDiagnosticBag) As BoundLateInvocation Dim args = invocation.ArgumentsOpt If Not args.IsEmpty Then Dim argBuilder As ArrayBuilder(Of BoundExpression) = Nothing For i As Integer = 0 To args.Length - 1 Dim arg = args(i) Dim newArg = MakeRValue(arg, diagnostics) If argBuilder Is Nothing AndAlso arg IsNot newArg Then argBuilder = ArrayBuilder(Of BoundExpression).GetInstance argBuilder.AddRange(args, i) End If If argBuilder IsNot Nothing Then argBuilder.Add(newArg) End If Next If argBuilder IsNot Nothing Then invocation = invocation.Update(invocation.Member, argBuilder.ToImmutableAndFree, invocation.ArgumentNamesOpt, invocation.AccessKind, invocation.MethodOrPropertyGroupOpt, invocation.Type) End If End If Return invocation End Function Friend Function PassArgumentByVal( argument As BoundExpression, conversion As KeyValuePair(Of ConversionKind, MethodSymbol), targetType As TypeSymbol, diagnostics As BindingDiagnosticBag ) As BoundExpression #If DEBUG Then Dim checkAgainst As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(argument, targetType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Debug.Assert(conversion.Key = checkAgainst.Key) Debug.Assert(Equals(conversion.Value, checkAgainst.Value)) #End If argument = CreateConversionAndReportDiagnostic(argument.Syntax, argument, conversion, False, targetType, diagnostics) Debug.Assert(Not argument.IsLValue) Return argument End Function ' Given a list of arguments, create arrays of the bound arguments and the names of those arguments. Private Sub BindArgumentsAndNames( argumentListOpt As ArgumentListSyntax, ByRef boundArguments As ImmutableArray(Of BoundExpression), ByRef argumentNames As ImmutableArray(Of String), ByRef argumentNamesLocations As ImmutableArray(Of Location), diagnostics As BindingDiagnosticBag ) Dim args As ImmutableArray(Of ArgumentSyntax) = Nothing If argumentListOpt IsNot Nothing Then Dim arguments = argumentListOpt.Arguments Dim argsArr(arguments.Count - 1) As ArgumentSyntax For i = 0 To argsArr.Length - 1 argsArr(i) = arguments(i) Next args = argsArr.AsImmutableOrNull End If BindArgumentsAndNames( args, boundArguments, argumentNames, argumentNamesLocations, diagnostics ) End Sub ' Given a list of arguments, create arrays of the bound arguments and the names of those arguments. Private Sub BindArgumentsAndNames( arguments As ImmutableArray(Of ArgumentSyntax), ByRef boundArguments As ImmutableArray(Of BoundExpression), ByRef argumentNames As ImmutableArray(Of String), ByRef argumentNamesLocations As ImmutableArray(Of Location), diagnostics As BindingDiagnosticBag ) ' With SeparatedSyntaxList, it is most efficient to iterate with foreach and not to access Count. If arguments.IsDefaultOrEmpty Then boundArguments = s_noArguments argumentNames = Nothing argumentNamesLocations = Nothing Else Dim boundArgumentsBuilder As ArrayBuilder(Of BoundExpression) = ArrayBuilder(Of BoundExpression).GetInstance Dim argumentNamesBuilder As ArrayBuilder(Of String) = Nothing Dim argumentNamesLocationsBuilder As ArrayBuilder(Of Location) = Nothing Dim argCount As Integer = 0 Dim argumentSyntax As ArgumentSyntax For Each argumentSyntax In arguments Select Case argumentSyntax.Kind Case SyntaxKind.SimpleArgument Dim simpleArgument = DirectCast(argumentSyntax, SimpleArgumentSyntax) boundArgumentsBuilder.Add(BindValue(simpleArgument.Expression, diagnostics)) If simpleArgument.IsNamed Then ' The common case is no named arguments. So we defer all work until the first named argument is seen. If argumentNamesBuilder Is Nothing Then argumentNamesBuilder = ArrayBuilder(Of String).GetInstance() argumentNamesLocationsBuilder = ArrayBuilder(Of Location).GetInstance() For i = 0 To argCount - 1 argumentNamesBuilder.Add(Nothing) argumentNamesLocationsBuilder.Add(Nothing) Next i End If Dim id = simpleArgument.NameColonEquals.Name.Identifier If id.ValueText.Length > 0 Then argumentNamesBuilder.Add(id.ValueText) Else argumentNamesBuilder.Add(Nothing) End If argumentNamesLocationsBuilder.Add(id.GetLocation()) ElseIf argumentNamesBuilder IsNot Nothing Then argumentNamesBuilder.Add(Nothing) argumentNamesLocationsBuilder.Add(Nothing) End If Case SyntaxKind.OmittedArgument boundArgumentsBuilder.Add(New BoundOmittedArgument(argumentSyntax, Nothing)) If argumentNamesBuilder IsNot Nothing Then argumentNamesBuilder.Add(Nothing) argumentNamesLocationsBuilder.Add(Nothing) End If Case SyntaxKind.RangeArgument ' NOTE: Redim statement supports range argument, like: Redim x(0 To 3)(0 To 6) ' This behavior is misleading, because the 'range' (0 To 3) is actually ' being ignored and only upper bound is being used. ' TODO: revise (add warning/error?) Dim rangeArgument = DirectCast(argumentSyntax, RangeArgumentSyntax) CheckRangeArgumentLowerBound(rangeArgument, diagnostics) boundArgumentsBuilder.Add(BindValue(rangeArgument.UpperBound, diagnostics)) If argumentNamesBuilder IsNot Nothing Then argumentNamesBuilder.Add(Nothing) argumentNamesLocationsBuilder.Add(Nothing) End If Case Else Throw ExceptionUtilities.UnexpectedValue(argumentSyntax.Kind) End Select argCount += 1 Next boundArguments = boundArgumentsBuilder.ToImmutableAndFree argumentNames = If(argumentNamesBuilder Is Nothing, Nothing, argumentNamesBuilder.ToImmutableAndFree) argumentNamesLocations = If(argumentNamesLocationsBuilder Is Nothing, Nothing, argumentNamesLocationsBuilder.ToImmutableAndFree) End If End Sub Friend Function GetArgumentForParameterDefaultValue(param As ParameterSymbol, syntax As SyntaxNode, diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, parameterToArgumentMap As ArrayBuilder(Of Integer), arguments As ImmutableArray(Of BoundExpression), reducedExtensionReceiverOpt As BoundExpression) As BoundExpression Dim defaultArgument As BoundExpression = Nothing ' See Section 3 of §11.8.2 Applicable Methods ' Deal with Optional arguments. HasDefaultValue is true if the parameter is optional and has a default value. Dim defaultConstantValue As ConstantValue = If(param.IsOptional, param.ExplicitDefaultConstantValue(DefaultParametersInProgress), Nothing) If defaultConstantValue IsNot Nothing Then If callerInfoOpt IsNot Nothing AndAlso callerInfoOpt.SyntaxTree IsNot Nothing AndAlso Not callerInfoOpt.SyntaxTree.IsEmbeddedOrMyTemplateTree() AndAlso Not SuppressCallerInfo Then Dim isCallerLineNumber As Boolean = param.IsCallerLineNumber Dim isCallerMemberName As Boolean = param.IsCallerMemberName Dim isCallerFilePath As Boolean = param.IsCallerFilePath Dim callerArgumentExpressionParameterIndex As Integer = param.CallerArgumentExpressionParameterIndex Dim isCallerArgumentExpression = callerArgumentExpressionParameterIndex > -1 OrElse (reducedExtensionReceiverOpt IsNot Nothing AndAlso callerArgumentExpressionParameterIndex > -2) If isCallerLineNumber OrElse isCallerMemberName OrElse isCallerFilePath OrElse isCallerArgumentExpression Then Dim callerInfoValue As ConstantValue = Nothing If isCallerLineNumber Then callerInfoValue = ConstantValue.Create(callerInfoOpt.SyntaxTree.GetDisplayLineNumber(GetCallerLocation(callerInfoOpt))) ElseIf isCallerMemberName Then Dim container As Symbol = ContainingMember While container IsNot Nothing Select Case container.Kind Case SymbolKind.Field, SymbolKind.Property, SymbolKind.Event Exit While Case SymbolKind.Method If container.IsLambdaMethod Then container = container.ContainingSymbol Else Dim propertyOrEvent As Symbol = DirectCast(container, MethodSymbol).AssociatedSymbol If propertyOrEvent IsNot Nothing Then container = propertyOrEvent End If Exit While End If Case Else container = container.ContainingSymbol End Select End While If container IsNot Nothing AndAlso container.Name IsNot Nothing Then callerInfoValue = ConstantValue.Create(container.Name) End If ElseIf isCallerFilePath Then callerInfoValue = ConstantValue.Create(callerInfoOpt.SyntaxTree.GetDisplayPath(callerInfoOpt.Span, Me.Compilation.Options.SourceReferenceResolver)) Else Debug.Assert(callerArgumentExpressionParameterIndex > -1 OrElse (reducedExtensionReceiverOpt IsNot Nothing AndAlso callerArgumentExpressionParameterIndex > -2)) Dim argumentSyntax As SyntaxNode = Nothing If callerArgumentExpressionParameterIndex = -1 Then argumentSyntax = reducedExtensionReceiverOpt.Syntax Else Dim argumentIndex = parameterToArgumentMap(callerArgumentExpressionParameterIndex) Debug.Assert(argumentIndex < arguments.Length) If argumentIndex > -1 Then argumentSyntax = arguments(argumentIndex).Syntax End If End If If argumentSyntax IsNot Nothing Then callerInfoValue = ConstantValue.Create(argumentSyntax.ToString()) End If End If If callerInfoValue IsNot Nothing Then ' Use the value only if it will not cause errors. Dim ignoreDiagnostics = New BindingDiagnosticBag(DiagnosticBag.GetInstance()) Dim literal As BoundLiteral If callerInfoValue.Discriminator = ConstantValueTypeDiscriminator.Int32 Then literal = New BoundLiteral(syntax, callerInfoValue, GetSpecialType(SpecialType.System_Int32, syntax, ignoreDiagnostics)) Else Debug.Assert(callerInfoValue.Discriminator = ConstantValueTypeDiscriminator.String) literal = New BoundLiteral(syntax, callerInfoValue, GetSpecialType(SpecialType.System_String, syntax, ignoreDiagnostics)) End If Dim convertedValue As BoundExpression = ApplyImplicitConversion(syntax, param.Type, literal, ignoreDiagnostics) If Not convertedValue.HasErrors AndAlso Not ignoreDiagnostics.HasAnyErrors Then ' Dev11 #248795: Caller info should be omitted if user defined conversion is involved. If Not (convertedValue.Kind = BoundKind.Conversion AndAlso (DirectCast(convertedValue, BoundConversion).ConversionKind And ConversionKind.UserDefined) <> 0) Then defaultConstantValue = callerInfoValue End If End If ignoreDiagnostics.Free() End If End If End If ' For compatibility with the native compiler bad metadata constants should be treated as default(T). This ' is a possible outcome of running an obfuscator over a valid DLL If defaultConstantValue.IsBad Then defaultConstantValue = ConstantValue.Null End If Dim defaultSpecialType = defaultConstantValue.SpecialType Dim defaultArgumentType As TypeSymbol = Nothing ' Constant has a type. Dim paramNullableUnderlyingTypeOrSelf As TypeSymbol = param.Type.GetNullableUnderlyingTypeOrSelf() If param.HasOptionCompare Then ' If the argument has the OptionCompareAttribute ' then use the setting for Option Compare [Binary|Text] ' Other languages will use the default value specified. If Me.OptionCompareText Then defaultConstantValue = ConstantValue.Create(1) Else defaultConstantValue = ConstantValue.Default(SpecialType.System_Int32) End If If paramNullableUnderlyingTypeOrSelf.GetEnumUnderlyingTypeOrSelf().SpecialType = SpecialType.System_Int32 Then defaultArgumentType = paramNullableUnderlyingTypeOrSelf Else defaultArgumentType = GetSpecialType(SpecialType.System_Int32, syntax, diagnostics) End If ElseIf defaultSpecialType <> SpecialType.None Then If paramNullableUnderlyingTypeOrSelf.GetEnumUnderlyingTypeOrSelf().SpecialType = defaultSpecialType Then ' Enum default values are encoded as the underlying primitive type. If the underlying types match then ' use the parameter's enum type. defaultArgumentType = paramNullableUnderlyingTypeOrSelf Else 'Use the primitive type. defaultArgumentType = GetSpecialType(defaultSpecialType, syntax, diagnostics) End If Else ' No type in constant. Constant should be nothing Debug.Assert(defaultConstantValue.IsNothing) End If defaultArgument = New BoundLiteral(syntax, defaultConstantValue, defaultArgumentType) ElseIf param.IsOptional Then ' Handle optional object type argument when no default value is specified. ' Section 3 of §11.8.2 Applicable Methods If param.Type.SpecialType = SpecialType.System_Object Then Dim methodSymbol As MethodSymbol = Nothing If param.IsMarshalAsObject Then ' Nothing defaultArgument = New BoundLiteral(syntax, ConstantValue.Null, Nothing) ElseIf param.IsIDispatchConstant Then ' new DispatchWrapper(nothing) methodSymbol = DirectCast(GetWellKnownTypeMember(WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor, syntax, diagnostics), MethodSymbol) ElseIf param.IsIUnknownConstant Then ' new UnknownWrapper(nothing) methodSymbol = DirectCast(GetWellKnownTypeMember(WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor, syntax, diagnostics), MethodSymbol) Else defaultArgument = New BoundOmittedArgument(syntax, param.Type) End If If methodSymbol IsNot Nothing Then Dim argument = New BoundLiteral(syntax, ConstantValue.Null, param.Type).MakeCompilerGenerated() defaultArgument = New BoundObjectCreationExpression(syntax, methodSymbol, ImmutableArray.Create(Of BoundExpression)(argument), Nothing, methodSymbol.ContainingType) End If Else defaultArgument = New BoundLiteral(syntax, ConstantValue.Null, Nothing) End If End If Return defaultArgument?.MakeCompilerGenerated() End Function Private Shared Function GetCallerLocation(syntax As SyntaxNode) As TextSpan Select Case syntax.Kind Case SyntaxKind.SimpleMemberAccessExpression Return DirectCast(syntax, MemberAccessExpressionSyntax).Name.Span Case SyntaxKind.DictionaryAccessExpression Return DirectCast(syntax, MemberAccessExpressionSyntax).OperatorToken.Span Case Else Return syntax.Span End Select End Function ''' <summary> ''' Return true if the node is an immediate child of a call statement. ''' </summary> Private Shared Function IsCallStatementContext(node As InvocationExpressionSyntax) As Boolean Dim parent As VisualBasicSyntaxNode = node.Parent ' Dig through conditional access If parent IsNot Nothing AndAlso parent.Kind = SyntaxKind.ConditionalAccessExpression Then Dim conditional = DirectCast(parent, ConditionalAccessExpressionSyntax) If conditional.WhenNotNull Is node Then parent = conditional.Parent End If End If Return parent IsNot Nothing AndAlso (parent.Kind = SyntaxKind.CallStatement OrElse parent.Kind = SyntaxKind.ExpressionStatement) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic ' Binding of method/property invocation is implemented in this part. Partial Friend Class Binder Private Function CreateBoundMethodGroup( node As SyntaxNode, lookupResult As LookupResult, lookupOptionsUsed As LookupOptions, withDependencies As Boolean, receiver As BoundExpression, typeArgumentsOpt As BoundTypeArguments, qualKind As QualificationKind, Optional hasError As Boolean = False ) As BoundMethodGroup Dim pendingExtensionMethods As ExtensionMethodGroup = Nothing Debug.Assert(lookupResult.Kind = LookupResultKind.Good OrElse lookupResult.Kind = LookupResultKind.Inaccessible) ' Name lookup does not look for extension methods if it found a suitable ' instance method. So, if the first symbol we have is not a reduced extension ' method, we might need to look for extension methods later, on demand. Debug.Assert((lookupOptionsUsed And LookupOptions.EagerlyLookupExtensionMethods) = 0) If lookupResult.IsGood AndAlso Not lookupResult.Symbols(0).IsReducedExtensionMethod() Then pendingExtensionMethods = New ExtensionMethodGroup(Me, lookupOptionsUsed, withDependencies) End If Return New BoundMethodGroup( node, typeArgumentsOpt, lookupResult.Symbols.ToDowncastedImmutable(Of MethodSymbol), pendingExtensionMethods, lookupResult.Kind, receiver, qualKind, hasErrors:=hasError) End Function ''' <summary> ''' Returns if all the rules for a "Me.New" or "MyBase.New" constructor call are satisfied: ''' a) In instance constructor body ''' b) First statement of that constructor ''' c) "Me", "MyClass", or "MyBase" is the receiver. ''' </summary> Private Function IsConstructorCallAllowed(invocationExpression As InvocationExpressionSyntax, boundMemberGroup As BoundMethodOrPropertyGroup) As Boolean If Me.ContainingMember.Kind = SymbolKind.Method AndAlso DirectCast(Me.ContainingMember, MethodSymbol).MethodKind = MethodKind.Constructor Then ' (a) we are in an instance constructor body Dim node As VisualBasicSyntaxNode = invocationExpression.Parent If node Is Nothing OrElse (node.Kind <> SyntaxKind.CallStatement AndAlso node.Kind <> SyntaxKind.ExpressionStatement) Then Return False End If Dim nodeParent As VisualBasicSyntaxNode = node.Parent If nodeParent Is Nothing OrElse nodeParent.Kind <> SyntaxKind.ConstructorBlock Then Return False End If If DirectCast(nodeParent, ConstructorBlockSyntax).Statements(0) Is node Then ' (b) call statement we are binding is 'the first' statement of the constructor Dim receiver As BoundExpression = boundMemberGroup.ReceiverOpt If receiver IsNot Nothing AndAlso (receiver.Kind = BoundKind.MeReference OrElse receiver.Kind = BoundKind.MyBaseReference OrElse receiver.Kind = BoundKind.MyClassReference) Then ' (c) receiver is 'Me'/'MyClass'/'MyBase' Return True End If End If End If Return False End Function Friend Class ConstructorCallArgumentsBinder Inherits Binder Public Sub New(containingBinder As Binder) MyBase.New(containingBinder) End Sub Protected Overrides ReadOnly Property IsInsideChainedConstructorCallArguments As Boolean Get Return True End Get End Property End Class ''' <summary> ''' Bind a Me.New(...), MyBase.New (...), MyClass.New(...) constructor call. ''' (NOT a normal constructor call like New Type(...)). ''' </summary> Private Function BindDirectConstructorCall(node As InvocationExpressionSyntax, group As BoundMethodGroup, diagnostics As BindingDiagnosticBag) As BoundExpression Dim boundArguments As ImmutableArray(Of BoundExpression) = Nothing Dim argumentNames As ImmutableArray(Of String) = Nothing Dim argumentNamesLocations As ImmutableArray(Of Location) = Nothing Dim argumentList As ArgumentListSyntax = node.ArgumentList Debug.Assert(IsGroupOfConstructors(group)) ' Direct constructor call is only allowed if: (a) we are in an instance constructor body, ' and (b) call statement we are binding is 'the first' statement of the constructor, ' and (c) receiver is 'Me'/'MyClass'/'MyBase' If IsConstructorCallAllowed(node, group) Then ' Bind arguments with special binder that prevents use of Me. Dim argumentsBinder As Binder = New ConstructorCallArgumentsBinder(Me) argumentsBinder.BindArgumentsAndNames(argumentList, boundArguments, argumentNames, argumentNamesLocations, diagnostics) ' Bind constructor call, errors will be generated if needed Return BindInvocationExpression(node, node.Expression, ExtractTypeCharacter(node.Expression), group, boundArguments, argumentNames, diagnostics, allowConstructorCall:=True, callerInfoOpt:=group.Syntax) Else ' Error case -- constructor call in wrong location. ' Report error BC30282 about invalid constructor call ' For semantic model / IDE purposes, we still bind it even if in a location that wasn't allowed. If Not group.HasErrors Then ReportDiagnostic(diagnostics, group.Syntax, ERRID.ERR_InvalidConstructorCall) End If BindArgumentsAndNames(argumentList, boundArguments, argumentNames, argumentNamesLocations, diagnostics) ' Bind constructor call, ignore errors by putting into discarded bag. Dim expr = BindInvocationExpression(node, node.Expression, ExtractTypeCharacter(node.Expression), group, boundArguments, argumentNames, BindingDiagnosticBag.Discarded, allowConstructorCall:=True, callerInfoOpt:=group.Syntax) If expr.Kind = BoundKind.Call Then ' Set HasErrors to prevent cascading errors. Dim callExpr = DirectCast(expr, BoundCall) expr = New BoundCall( callExpr.Syntax, callExpr.Method, callExpr.MethodGroupOpt, callExpr.ReceiverOpt, callExpr.Arguments, callExpr.DefaultArguments, callExpr.ConstantValueOpt, isLValue:=False, suppressObjectClone:=False, type:=callExpr.Type, hasErrors:=True) End If Return expr End If End Function Private Function BindInvocationExpression(node As InvocationExpressionSyntax, diagnostics As BindingDiagnosticBag) As BoundExpression ' Set "IsInvocationsOrAddressOf" to prevent binding to return value variable. Dim target As BoundExpression If node.Expression Is Nothing Then ' Must be conditional case Dim conditionalAccess As ConditionalAccessExpressionSyntax = node.GetCorrespondingConditionalAccessExpression() If conditionalAccess IsNot Nothing Then target = GetConditionalAccessReceiver(conditionalAccess) Else target = ReportDiagnosticAndProduceBadExpression(diagnostics, node, ERRID.ERR_Syntax).MakeCompilerGenerated() End If Else target = BindExpression(node.Expression, diagnostics:=diagnostics, isInvocationOrAddressOf:=True, isOperandOfConditionalBranch:=False, eventContext:=False) End If ' If 'target' is a bound constructor group, we need to do special checks and special processing of arguments. If target.Kind = BoundKind.MethodGroup Then Dim group = DirectCast(target, BoundMethodGroup) If IsGroupOfConstructors(group) Then Return BindDirectConstructorCall(node, group, diagnostics) End If End If Dim boundArguments As ImmutableArray(Of BoundExpression) = Nothing Dim argumentNames As ImmutableArray(Of String) = Nothing Dim argumentNamesLocations As ImmutableArray(Of Location) = Nothing Me.BindArgumentsAndNames(node.ArgumentList, boundArguments, argumentNames, argumentNamesLocations, diagnostics) If target.Kind = BoundKind.MethodGroup OrElse target.Kind = BoundKind.PropertyGroup Then Return BindInvocationExpressionPossiblyWithoutArguments( node, ExtractTypeCharacter(node.Expression), DirectCast(target, BoundMethodOrPropertyGroup), boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments:=True, diagnostics:=diagnostics) End If If target.Kind = BoundKind.NamespaceExpression Then Dim namespaceExp As BoundNamespaceExpression = DirectCast(target, BoundNamespaceExpression) Dim diagInfo = ErrorFactory.ErrorInfo(ERRID.ERR_NamespaceNotExpression1, namespaceExp.NamespaceSymbol) ReportDiagnostic(diagnostics, node.Expression, diagInfo) ElseIf target.Kind = BoundKind.TypeExpression Then Dim typeExp As BoundTypeExpression = DirectCast(target, BoundTypeExpression) If Not IsCallStatementContext(node) Then ' Try default instance property through DefaultInstanceAlias Dim instance As BoundExpression = TryDefaultInstanceProperty(typeExp, diagnostics) If instance IsNot Nothing Then Return BindIndexedInvocationExpression( node, instance, boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments:=False, hasIndexableTarget:=False, diagnostics:=diagnostics) End If End If Dim diagInfo = ErrorFactory.ErrorInfo(GetTypeNotExpressionErrorId(typeExp.Type), typeExp.Type) ReportDiagnostic(diagnostics, node.Expression, diagInfo) Else Return BindIndexedInvocationExpression( node, target, boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments:=True, hasIndexableTarget:=False, diagnostics:=diagnostics) End If Return GenerateBadExpression(node, target, boundArguments) End Function ''' <summary> ''' Bind an invocation expression representing an array access, ''' delegate invocation, or default member. ''' </summary> Private Function BindIndexedInvocationExpression( node As InvocationExpressionSyntax, target As BoundExpression, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), argumentNamesLocations As ImmutableArray(Of Location), allowBindingWithoutArguments As Boolean, <Out()> ByRef hasIndexableTarget As Boolean, diagnostics As BindingDiagnosticBag) As BoundExpression Debug.Assert(target.Kind <> BoundKind.NamespaceExpression) Debug.Assert(target.Kind <> BoundKind.TypeExpression) Debug.Assert(target.Kind <> BoundKind.MethodGroup) Debug.Assert(target.Kind <> BoundKind.PropertyGroup) hasIndexableTarget = False If Not target.IsLValue AndAlso target.Kind <> BoundKind.LateMemberAccess Then target = MakeRValue(target, diagnostics) End If Dim targetType As TypeSymbol = target.Type ' there are values or variables like "Nothing" which have no type If targetType IsNot Nothing Then ' this method is also called for e.g. Arrays because they are also InvocationExpressions ' if target is an array, then call BindArrayAccess only if target is not a direct successor ' of a call statement If targetType.IsArrayType Then hasIndexableTarget = True ' only bind to an array if this method was called outside of a call statement context If Not IsCallStatementContext(node) Then Return BindArrayAccess(node, target, boundArguments, argumentNames, diagnostics) End If ElseIf targetType.Kind = SymbolKind.NamedType AndAlso targetType.TypeKind = TypeKind.Delegate Then hasIndexableTarget = True ' an invocation of a delegate actually calls the delegate's Invoke method. Dim delegateInvoke = DirectCast(targetType, NamedTypeSymbol).DelegateInvokeMethod If delegateInvoke Is Nothing Then If Not target.HasErrors Then ReportDiagnostic(diagnostics, target.Syntax, ERRID.ERR_DelegateNoInvoke1, target.Type) End If ElseIf ReportDelegateInvokeUseSite(diagnostics, target.Syntax, targetType, delegateInvoke) Then delegateInvoke = Nothing End If If delegateInvoke IsNot Nothing Then Dim methodGroup = New BoundMethodGroup( If(node.Expression, node), Nothing, ImmutableArray.Create(Of MethodSymbol)(delegateInvoke), LookupResultKind.Good, target, QualificationKind.QualifiedViaValue).MakeCompilerGenerated() Return BindInvocationExpression( node, If(node.Expression, node), ExtractTypeCharacter(node.Expression), methodGroup, boundArguments, argumentNames, diagnostics, callerInfoOpt:=node, representCandidateInDiagnosticsOpt:=targetType) Else Dim badExpressionChildren = ArrayBuilder(Of BoundExpression).GetInstance() badExpressionChildren.Add(target) badExpressionChildren.AddRange(boundArguments) Return BadExpression(node, badExpressionChildren.ToImmutableAndFree(), ErrorTypeSymbol.UnknownResultType) End If End If End If If target.Kind = BoundKind.BadExpression Then ' Error already reported for a bad expression, so don't report another error ElseIf Not IsCallStatementContext(node) Then ' If the invocation is outside of a call statement ' context, bind to the default property group if any. If target.Type.SpecialType = SpecialType.System_Object OrElse target.Type.SpecialType = SpecialType.System_Array Then hasIndexableTarget = True Return BindLateBoundInvocation(node, Nothing, target, boundArguments, argumentNames, diagnostics, suppressLateBindingResolutionDiagnostics:=(target.Kind = BoundKind.LateMemberAccess)) End If If Not target.HasErrors Then ' Bind to the default property group. Dim defaultPropertyGroup As BoundExpression = BindDefaultPropertyGroup(If(node.Expression, node), target, diagnostics) If defaultPropertyGroup IsNot Nothing Then Debug.Assert(defaultPropertyGroup.Kind = BoundKind.PropertyGroup OrElse defaultPropertyGroup.Kind = BoundKind.MethodGroup OrElse defaultPropertyGroup.HasErrors) hasIndexableTarget = True If defaultPropertyGroup.Kind = BoundKind.PropertyGroup OrElse defaultPropertyGroup.Kind = BoundKind.MethodGroup Then Return BindInvocationExpressionPossiblyWithoutArguments( node, TypeCharacter.None, DirectCast(defaultPropertyGroup, BoundMethodOrPropertyGroup), boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments, diagnostics) End If Else ReportNoDefaultProperty(target, diagnostics) End If End If ElseIf target.Kind = BoundKind.LateMemberAccess Then hasIndexableTarget = True Dim lateMember = DirectCast(target, BoundLateMemberAccess) Return BindLateBoundInvocation(node, Nothing, lateMember, boundArguments, argumentNames, diagnostics) ElseIf Not target.HasErrors Then ' "Expression is not a method." Dim diagInfo = ErrorFactory.ErrorInfo(ERRID.ERR_ExpectedProcedure) ReportDiagnostic(diagnostics, If(node.Expression, node), diagInfo) End If Return GenerateBadExpression(node, target, boundArguments) End Function Private Function BindInvocationExpressionPossiblyWithoutArguments( node As InvocationExpressionSyntax, typeChar As TypeCharacter, group As BoundMethodOrPropertyGroup, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), argumentNamesLocations As ImmutableArray(Of Location), allowBindingWithoutArguments As Boolean, diagnostics As BindingDiagnosticBag) As BoundExpression ' Spec §11.8 Invocation Expressions ' ... ' If the method group only contains one accessible method, including both instance and ' extension methods, and that method takes no arguments and is a function, then the method ' group is interpreted as an invocation expression with an empty argument list and the result ' is used as the target of an invocation expression with the provided argument list(s). If allowBindingWithoutArguments AndAlso boundArguments.Length > 0 AndAlso Not IsCallStatementContext(node) AndAlso ShouldBindWithoutArguments(node, group, diagnostics) Then Dim tmpDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics) Dim result As BoundExpression = Nothing Debug.Assert(node.Expression IsNot Nothing) ' NOTE: when binding without arguments, we pass node.Expression as the first parameter ' so that the new bound node references it instead of invocation expression Dim withoutArgs = BindInvocationExpression( node.Expression, node.Expression, typeChar, group, ImmutableArray(Of BoundExpression).Empty, Nothing, tmpDiagnostics, callerInfoOpt:=group.Syntax) If withoutArgs.Kind = BoundKind.Call OrElse withoutArgs.Kind = BoundKind.PropertyAccess Then ' We were able to bind the method group or property access without arguments, ' possibly with some diagnostic. diagnostics.AddRange(tmpDiagnostics) tmpDiagnostics.Clear() If withoutArgs.Kind = BoundKind.PropertyAccess Then Dim receiverOpt As BoundExpression = DirectCast(withoutArgs, BoundPropertyAccess).ReceiverOpt If receiverOpt?.Syntax Is withoutArgs.Syntax AndAlso Not receiverOpt.WasCompilerGenerated Then withoutArgs.MakeCompilerGenerated() End If withoutArgs = MakeRValue(withoutArgs, diagnostics) Else Dim receiverOpt As BoundExpression = DirectCast(withoutArgs, BoundCall).ReceiverOpt If receiverOpt?.Syntax Is withoutArgs.Syntax AndAlso Not receiverOpt.WasCompilerGenerated Then withoutArgs.MakeCompilerGenerated() End If End If If withoutArgs.Kind = BoundKind.BadExpression Then result = GenerateBadExpression(node, withoutArgs, boundArguments) Else Dim hasIndexableTarget = False ' Bind the invocation with arguments as an indexed invocation. Dim withArgs = BindIndexedInvocationExpression( node, withoutArgs, boundArguments, argumentNames, argumentNamesLocations, allowBindingWithoutArguments:=False, hasIndexableTarget:=hasIndexableTarget, diagnostics:=tmpDiagnostics) If hasIndexableTarget Then diagnostics.AddRange(tmpDiagnostics) result = withArgs Else ' Report BC32016 if something wrong. ReportDiagnostic(diagnostics, node.Expression, ERRID.ERR_FunctionResultCannotBeIndexed1, withoutArgs.ExpressionSymbol) ' If result of binding with no args was not indexable after all, then instead ' of just producing a bad expression, bind the invocation expression normally, ' but without reporting any more diagnostics. This produces more accurate ' bound nodes for semantic model questions and may allow the type of the ' expression to be computed, thus leading to fewer errors later. result = BindInvocationExpression( node, node.Expression, typeChar, group, boundArguments, argumentNames, BindingDiagnosticBag.Discarded, callerInfoOpt:=group.Syntax) End If End If End If tmpDiagnostics.Free() If result IsNot Nothing Then Return result End If End If Return BindInvocationExpression( node, If(node.Expression, group.Syntax), typeChar, group, boundArguments, argumentNames, diagnostics, callerInfoOpt:=group.Syntax) End Function ''' <summary> ''' Returns a BoundPropertyGroup if the expression represents a valid ''' default property access. If there is a default property but the property ''' access is invalid, a BoundBadExpression is returned. If there is no ''' default property for the expression type, Nothing is returned. ''' ''' Note, that default Query Indexer may be a method, not a property. ''' </summary> Private Function BindDefaultPropertyGroup(node As VisualBasicSyntaxNode, target As BoundExpression, diagnostics As BindingDiagnosticBag) As BoundExpression Dim result = LookupResult.GetInstance() Dim defaultMemberGroup As BoundExpression = Nothing Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) MemberLookup.LookupDefaultProperty(result, target.Type, Me, useSiteInfo) ' We're not reporting any diagnostic if there are no symbols. Debug.Assert(result.HasSymbol OrElse Not result.HasDiagnostic) If result.HasSymbol Then defaultMemberGroup = BindSymbolAccess(node, result, LookupOptions.Default, target, Nothing, QualificationKind.QualifiedViaValue, diagnostics) Debug.Assert(defaultMemberGroup IsNot Nothing) Debug.Assert((defaultMemberGroup.Kind = BoundKind.BadExpression) OrElse (defaultMemberGroup.Kind = BoundKind.PropertyGroup)) Else ' All queryable sources have default indexer, which maps to an ElementAtOrDefault method or property on the source. Dim tempDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics) target = MakeRValue(target, tempDiagnostics) Dim controlVariableType As TypeSymbol = Nothing target = ConvertToQueryableType(target, tempDiagnostics, controlVariableType) If controlVariableType IsNot Nothing Then result.Clear() Const options As LookupOptions = LookupOptions.AllMethodsOfAnyArity ' overload resolution filters methods by arity. LookupMember(result, target.Type, StringConstants.ElementAtMethod, 0, options, useSiteInfo) If result.IsGood Then Dim kind As SymbolKind = result.Symbols(0).Kind If kind = SymbolKind.Method OrElse kind = SymbolKind.Property Then diagnostics.AddRange(tempDiagnostics) defaultMemberGroup = BindSymbolAccess(node, result, options, target, Nothing, QualificationKind.QualifiedViaValue, diagnostics) End If End If End If tempDiagnostics.Free() End If diagnostics.Add(node, useSiteInfo) result.Free() ' We don't want the default property GROUP to override the meaning of the item it's being ' accessed off of, so mark it as compiler generated. If defaultMemberGroup IsNot Nothing Then defaultMemberGroup.SetWasCompilerGenerated() End If Return defaultMemberGroup End Function ''' <summary> ''' Tests whether or not the method or property group should be bound without arguments. ''' In case of method group it may also update the group by filtering out all subs ''' </summary> Private Function ShouldBindWithoutArguments(node As VisualBasicSyntaxNode, ByRef group As BoundMethodOrPropertyGroup, diagnostics As BindingDiagnosticBag) As Boolean Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) Dim result = ShouldBindWithoutArguments(group, useSiteInfo) diagnostics.Add(node, useSiteInfo) Return result End Function Private Function ShouldBindWithoutArguments(ByRef group As BoundMethodOrPropertyGroup, <[In], Out> ByRef useSiteInfo As CompoundUseSiteInfo(Of AssemblySymbol)) As Boolean If group.Kind = BoundKind.MethodGroup Then Dim newMethods As ArrayBuilder(Of MethodSymbol) = ArrayBuilder(Of MethodSymbol).GetInstance() ' check method group members Dim methodGroup = DirectCast(group, BoundMethodGroup) Debug.Assert(methodGroup.Methods.Length > 0) ' any sub should be removed from a group in case we try binding without arguments Dim shouldUpdateGroup As Boolean = False Dim atLeastOneFunction As Boolean = False ' Dev10 behavior: ' For instance methods - ' Check if all functions from the group (ignoring subs) ' have the same arity as specified in the call and 0 parameters. ' However, the part that handles arity check is rather inconsistent between methods ' overloaded within the same type and in derived type. Also, language spec doesn't mention ' any restrictions for arity. So, we will not try to duplicate Dev10 logic around arity ' because the logic is close to impossible to match and behavior change will not be a breaking ' change. ' In presence of extension methods the rules are more constrained- ' If group contains an extension method, it must be the only method in the group, ' it must have no parameters, must have no type parameters and must be a Function. ' Note, we should avoid requesting AdditionalExtensionMethods whenever possible because ' lookup of extension methods might be very expensive. Dim extensionMethod As MethodSymbol = Nothing For Each method In methodGroup.Methods If method.IsReducedExtensionMethod Then extensionMethod = method Exit For End If If (method.IsSub) Then If method.CanBeCalledWithNoParameters() Then ' If its a sub that could be called parameterlessly, it might hide the function. So it is included ' in the group for further processing in overload resolution (which will process possible hiding). ' If overload resolution does select the Sub, we'll get an error about return type not indexable. ' See Roslyn bug 14019 for example. newMethods.Add(method) Else ' ignore other subs entirely shouldUpdateGroup = True End If ElseIf method.ParameterCount > 0 Then ' any function with more than 0 parameters newMethods.Free() Return False Else newMethods.Add(method) atLeastOneFunction = True End If Next If extensionMethod Is Nothing Then Dim additionalExtensionMethods As ImmutableArray(Of MethodSymbol) = methodGroup.AdditionalExtensionMethods(useSiteInfo) If additionalExtensionMethods.Length > 0 Then Debug.Assert(methodGroup.Methods.Length > 0) ' We have at least one extension method in the group and it is not the only one method in the ' group. Cannot apply default property transformation. newMethods.Free() Return False End If Else newMethods.Free() Debug.Assert(extensionMethod IsNot Nothing) ' This method must have no parameters, must have no type parameters and must not be a Sub. Return methodGroup.Methods.Length = 1 AndAlso methodGroup.TypeArgumentsOpt Is Nothing AndAlso extensionMethod.ParameterCount = 0 AndAlso extensionMethod.Arity = 0 AndAlso Not extensionMethod.IsSub AndAlso methodGroup.AdditionalExtensionMethods(useSiteInfo).Length = 0 End If If Not atLeastOneFunction Then newMethods.Free() Return False End If If shouldUpdateGroup Then ' at least one sub was removed If newMethods.IsEmpty Then ' no functions left newMethods.Free() Return False End If ' there are some functions, update the group group = methodGroup.Update(methodGroup.TypeArgumentsOpt, newMethods.ToImmutable(), Nothing, methodGroup.ResultKind, methodGroup.ReceiverOpt, methodGroup.QualificationKind) End If newMethods.Free() Return True Else ' check property group members Dim propertyGroup = DirectCast(group, BoundPropertyGroup) Debug.Assert(propertyGroup.Properties.Length > 0) For Each prop In propertyGroup.Properties If (prop.ParameterCount > 0) Then Return False End If Next ' assuming property group was not empty Return True End If End Function Private Shared Function IsGroupOfConstructors(group As BoundMethodOrPropertyGroup) As Boolean If group.Kind = BoundKind.MethodGroup Then Dim methodGroup = DirectCast(group, BoundMethodGroup) Debug.Assert(methodGroup.Methods.Length > 0) Return methodGroup.Methods(0).MethodKind = MethodKind.Constructor End If Return False End Function Friend Function BindInvocationExpression( node As SyntaxNode, target As SyntaxNode, typeChar As TypeCharacter, group As BoundMethodOrPropertyGroup, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional allowConstructorCall As Boolean = False, Optional suppressAbstractCallDiagnostics As Boolean = False, Optional isDefaultMemberAccess As Boolean = False, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing, Optional forceExpandedForm As Boolean = False ) As BoundExpression Debug.Assert(group IsNot Nothing) Debug.Assert(allowConstructorCall OrElse Not IsGroupOfConstructors(group)) Debug.Assert(group.ResultKind = LookupResultKind.Good OrElse group.ResultKind = LookupResultKind.Inaccessible) ' It is possible to get here with method group with ResultKind = LookupResultKind.Inaccessible. ' When this happens, it is worth trying to do overload resolution on the "bad" set ' to report better errors. Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) Dim results As OverloadResolution.OverloadResolutionResult = OverloadResolution.MethodOrPropertyInvocationOverloadResolution(group, boundArguments, argumentNames, Me, callerInfoOpt, useSiteInfo, forceExpandedForm:=forceExpandedForm) If diagnostics.Add(node, useSiteInfo) Then If group.ResultKind <> LookupResultKind.Inaccessible Then ' Suppress additional diagnostics diagnostics = BindingDiagnosticBag.Discarded End If End If If Not results.BestResult.HasValue Then If results.ResolutionIsLateBound Then Debug.Assert(OptionStrict <> VisualBasic.OptionStrict.On) ' Did we have extension methods among candidates? If group.Kind = BoundKind.MethodGroup Then Dim haveAnExtensionMethod As Boolean = False Dim methodGroup = DirectCast(group, BoundMethodGroup) For Each method As MethodSymbol In methodGroup.Methods If method.ReducedFrom IsNot Nothing Then haveAnExtensionMethod = True Exit For End If Next If Not haveAnExtensionMethod Then useSiteInfo = New CompoundUseSiteInfo(Of AssemblySymbol)(useSiteInfo) haveAnExtensionMethod = Not methodGroup.AdditionalExtensionMethods(useSiteInfo).IsEmpty diagnostics.Add(node, useSiteInfo) End If If haveAnExtensionMethod Then ReportDiagnostic(diagnostics, GetLocationForOverloadResolutionDiagnostic(node, group), ERRID.ERR_ExtensionMethodCannotBeLateBound) Dim builder = ArrayBuilder(Of BoundExpression).GetInstance() builder.Add(group) If Not boundArguments.IsEmpty Then builder.AddRange(boundArguments) End If Return New BoundBadExpression(node, LookupResultKind.OverloadResolutionFailure, ImmutableArray(Of Symbol).Empty, builder.ToImmutableAndFree(), ErrorTypeSymbol.UnknownResultType, hasErrors:=True) End If End If Return BindLateBoundInvocation(node, group, isDefaultMemberAccess, boundArguments, argumentNames, diagnostics) End If ' Create and report the diagnostic. If results.Candidates.Length = 0 Then results = OverloadResolution.MethodOrPropertyInvocationOverloadResolution(group, boundArguments, argumentNames, Me, includeEliminatedCandidates:=True, callerInfoOpt:=callerInfoOpt, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded, forceExpandedForm:=forceExpandedForm) End If Return ReportOverloadResolutionFailureAndProduceBoundNode(node, group, boundArguments, argumentNames, results, diagnostics, callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else Return CreateBoundCallOrPropertyAccess( node, target, typeChar, group, boundArguments, results.BestResult.Value, results.AsyncLambdaSubToFunctionMismatch, diagnostics, suppressAbstractCallDiagnostics) End If End Function Private Function CreateBoundCallOrPropertyAccess( node As SyntaxNode, target As SyntaxNode, typeChar As TypeCharacter, group As BoundMethodOrPropertyGroup, boundArguments As ImmutableArray(Of BoundExpression), bestResult As OverloadResolution.CandidateAnalysisResult, asyncLambdaSubToFunctionMismatch As ImmutableArray(Of BoundExpression), diagnostics As BindingDiagnosticBag, Optional suppressAbstractCallDiagnostics As Boolean = False ) As BoundExpression Dim candidate = bestResult.Candidate Dim methodOrProperty = candidate.UnderlyingSymbol Dim returnType = candidate.ReturnType If group.ResultKind = LookupResultKind.Inaccessible Then ReportDiagnostic(diagnostics, target, GetInaccessibleErrorInfo(bestResult.Candidate.UnderlyingSymbol)) Else Debug.Assert(group.ResultKind = LookupResultKind.Good) CheckMemberTypeAccessibility(diagnostics, node, methodOrProperty) End If If bestResult.TypeArgumentInferenceDiagnosticsOpt IsNot Nothing Then diagnostics.AddRange(bestResult.TypeArgumentInferenceDiagnosticsOpt) End If Dim argumentInfo As (Arguments As ImmutableArray(Of BoundExpression), DefaultArguments As BitVector) = PassArguments(node, bestResult, boundArguments, diagnostics) boundArguments = argumentInfo.Arguments Debug.Assert(Not boundArguments.IsDefault) Dim hasErrors As Boolean = False Dim receiver As BoundExpression = group.ReceiverOpt If group.ResultKind = LookupResultKind.Good Then hasErrors = CheckSharedSymbolAccess(target, methodOrProperty.IsShared, receiver, group.QualificationKind, diagnostics) ' give diagnostics if sharedness is wrong. End If ReportDiagnosticsIfObsoleteOrNotSupported(diagnostics, methodOrProperty, node) hasErrors = hasErrors Or group.HasErrors If Not returnType.IsErrorType() Then VerifyTypeCharacterConsistency(node, returnType, typeChar, diagnostics) End If Dim resolvedTypeOrValueReceiver As BoundExpression = Nothing If receiver IsNot Nothing AndAlso Not hasErrors Then receiver = AdjustReceiverTypeOrValue(receiver, receiver.Syntax, methodOrProperty.IsShared, diagnostics, resolvedTypeOrValueReceiver) End If If Not suppressAbstractCallDiagnostics AndAlso receiver IsNot Nothing AndAlso (receiver.IsMyBaseReference OrElse receiver.IsMyClassReference) Then If methodOrProperty.IsMustOverride Then ' Generate an error, but continue processing ReportDiagnostic(diagnostics, group.Syntax, If(receiver.IsMyBaseReference, ERRID.ERR_MyBaseAbstractCall1, ERRID.ERR_MyClassAbstractCall1), methodOrProperty) End If End If If Not asyncLambdaSubToFunctionMismatch.IsEmpty Then For Each lambda In asyncLambdaSubToFunctionMismatch Dim errorLocation As SyntaxNode = lambda.Syntax Dim lambdaNode = TryCast(errorLocation, LambdaExpressionSyntax) If lambdaNode IsNot Nothing Then errorLocation = lambdaNode.SubOrFunctionHeader End If ReportDiagnostic(diagnostics, errorLocation, ERRID.WRN_AsyncSubCouldBeFunction) Next End If If methodOrProperty.Kind = SymbolKind.Method Then Dim method = DirectCast(methodOrProperty, MethodSymbol) Dim reducedFrom = method.ReducedFrom Dim constantValue As ConstantValue = Nothing If reducedFrom Is Nothing Then If receiver IsNot Nothing AndAlso receiver.IsPropertyOrXmlPropertyAccess() Then receiver = MakeRValue(receiver, diagnostics) End If If method.IsUserDefinedOperator() AndAlso Me.ContainingMember Is method Then ReportDiagnostic(diagnostics, target, ERRID.WRN_RecursiveOperatorCall, method) End If ' replace call with literal if possible (Chr, ChrW, Asc, AscW) constantValue = OptimizeLibraryCall(method, boundArguments, node, hasErrors, diagnostics) Else ' We are calling an extension method, prepare the receiver to be ' passed as the first parameter. receiver = UpdateReceiverForExtensionMethodOrPropertyGroup(receiver, method.ReceiverType, reducedFrom.Parameters(0), diagnostics) End If ' Remove receiver from the method group ' NOTE: we only remove it if we pass it to a new BoundCall node, ' otherwise we keep it in the group to support semantic queries Dim methodGroup = DirectCast(group, BoundMethodGroup) Dim newReceiver As BoundExpression = If(receiver IsNot Nothing, Nothing, If(resolvedTypeOrValueReceiver, methodGroup.ReceiverOpt)) methodGroup = methodGroup.Update(methodGroup.TypeArgumentsOpt, methodGroup.Methods, methodGroup.PendingExtensionMethodsOpt, methodGroup.ResultKind, newReceiver, methodGroup.QualificationKind) Return New BoundCall( node, method, methodGroup, receiver, boundArguments, constantValue, returnType, suppressObjectClone:=False, hasErrors:=hasErrors, defaultArguments:=argumentInfo.DefaultArguments) Else Dim [property] = DirectCast(methodOrProperty, PropertySymbol) Dim reducedFrom = [property].ReducedFromDefinition Debug.Assert(Not boundArguments.Any(Function(a) a.Kind = BoundKind.ByRefArgumentWithCopyBack)) If reducedFrom Is Nothing Then If receiver IsNot Nothing AndAlso receiver.IsPropertyOrXmlPropertyAccess() Then receiver = MakeRValue(receiver, diagnostics) End If Else receiver = UpdateReceiverForExtensionMethodOrPropertyGroup(receiver, [property].ReceiverType, reducedFrom.Parameters(0), diagnostics) End If ' Remove receiver from the property group ' NOTE: we only remove it if we pass it to a new BoundPropertyAccess node, ' otherwise we keep it in the group to support semantic queries Dim propertyGroup = DirectCast(group, BoundPropertyGroup) Dim newReceiver As BoundExpression = If(receiver IsNot Nothing, Nothing, If(resolvedTypeOrValueReceiver, propertyGroup.ReceiverOpt)) propertyGroup = propertyGroup.Update(propertyGroup.Properties, propertyGroup.ResultKind, newReceiver, propertyGroup.QualificationKind) Return New BoundPropertyAccess( node, [property], propertyGroup, PropertyAccessKind.Unknown, [property].IsWritable(receiver, Me, isKnownTargetOfObjectMemberInitializer:=False), receiver, boundArguments, argumentInfo.DefaultArguments, hasErrors:=hasErrors) End If End Function Friend Sub WarnOnRecursiveAccess(propertyAccess As BoundPropertyAccess, accessKind As PropertyAccessKind, diagnostics As BindingDiagnosticBag) Dim [property] As PropertySymbol = propertyAccess.PropertySymbol If [property].ReducedFromDefinition Is Nothing AndAlso [property].ParameterCount = 0 AndAlso ([property].IsShared OrElse (propertyAccess.ReceiverOpt IsNot Nothing AndAlso propertyAccess.ReceiverOpt.Kind = BoundKind.MeReference)) Then Dim reportRecursiveCall As Boolean = False If [property].GetMethod Is ContainingMember Then If (accessKind And PropertyAccessKind.Get) <> 0 AndAlso (propertyAccess.AccessKind And PropertyAccessKind.Get) = 0 Then reportRecursiveCall = True End If ElseIf [property].SetMethod Is ContainingMember Then If (accessKind And PropertyAccessKind.Set) <> 0 AndAlso (propertyAccess.AccessKind And PropertyAccessKind.Set) = 0 Then reportRecursiveCall = True End If End If If reportRecursiveCall Then ReportDiagnostic(diagnostics, propertyAccess.Syntax, ERRID.WRN_RecursivePropertyCall, [property]) End If End If End Sub Friend Sub WarnOnRecursiveAccess(node As BoundExpression, accessKind As PropertyAccessKind, diagnostics As BindingDiagnosticBag) Select Case node.Kind Case BoundKind.XmlMemberAccess ' Nothing to do Case BoundKind.PropertyAccess WarnOnRecursiveAccess(DirectCast(node, BoundPropertyAccess), accessKind, diagnostics) Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Sub Private Function UpdateReceiverForExtensionMethodOrPropertyGroup( receiver As BoundExpression, targetType As TypeSymbol, thisParameterDefinition As ParameterSymbol, diagnostics As BindingDiagnosticBag ) As BoundExpression If receiver IsNot Nothing AndAlso receiver.IsValue AndAlso Not targetType.IsErrorType() AndAlso Not receiver.Type.IsErrorType() Then Dim oldReceiver As BoundExpression = receiver Dim useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics) receiver = PassArgument(receiver, Conversions.ClassifyConversion(receiver, targetType, Me, useSiteInfo), False, Conversions.ClassifyConversion(targetType, receiver.Type, useSiteInfo), targetType, thisParameterDefinition, diagnostics) diagnostics.Add(receiver, useSiteInfo) If oldReceiver.WasCompilerGenerated AndAlso receiver IsNot oldReceiver Then Select Case oldReceiver.Kind Case BoundKind.MeReference, BoundKind.WithLValueExpressionPlaceholder, BoundKind.WithRValueExpressionPlaceholder receiver.SetWasCompilerGenerated() End Select End If End If Return receiver End Function Private Function IsWellKnownTypeMember(memberId As WellKnownMember, method As MethodSymbol) As Boolean Return Compilation.GetWellKnownTypeMember(memberId) Is method End Function ''' <summary> ''' Optimizes some runtime library calls through replacing them with a literal if possible. ''' VB Spec 11.2 defines the following runtime functions as being constant: ''' - Microsoft.VisualBasic.Strings.ChrW ''' - Microsoft.VisualBasic.Strings.Chr, if the constant value is between 0 and 128 ''' - Microsoft.VisualBasic.Strings.AscW, if the constant string is not empty ''' - Microsoft.VisualBasic.Strings.Asc, if the constant string is not empty ''' </summary> ''' <param name="method">The method.</param> ''' <param name="arguments">The arguments of the method call.</param> ''' <param name="syntax">The syntax node for report errors.</param> ''' <param name="diagnostics">The diagnostics.</param> ''' <param name="hasErrors">Set to true if there are conversion errors (e.g. Asc("")). Otherwise it's not written to.</param> ''' <returns>The constant value that replaces this node, or nothing.</returns> Private Function OptimizeLibraryCall( method As MethodSymbol, arguments As ImmutableArray(Of BoundExpression), syntax As SyntaxNode, ByRef hasErrors As Boolean, diagnostics As BindingDiagnosticBag ) As ConstantValue ' cheapest way to filter out methods that do not match If arguments.Length = 1 AndAlso arguments(0).IsConstant AndAlso Not arguments(0).ConstantValueOpt.IsBad Then ' only continue checking if containing type is Microsoft.VisualBasic.Strings If Compilation.GetWellKnownType(WellKnownType.Microsoft_VisualBasic_Strings) IsNot method.ContainingType Then Return Nothing End If ' AscW(char) / AscW(String) ' all values can be optimized as a literal, except an empty string that produces a diagnostic If IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscWCharInt32, method) OrElse IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscWStringInt32, method) Then Dim argumentConstantValue = arguments(0).ConstantValueOpt Dim argumentValue As String If argumentConstantValue.IsNull Then argumentValue = String.Empty ElseIf argumentConstantValue.IsChar Then argumentValue = argumentConstantValue.CharValue Else Debug.Assert(argumentConstantValue.IsString()) argumentValue = argumentConstantValue.StringValue End If If argumentValue.IsEmpty() Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_CannotConvertValue2, argumentValue, method.ReturnType) hasErrors = True Return Nothing End If Return ConstantValue.Create(AscW(argumentValue)) End If ' ChrW ' for -32768 < value or value > 65535 we show a diagnostic If IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrWInt32Char, method) Then Dim argumentValue = arguments(0).ConstantValueOpt.Int32Value If argumentValue < -32768 OrElse argumentValue > 65535 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_CannotConvertValue2, argumentValue, method.ReturnType) hasErrors = True Return Nothing End If Return ConstantValue.Create(ChrW(argumentValue)) End If ' Asc(Char) / Asc(String) ' all values from 0 to 127 can be optimized to a literal. If IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscCharInt32, method) OrElse IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__AscStringInt32, method) Then Dim constantValue = arguments(0).ConstantValueOpt Dim argumentValue As String If constantValue.IsNull Then argumentValue = String.Empty ElseIf constantValue.IsChar Then argumentValue = constantValue.CharValue Else Debug.Assert(constantValue.IsString()) argumentValue = constantValue.StringValue End If If argumentValue.IsEmpty() Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_CannotConvertValue2, argumentValue, method.ReturnType) hasErrors = True Return Nothing End If ' we are only folding 7bit ASCII chars, so it's ok to use AscW here, although this is the Asc folding. Dim charValue = AscW(argumentValue) If charValue < 128 Then Return ConstantValue.Create(charValue) End If Return Nothing End If ' Chr ' values from 0 to 127 can be optimized as a literal ' for -32768 < value or value > 65535 we show a diagnostic If IsWellKnownTypeMember(WellKnownMember.Microsoft_VisualBasic_Strings__ChrInt32Char, method) Then Dim argumentValue = arguments(0).ConstantValueOpt.Int32Value If argumentValue >= 0 AndAlso argumentValue < 128 Then Return ConstantValue.Create(ChrW(argumentValue)) ElseIf argumentValue < -32768 OrElse argumentValue > 65535 Then ReportDiagnostic(diagnostics, syntax, ERRID.ERR_CannotConvertValue2, argumentValue, method.ReturnType) hasErrors = True Return Nothing End If End If End If Return Nothing End Function Private Function ReportOverloadResolutionFailureAndProduceBoundNode( node As SyntaxNode, group As BoundMethodOrPropertyGroup, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), <[In]> ByRef results As OverloadResolution.OverloadResolutionResult, diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional overrideCommonReturnType As TypeSymbol = Nothing, Optional queryMode As Boolean = False, Optional boundTypeExpression As BoundTypeExpression = Nothing, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing, Optional diagnosticLocationOpt As Location = Nothing ) As BoundExpression Return ReportOverloadResolutionFailureAndProduceBoundNode( node, group.ResultKind, boundArguments, argumentNames, results, diagnostics, callerInfoOpt, group, overrideCommonReturnType, queryMode, boundTypeExpression, representCandidateInDiagnosticsOpt, diagnosticLocationOpt) End Function Private Function ReportOverloadResolutionFailureAndProduceBoundNode( node As SyntaxNode, lookupResult As LookupResultKind, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), <[In]> ByRef results As OverloadResolution.OverloadResolutionResult, diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional groupOpt As BoundMethodOrPropertyGroup = Nothing, Optional overrideCommonReturnType As TypeSymbol = Nothing, Optional queryMode As Boolean = False, Optional boundTypeExpression As BoundTypeExpression = Nothing, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing, Optional diagnosticLocationOpt As Location = Nothing ) As BoundExpression Dim bestCandidates = ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult).GetInstance() Dim bestSymbols = ImmutableArray(Of Symbol).Empty Dim commonReturnType As TypeSymbol = GetSetOfTheBestCandidates(results, bestCandidates, bestSymbols) If overrideCommonReturnType IsNot Nothing Then commonReturnType = overrideCommonReturnType End If Dim result As BoundExpression = ReportOverloadResolutionFailureAndProduceBoundNode( node, lookupResult, bestCandidates, bestSymbols, commonReturnType, boundArguments, argumentNames, diagnostics, callerInfoOpt, groupOpt, Nothing, queryMode, boundTypeExpression, representCandidateInDiagnosticsOpt, diagnosticLocationOpt) bestCandidates.Free() Return result End Function Private Function ReportOverloadResolutionFailureAndProduceBoundNode( node As SyntaxNode, group As BoundMethodOrPropertyGroup, bestCandidates As ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult), bestSymbols As ImmutableArray(Of Symbol), commonReturnType As TypeSymbol, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional delegateSymbol As Symbol = Nothing, Optional queryMode As Boolean = False, Optional boundTypeExpression As BoundTypeExpression = Nothing, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing ) As BoundExpression Return ReportOverloadResolutionFailureAndProduceBoundNode( node, group.ResultKind, bestCandidates, bestSymbols, commonReturnType, boundArguments, argumentNames, diagnostics, callerInfoOpt, group, delegateSymbol, queryMode, boundTypeExpression, representCandidateInDiagnosticsOpt) End Function Public Shared Function GetLocationForOverloadResolutionDiagnostic(node As SyntaxNode, Optional groupOpt As BoundMethodOrPropertyGroup = Nothing) As Location Dim result As SyntaxNode If groupOpt IsNot Nothing Then If node.SyntaxTree Is groupOpt.Syntax.SyntaxTree AndAlso node.Span.Contains(groupOpt.Syntax.Span) Then result = groupOpt.Syntax If result Is node AndAlso (groupOpt.ReceiverOpt Is Nothing OrElse groupOpt.ReceiverOpt.Syntax Is result) Then Return result.GetLocation() End If Else Return node.GetLocation() End If ElseIf node.IsKind(SyntaxKind.InvocationExpression) Then result = If(DirectCast(node, InvocationExpressionSyntax).Expression, node) Else Return node.GetLocation() End If Select Case result.Kind Case SyntaxKind.QualifiedName Return DirectCast(result, QualifiedNameSyntax).Right.GetLocation() Case SyntaxKind.SimpleMemberAccessExpression If result.Parent IsNot Nothing AndAlso result.Parent.IsKind(SyntaxKind.AddressOfExpression) Then Return result.GetLocation() End If Return DirectCast(result, MemberAccessExpressionSyntax).Name.GetLocation() Case SyntaxKind.XmlElementAccessExpression, SyntaxKind.XmlDescendantAccessExpression, SyntaxKind.XmlAttributeAccessExpression Return DirectCast(result, XmlMemberAccessExpressionSyntax).Name.GetLocation() Case SyntaxKind.HandlesClauseItem Return DirectCast(result, HandlesClauseItemSyntax).EventMember.GetLocation() End Select Return result.GetLocation() End Function Private Function ReportOverloadResolutionFailureAndProduceBoundNode( node As SyntaxNode, lookupResult As LookupResultKind, bestCandidates As ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult), bestSymbols As ImmutableArray(Of Symbol), commonReturnType As TypeSymbol, boundArguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, Optional groupOpt As BoundMethodOrPropertyGroup = Nothing, Optional delegateSymbol As Symbol = Nothing, Optional queryMode As Boolean = False, Optional boundTypeExpression As BoundTypeExpression = Nothing, Optional representCandidateInDiagnosticsOpt As Symbol = Nothing, Optional diagnosticLocationOpt As Location = Nothing ) As BoundExpression Debug.Assert(commonReturnType IsNot Nothing AndAlso bestSymbols.Length > 0 AndAlso bestCandidates.Count >= bestSymbols.Length) Debug.Assert(groupOpt Is Nothing OrElse lookupResult = groupOpt.ResultKind) Dim state = OverloadResolution.CandidateAnalysisResultState.Count If bestCandidates.Count > 0 Then state = bestCandidates(0).State End If If boundArguments.IsDefault Then boundArguments = ImmutableArray(Of BoundExpression).Empty End If Dim singleCandidateAnalysisResult As OverloadResolution.CandidateAnalysisResult = Nothing Dim singleCandidate As OverloadResolution.Candidate = Nothing Dim allowUnexpandedParamArrayForm As Boolean = False Dim allowExpandedParamArrayForm As Boolean = False ' Figure out if we should report single candidate errors If bestSymbols.Length = 1 AndAlso bestCandidates.Count < 3 Then singleCandidateAnalysisResult = bestCandidates(0) singleCandidate = singleCandidateAnalysisResult.Candidate allowExpandedParamArrayForm = singleCandidateAnalysisResult.IsExpandedParamArrayForm allowUnexpandedParamArrayForm = Not allowExpandedParamArrayForm If bestCandidates.Count > 1 Then If bestCandidates(1).IsExpandedParamArrayForm Then allowExpandedParamArrayForm = True Else allowUnexpandedParamArrayForm = True End If End If End If If lookupResult = LookupResultKind.Inaccessible Then If singleCandidate IsNot Nothing Then ReportDiagnostic(diagnostics, If(groupOpt IsNot Nothing, groupOpt.Syntax, node), GetInaccessibleErrorInfo(singleCandidate.UnderlyingSymbol)) Else If Not queryMode Then ReportDiagnostic(diagnostics, If(groupOpt IsNot Nothing, groupOpt.Syntax, node), ERRID.ERR_NoViableOverloadCandidates1, bestSymbols(0).Name) End If ' Do not report more errors. GoTo ProduceBoundNode End If Else Debug.Assert(lookupResult = LookupResultKind.Good) End If If diagnosticLocationOpt Is Nothing Then diagnosticLocationOpt = GetLocationForOverloadResolutionDiagnostic(node, groupOpt) End If ' Report diagnostic according to the state of candidates Select Case state Case VisualBasic.OverloadResolution.CandidateAnalysisResultState.HasUseSiteError, OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata If singleCandidate IsNot Nothing Then ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocationOpt, lookupResult, singleCandidateAnalysisResult, boundArguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, True, False, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else ReportOverloadResolutionFailureForASetOfCandidates(node, diagnosticLocationOpt, lookupResult, ERRID.ERR_BadOverloadCandidates2, bestCandidates, boundArguments, argumentNames, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt) End If Case VisualBasic.OverloadResolution.CandidateAnalysisResultState.Ambiguous Dim candidate As Symbol = bestSymbols(0).OriginalDefinition Dim container As Symbol = candidate.ContainingSymbol ReportDiagnostic(diagnostics, diagnosticLocationOpt, ERRID.ERR_MetadataMembersAmbiguous3, candidate.Name, container.GetKindText(), container) Case OverloadResolution.CandidateAnalysisResultState.BadGenericArity Debug.Assert(groupOpt IsNot Nothing AndAlso groupOpt.Kind = BoundKind.MethodGroup) Dim mg = DirectCast(groupOpt, BoundMethodGroup) If singleCandidate IsNot Nothing Then Dim typeArguments = If(mg.TypeArgumentsOpt IsNot Nothing, mg.TypeArgumentsOpt.Arguments, ImmutableArray(Of TypeSymbol).Empty) If typeArguments.IsDefault Then typeArguments = ImmutableArray(Of TypeSymbol).Empty End If Dim singleSymbol As Symbol = singleCandidate.UnderlyingSymbol Dim isExtension As Boolean = singleCandidate.IsExtensionMethod If singleCandidate.Arity < typeArguments.Length Then If isExtension Then ReportDiagnostic(diagnostics, mg.TypeArgumentsOpt.Syntax, If(singleCandidate.Arity = 0, ERRID.ERR_TypeOrMemberNotGeneric2, ERRID.ERR_TooManyGenericArguments2), singleSymbol, singleSymbol.ContainingType) Else ReportDiagnostic(diagnostics, mg.TypeArgumentsOpt.Syntax, If(singleCandidate.Arity = 0, ERRID.ERR_TypeOrMemberNotGeneric1, ERRID.ERR_TooManyGenericArguments1), singleSymbol) End If Else Debug.Assert(singleCandidate.Arity > typeArguments.Length) If isExtension Then ReportDiagnostic(diagnostics, mg.TypeArgumentsOpt.Syntax, ERRID.ERR_TooFewGenericArguments2, singleSymbol, singleSymbol.ContainingType) Else ReportDiagnostic(diagnostics, mg.TypeArgumentsOpt.Syntax, ERRID.ERR_TooFewGenericArguments1, singleSymbol) End If End If Else ReportDiagnostic(diagnostics, diagnosticLocationOpt, ERRID.ERR_NoTypeArgumentCountOverloadCand1, CustomSymbolDisplayFormatter.ShortErrorName(bestSymbols(0))) End If Case OverloadResolution.CandidateAnalysisResultState.ArgumentCountMismatch If node.Kind = SyntaxKind.IdentifierName AndAlso node.Parent IsNot Nothing AndAlso node.Parent.Kind = SyntaxKind.NamedFieldInitializer AndAlso groupOpt IsNot Nothing AndAlso groupOpt.Kind = BoundKind.PropertyGroup Then ' report special diagnostics for a failed overload resolution because all available properties ' require arguments in case this method was called while binding a object member initializer. ReportDiagnostic(diagnostics, diagnosticLocationOpt, If(singleCandidate IsNot Nothing, ERRID.ERR_ParameterizedPropertyInAggrInit1, ERRID.ERR_NoZeroCountArgumentInitCandidates1), CustomSymbolDisplayFormatter.ShortErrorName(bestSymbols(0))) Else If singleCandidate IsNot Nothing AndAlso (Not queryMode OrElse singleCandidate.ParameterCount <= boundArguments.Length) Then ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocationOpt, lookupResult, singleCandidateAnalysisResult, boundArguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, True, False, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else ReportDiagnostic(diagnostics, diagnosticLocationOpt, ERRID.ERR_NoArgumentCountOverloadCandidates1, CustomSymbolDisplayFormatter.ShortErrorName(bestSymbols(0))) End If End If Case OverloadResolution.CandidateAnalysisResultState.ArgumentMismatch, OverloadResolution.CandidateAnalysisResultState.GenericConstraintsViolated Dim haveBadArgument As Boolean = False For i As Integer = 0 To boundArguments.Length - 1 Step 1 Dim type = boundArguments(i).Type If boundArguments(i).HasErrors OrElse (type IsNot Nothing AndAlso type.IsErrorType()) Then haveBadArgument = True Exit For End If Next If Not haveBadArgument Then If singleCandidate IsNot Nothing Then ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocationOpt, lookupResult, singleCandidateAnalysisResult, boundArguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, True, False, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else ReportOverloadResolutionFailureForASetOfCandidates(node, diagnosticLocationOpt, lookupResult, If(delegateSymbol Is Nothing, ERRID.ERR_NoCallableOverloadCandidates2, ERRID.ERR_DelegateBindingFailure3), bestCandidates, boundArguments, argumentNames, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt) End If End If Case OverloadResolution.CandidateAnalysisResultState.TypeInferenceFailed If singleCandidate IsNot Nothing Then ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocationOpt, lookupResult, singleCandidateAnalysisResult, boundArguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, True, False, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=representCandidateInDiagnosticsOpt) Else ReportOverloadResolutionFailureForASetOfCandidates(node, diagnosticLocationOpt, lookupResult, ERRID.ERR_NoCallableOverloadCandidates2, bestCandidates, boundArguments, argumentNames, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt) End If Case OverloadResolution.CandidateAnalysisResultState.Applicable ' it is only possible to get overloading failure with a single candidate ' if we have a paramarray with equally specific virtual signatures Debug.Assert(singleCandidate Is Nothing OrElse singleCandidate.ParameterCount <> 0 AndAlso singleCandidate.Parameters(singleCandidate.ParameterCount - 1).IsParamArray) If bestCandidates(0).RequiresNarrowingConversion Then ReportOverloadResolutionFailureForASetOfCandidates(node, diagnosticLocationOpt, lookupResult, If(delegateSymbol Is Nothing, ERRID.ERR_NoNonNarrowingOverloadCandidates2, ERRID.ERR_DelegateBindingFailure3), bestCandidates, boundArguments, argumentNames, diagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt) Else ReportUnspecificProcedures(diagnosticLocationOpt, bestSymbols, diagnostics, (delegateSymbol IsNot Nothing)) End If Case Else ' Unexpected Throw ExceptionUtilities.UnexpectedValue(state) End Select ProduceBoundNode: Dim childBoundNodes As ImmutableArray(Of BoundExpression) If boundArguments.IsEmpty AndAlso boundTypeExpression Is Nothing Then If groupOpt Is Nothing Then childBoundNodes = ImmutableArray(Of BoundExpression).Empty Else childBoundNodes = ImmutableArray.Create(Of BoundExpression)(groupOpt) End If Else Dim builder = ArrayBuilder(Of BoundExpression).GetInstance() If groupOpt IsNot Nothing Then builder.Add(groupOpt) End If If Not boundArguments.IsEmpty Then builder.AddRange(boundArguments) End If If boundTypeExpression IsNot Nothing Then builder.Add(boundTypeExpression) End If childBoundNodes = builder.ToImmutableAndFree() End If Dim resultKind = LookupResultKind.OverloadResolutionFailure If lookupResult < resultKind Then resultKind = lookupResult End If Return New BoundBadExpression(node, resultKind, bestSymbols, childBoundNodes, commonReturnType, hasErrors:=True) End Function ''' <summary> '''Figure out the set of best candidates in the following preference order: ''' 1) Applicable ''' 2) ArgumentMismatch, GenericConstraintsViolated ''' 3) TypeInferenceFailed ''' 4) ArgumentCountMismatch ''' 5) BadGenericArity ''' 6) Ambiguous ''' 7) HasUseSiteError ''' 8) HasUnsupportedMetadata ''' ''' Also return the set of unique symbols behind the set. ''' ''' Returns type symbol for the common type, if any. ''' Otherwise returns ErrorTypeSymbol.UnknownResultType. ''' </summary> Private Shared Function GetSetOfTheBestCandidates( ByRef results As OverloadResolution.OverloadResolutionResult, bestCandidates As ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult), ByRef bestSymbols As ImmutableArray(Of Symbol) ) As TypeSymbol Const Applicable = OverloadResolution.CandidateAnalysisResultState.Applicable Const ArgumentMismatch = OverloadResolution.CandidateAnalysisResultState.ArgumentMismatch Const GenericConstraintsViolated = OverloadResolution.CandidateAnalysisResultState.GenericConstraintsViolated Const TypeInferenceFailed = OverloadResolution.CandidateAnalysisResultState.TypeInferenceFailed Const ArgumentCountMismatch = OverloadResolution.CandidateAnalysisResultState.ArgumentCountMismatch Const BadGenericArity = OverloadResolution.CandidateAnalysisResultState.BadGenericArity Const Ambiguous = OverloadResolution.CandidateAnalysisResultState.Ambiguous Const HasUseSiteError = OverloadResolution.CandidateAnalysisResultState.HasUseSiteError Const HasUnsupportedMetadata = OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata Dim preference(OverloadResolution.CandidateAnalysisResultState.Count - 1) As Integer preference(Applicable) = 1 preference(ArgumentMismatch) = 2 preference(GenericConstraintsViolated) = 2 preference(TypeInferenceFailed) = 3 preference(ArgumentCountMismatch) = 4 preference(BadGenericArity) = 5 preference(Ambiguous) = 6 preference(HasUseSiteError) = 7 preference(HasUnsupportedMetadata) = 8 For Each candidate In results.Candidates Dim prefNew = preference(candidate.State) If prefNew <> 0 Then If bestCandidates.Count = 0 Then bestCandidates.Add(candidate) Else Dim prefOld = preference(bestCandidates(0).State) If prefNew = prefOld Then bestCandidates.Add(candidate) ElseIf prefNew < prefOld Then bestCandidates.Clear() bestCandidates.Add(candidate) End If End If End If Next ' Collect unique best symbols. Dim bestSymbolsBuilder = ArrayBuilder(Of Symbol).GetInstance(bestCandidates.Count) Dim commonReturnType As TypeSymbol = Nothing If bestCandidates.Count = 1 Then ' For multiple candidates we never pick common type that refers to method's type parameter ' because each method has distinct type parameters. For single candidate case we need to ' ensure this explicitly. Dim underlyingSymbol As Symbol = bestCandidates(0).Candidate.UnderlyingSymbol bestSymbolsBuilder.Add(underlyingSymbol) commonReturnType = bestCandidates(0).Candidate.ReturnType If underlyingSymbol.Kind = SymbolKind.Method Then Dim method = DirectCast(underlyingSymbol, MethodSymbol) If method.IsGenericMethod AndAlso commonReturnType.ReferencesMethodsTypeParameter(method) Then Select Case CInt(bestCandidates(0).State) Case TypeInferenceFailed, HasUseSiteError, HasUnsupportedMetadata, BadGenericArity, ArgumentCountMismatch commonReturnType = Nothing End Select End If End If Else For i As Integer = 0 To bestCandidates.Count - 1 Step 1 If i = 0 OrElse Not bestSymbolsBuilder(bestSymbolsBuilder.Count - 1).Equals(bestCandidates(i).Candidate.UnderlyingSymbol) Then bestSymbolsBuilder.Add(bestCandidates(i).Candidate.UnderlyingSymbol) Dim returnType = bestCandidates(i).Candidate.ReturnType If commonReturnType Is Nothing Then commonReturnType = returnType ElseIf commonReturnType IsNot ErrorTypeSymbol.UnknownResultType AndAlso Not commonReturnType.IsSameTypeIgnoringAll(returnType) Then commonReturnType = ErrorTypeSymbol.UnknownResultType End If End If Next End If bestSymbols = bestSymbolsBuilder.ToImmutableAndFree() Return If(commonReturnType, ErrorTypeSymbol.UnknownResultType) End Function Private Shared Sub ReportUnspecificProcedures( diagnosticLocation As Location, bestSymbols As ImmutableArray(Of Symbol), diagnostics As BindingDiagnosticBag, isDelegateContext As Boolean ) Dim diagnosticInfos = ArrayBuilder(Of DiagnosticInfo).GetInstance(bestSymbols.Length) Dim notMostSpecificMessage = ErrorFactory.ErrorInfo(ERRID.ERR_NotMostSpecificOverload) Dim withContainingTypeInDiagnostics As Boolean = False If Not bestSymbols(0).IsReducedExtensionMethod Then Dim container As NamedTypeSymbol = bestSymbols(0).ContainingType For i As Integer = 1 To bestSymbols.Length - 1 Step 1 If Not TypeSymbol.Equals(bestSymbols(i).ContainingType, container, TypeCompareKind.ConsiderEverything) Then withContainingTypeInDiagnostics = True End If Next End If For i As Integer = 0 To bestSymbols.Length - 1 Step 1 ' in delegate context we just output for each candidates ' BC30794: No accessible 'goo' is most specific: ' Public Sub goo(p As Integer) ' Public Sub goo(p As Integer) ' ' in other contexts we give more information, e.g. ' BC30794: No accessible 'goo' is most specific: ' Public Sub goo(p As Integer): <reason> ' Public Sub goo(p As Integer): <reason> Dim bestSymbol As Symbol = bestSymbols(i) Dim bestSymbolIsExtension As Boolean = bestSymbol.IsReducedExtensionMethod If isDelegateContext Then If bestSymbolIsExtension Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOverloadCandidate2, bestSymbol, bestSymbol.ContainingType)) ElseIf withContainingTypeInDiagnostics Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate1, CustomSymbolDisplayFormatter.WithContainingType(bestSymbol))) Else diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate1, bestSymbol)) End If Else If bestSymbolIsExtension Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOverloadCandidate3, bestSymbol, bestSymbol.ContainingType, notMostSpecificMessage)) ElseIf withContainingTypeInDiagnostics Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate2, CustomSymbolDisplayFormatter.WithContainingType(bestSymbol), notMostSpecificMessage)) Else diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate2, bestSymbol, notMostSpecificMessage)) End If End If Next ReportDiagnostic(diagnostics, diagnosticLocation, ErrorFactory.ErrorInfo(If(isDelegateContext, ERRID.ERR_AmbiguousDelegateBinding2, ERRID.ERR_NoMostSpecificOverload2), CustomSymbolDisplayFormatter.ShortErrorName(bestSymbols(0)), New CompoundDiagnosticInfo(diagnosticInfos.ToArrayAndFree()) )) End Sub Private Sub ReportOverloadResolutionFailureForASetOfCandidates( node As SyntaxNode, diagnosticLocation As Location, lookupResult As LookupResultKind, errorNo As ERRID, candidates As ArrayBuilder(Of OverloadResolution.CandidateAnalysisResult), arguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), diagnostics As BindingDiagnosticBag, delegateSymbol As Symbol, queryMode As Boolean, callerInfoOpt As SyntaxNode ) Dim diagnosticPerSymbol = ArrayBuilder(Of KeyValuePair(Of Symbol, ImmutableBindingDiagnostic(Of AssemblySymbol))).GetInstance(candidates.Count) If arguments.IsDefault Then arguments = ImmutableArray(Of BoundExpression).Empty End If For i As Integer = 0 To candidates.Count - 1 Step 1 ' See if we need to consider both expanded and unexpanded version of the same method. ' We want to report only one set of errors in this case. ' Note, that, when OverloadResolution collects candidates expanded form always ' immediately follows unexpanded form, if both should be considered. Dim allowExpandedParamArrayForm As Boolean = candidates(i).IsExpandedParamArrayForm Dim allowUnexpandedParamArrayForm As Boolean = Not allowExpandedParamArrayForm If allowUnexpandedParamArrayForm AndAlso i + 1 < candidates.Count AndAlso candidates(i + 1).IsExpandedParamArrayForm AndAlso candidates(i + 1).Candidate.UnderlyingSymbol.Equals(candidates(i).Candidate.UnderlyingSymbol) Then allowExpandedParamArrayForm = True i += 1 End If Dim candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics) ' Collect diagnostic for this candidate ReportOverloadResolutionFailureForASingleCandidate(node, diagnosticLocation, lookupResult, candidates(i), arguments, argumentNames, allowUnexpandedParamArrayForm, allowExpandedParamArrayForm, False, errorNo = If(delegateSymbol Is Nothing, ERRID.ERR_NoNonNarrowingOverloadCandidates2, ERRID.ERR_DelegateBindingFailure3), candidateDiagnostics, delegateSymbol:=delegateSymbol, queryMode:=queryMode, callerInfoOpt:=callerInfoOpt, representCandidateInDiagnosticsOpt:=Nothing) diagnosticPerSymbol.Add(KeyValuePairUtil.Create(candidates(i).Candidate.UnderlyingSymbol, candidateDiagnostics.ToReadOnlyAndFree())) Next ' See if there are errors that are reported for each candidate at the same location within a lambda argument. ' Report them and don't report remaining diagnostics for each symbol separately. If Not ReportCommonErrorsFromLambdas(diagnosticPerSymbol, arguments, diagnostics) Then Dim diagnosticInfos = ArrayBuilder(Of DiagnosticInfo).GetInstance(candidates.Count) For i As Integer = 0 To diagnosticPerSymbol.Count - 1 Dim symbol = diagnosticPerSymbol(i).Key Dim isExtension As Boolean = symbol.IsReducedExtensionMethod() Dim sealedCandidateDiagnostics = diagnosticPerSymbol(i).Value.Diagnostics ' When reporting errors for an AddressOf, Dev 10 shows different error messages depending on how many ' errors there are per candidate. ' One narrowing error will be shown like: ' 'Public Sub goo6(p As Integer, p2 As Byte)': Option Strict On disallows implicit conversions from 'Integer' to 'Byte'. ' More than one narrowing issues in the parameters are abbreviated with: ' 'Public Sub goo6(p As Byte, p2 As Byte)': Method does not have a signature compatible with the delegate. If delegateSymbol Is Nothing OrElse Not sealedCandidateDiagnostics.Skip(1).Any() Then If isExtension Then For Each iDiagnostic In sealedCandidateDiagnostics diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOverloadCandidate3, symbol, symbol.ContainingType, DirectCast(iDiagnostic, DiagnosticWithInfo).Info)) Next Else For Each iDiagnostic In sealedCandidateDiagnostics Dim msg = VisualBasicDiagnosticFormatter.Instance.Format(iDiagnostic.WithLocation(Location.None)) diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate2, symbol, DirectCast(iDiagnostic, DiagnosticWithInfo).Info)) Next End If Else If isExtension Then diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionMethodOverloadCandidate3, symbol, symbol.ContainingType, ErrorFactory.ErrorInfo(ERRID.ERR_DelegateBindingMismatch, symbol))) Else diagnosticInfos.Add(ErrorFactory.ErrorInfo(ERRID.ERR_OverloadCandidate2, symbol, ErrorFactory.ErrorInfo(ERRID.ERR_DelegateBindingMismatch, symbol))) End If End If Next Dim diagnosticCompoundInfos() As DiagnosticInfo = diagnosticInfos.ToArrayAndFree() If delegateSymbol Is Nothing Then ReportDiagnostic(diagnostics, diagnosticLocation, ErrorFactory.ErrorInfo(errorNo, CustomSymbolDisplayFormatter.ShortErrorName(candidates(0).Candidate.UnderlyingSymbol), New CompoundDiagnosticInfo(diagnosticCompoundInfos))) Else ReportDiagnostic(diagnostics, diagnosticLocation, ErrorFactory.ErrorInfo(errorNo, CustomSymbolDisplayFormatter.ShortErrorName(candidates(0).Candidate.UnderlyingSymbol), CustomSymbolDisplayFormatter.DelegateSignature(delegateSymbol), New CompoundDiagnosticInfo(diagnosticCompoundInfos))) End If End If diagnosticPerSymbol.Free() End Sub Private Shared Function ReportCommonErrorsFromLambdas( diagnosticPerSymbol As ArrayBuilder(Of KeyValuePair(Of Symbol, ImmutableBindingDiagnostic(Of AssemblySymbol))), arguments As ImmutableArray(Of BoundExpression), diagnostics As BindingDiagnosticBag ) As Boolean Dim haveCommonErrors As Boolean = False For Each diagnostic In diagnosticPerSymbol(0).Value.Diagnostics If diagnostic.Severity <> DiagnosticSeverity.Error Then Continue For End If For Each argument In arguments If argument.Syntax.SyntaxTree Is diagnostic.Location.SourceTree AndAlso argument.Kind = BoundKind.UnboundLambda Then If argument.Syntax.Span.Contains(diagnostic.Location.SourceSpan) Then Dim common As Boolean = True For i As Integer = 1 To diagnosticPerSymbol.Count - 1 If Not diagnosticPerSymbol(i).Value.Diagnostics.Contains(diagnostic) Then common = False Exit For End If Next If common Then haveCommonErrors = True diagnostics.Add(diagnostic) End If Exit For End If End If Next Next Return haveCommonErrors End Function ''' <summary> ''' Should be kept in sync with OverloadResolution.MatchArguments. Anything that ''' OverloadResolution.MatchArguments flags as an error should be detected by ''' this function as well. ''' </summary> Private Sub ReportOverloadResolutionFailureForASingleCandidate( node As SyntaxNode, diagnosticLocation As Location, lookupResult As LookupResultKind, ByRef candidateAnalysisResult As OverloadResolution.CandidateAnalysisResult, arguments As ImmutableArray(Of BoundExpression), argumentNames As ImmutableArray(Of String), allowUnexpandedParamArrayForm As Boolean, allowExpandedParamArrayForm As Boolean, includeMethodNameInErrorMessages As Boolean, reportNarrowingConversions As Boolean, diagnostics As BindingDiagnosticBag, delegateSymbol As Symbol, queryMode As Boolean, callerInfoOpt As SyntaxNode, representCandidateInDiagnosticsOpt As Symbol ) Dim candidate As OverloadResolution.Candidate = candidateAnalysisResult.Candidate If arguments.IsDefault Then arguments = ImmutableArray(Of BoundExpression).Empty End If Debug.Assert(argumentNames.IsDefaultOrEmpty OrElse (argumentNames.Length > 0 AndAlso argumentNames.Length = arguments.Length)) Debug.Assert(allowUnexpandedParamArrayForm OrElse allowExpandedParamArrayForm) If candidateAnalysisResult.State = VisualBasic.OverloadResolution.CandidateAnalysisResultState.HasUseSiteError OrElse candidateAnalysisResult.State = VisualBasic.OverloadResolution.CandidateAnalysisResultState.HasUnsupportedMetadata Then If lookupResult <> LookupResultKind.Inaccessible Then Debug.Assert(lookupResult = LookupResultKind.Good) ReportUseSite(diagnostics, diagnosticLocation, candidate.UnderlyingSymbol.GetUseSiteInfo()) End If Return End If ' To simplify following code If Not argumentNames.IsDefault AndAlso argumentNames.Length = 0 Then argumentNames = Nothing End If Dim parameterToArgumentMap As ArrayBuilder(Of Integer) = ArrayBuilder(Of Integer).GetInstance(candidate.ParameterCount, -1) Dim paramArrayItems As ArrayBuilder(Of Integer) = ArrayBuilder(Of Integer).GetInstance() Try '§11.8.2 Applicable Methods '1. First, match each positional argument in order to the list of method parameters. 'If there are more positional arguments than parameters and the last parameter is not a paramarray, the method is not applicable. 'Otherwise, the paramarray parameter is expanded with parameters of the paramarray element type to match the number of positional arguments. 'If a positional argument is omitted, the method is not applicable. ' !!! Not sure about the last sentence: "If a positional argument is omitted, the method is not applicable." ' !!! Dev10 allows omitting positional argument as long as the corresponding parameter is optional. Dim positionalArguments As Integer = 0 Dim paramIndex = 0 Dim someArgumentsBad As Boolean = False Dim someParamArrayArgumentsBad As Boolean = False Dim seenOutOfPositionNamedArgIndex As Integer = -1 Dim candidateSymbol As Symbol = candidate.UnderlyingSymbol Dim candidateIsExtension As Boolean = candidate.IsExtensionMethod For i As Integer = 0 To arguments.Length - 1 Step 1 ' A named argument which is used in-position counts as positional If Not argumentNames.IsDefault AndAlso argumentNames(i) IsNot Nothing Then If Not candidate.TryGetNamedParamIndex(argumentNames(i), paramIndex) Then Exit For End If If paramIndex <> i Then ' all remaining arguments must be named seenOutOfPositionNamedArgIndex = i Exit For End If If paramIndex = candidate.ParameterCount - 1 AndAlso candidate.Parameters(paramIndex).IsParamArray Then Exit For End If Debug.Assert(parameterToArgumentMap(paramIndex) = -1) End If If paramIndex = candidate.ParameterCount Then If Not someArgumentsBad Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, arguments(i).Syntax, ERRID.ERR_TooManyArgs) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, arguments(i).Syntax, ERRID.ERR_TooManyArgs2, candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, arguments(i).Syntax, ERRID.ERR_TooManyArgs1, If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True End If ElseIf paramIndex = candidate.ParameterCount - 1 AndAlso candidate.Parameters(paramIndex).IsParamArray Then ' Collect ParamArray arguments While i < arguments.Length If Not argumentNames.IsDefault AndAlso argumentNames(i) IsNot Nothing Then ' First named argument Continue For End If If arguments(i).Kind = BoundKind.OmittedArgument Then ReportDiagnostic(diagnostics, arguments(i).Syntax, ERRID.ERR_OmittedParamArrayArgument) someParamArrayArgumentsBad = True Else paramArrayItems.Add(i) End If positionalArguments += 1 i += 1 End While Exit For Else parameterToArgumentMap(paramIndex) = i paramIndex += 1 End If positionalArguments += 1 Next Dim skippedSomeArguments As Boolean = False '§11.8.2 Applicable Methods '2. Next, match each named argument to a parameter with the given name. 'If one of the named arguments fails to match, matches a paramarray parameter, 'or matches an argument already matched with another positional or named argument, 'the method is not applicable. For i As Integer = positionalArguments To arguments.Length - 1 Step 1 Debug.Assert(argumentNames(i) Is Nothing OrElse argumentNames(i).Length > 0) If argumentNames(i) Is Nothing Then ' Unnamed argument follows out-of-position named arguments If Not someArgumentsBad Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(seenOutOfPositionNamedArgIndex).Syntax), ERRID.ERR_BadNonTrailingNamedArgument, argumentNames(seenOutOfPositionNamedArgIndex)) End If Return End If If Not candidate.TryGetNamedParamIndex(argumentNames(i), paramIndex) Then ' ERRID_NamedParamNotFound1 ' ERRID_NamedParamNotFound2 If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedParamNotFound1, argumentNames(i)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedParamNotFound3, argumentNames(i), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedParamNotFound2, argumentNames(i), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True Continue For End If If paramIndex = candidate.ParameterCount - 1 AndAlso candidate.Parameters(paramIndex).IsParamArray Then ' ERRID_NamedParamArrayArgument ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedParamArrayArgument) someArgumentsBad = True Continue For End If If parameterToArgumentMap(paramIndex) <> -1 AndAlso arguments(parameterToArgumentMap(paramIndex)).Kind <> BoundKind.OmittedArgument Then ' ERRID_NamedArgUsedTwice1 ' ERRID_NamedArgUsedTwice2 ' ERRID_NamedArgUsedTwice3 If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgUsedTwice1, argumentNames(i)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgUsedTwice3, argumentNames(i), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgUsedTwice2, argumentNames(i), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True Continue For End If ' It is an error for a named argument to specify ' a value for an explicitly omitted positional argument. If paramIndex < positionalArguments Then 'ERRID_NamedArgAlsoOmitted1 'ERRID_NamedArgAlsoOmitted2 'ERRID_NamedArgAlsoOmitted3 If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgAlsoOmitted1, argumentNames(i)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgAlsoOmitted3, argumentNames(i), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, GetNamedArgumentIdentifier(arguments(i).Syntax), ERRID.ERR_NamedArgAlsoOmitted2, argumentNames(i), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True End If parameterToArgumentMap(paramIndex) = i Next ' Check whether type inference failed If candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt IsNot Nothing Then diagnostics.AddRange(candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt) End If If candidate.IsGeneric AndAlso candidateAnalysisResult.State = OverloadResolution.CandidateAnalysisResultState.TypeInferenceFailed Then ' Bug 122092: AddressOf doesn't want detailed info on which parameters could not be ' inferred, just report the general type inference failed message in this case. If delegateSymbol IsNot Nothing Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_DelegateBindingTypeInferenceFails) Return End If If Not candidateAnalysisResult.SomeInferenceFailed Then Dim reportedAnError As Boolean = False For i As Integer = 0 To candidate.Arity - 1 Step 1 If candidateAnalysisResult.NotInferredTypeArguments(i) Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_UnboundTypeParam1, candidate.TypeParameters(i)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_UnboundTypeParam3, candidate.TypeParameters(i), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_UnboundTypeParam2, candidate.TypeParameters(i), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If reportedAnError = True End If Next If reportedAnError Then Return End If End If Dim inferenceErrorReasons As InferenceErrorReasons = candidateAnalysisResult.InferenceErrorReasons If (inferenceErrorReasons And InferenceErrorReasons.Ambiguous) <> 0 Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitAmbiguous1, ERRID.ERR_TypeInferenceFailureAmbiguous1)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitAmbiguous3, ERRID.ERR_TypeInferenceFailureAmbiguous3), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitAmbiguous2, ERRID.ERR_TypeInferenceFailureAmbiguous2), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If ElseIf (inferenceErrorReasons And InferenceErrorReasons.NoBest) <> 0 Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitNoBest1, ERRID.ERR_TypeInferenceFailureNoBest1)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitNoBest3, ERRID.ERR_TypeInferenceFailureNoBest3), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicitNoBest2, ERRID.ERR_TypeInferenceFailureNoBest2), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If Else If candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt IsNot Nothing AndAlso candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt.HasAnyResolvedErrors Then ' Already reported some errors, let's not report a general inference error Return End If If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicit1, ERRID.ERR_TypeInferenceFailure1)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicit3, ERRID.ERR_TypeInferenceFailure3), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, If(queryMode, ERRID.ERR_TypeInferenceFailureNoExplicit2, ERRID.ERR_TypeInferenceFailure2), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If End If Return End If ' Check generic constraints for method type arguments. If candidateAnalysisResult.State = OverloadResolution.CandidateAnalysisResultState.GenericConstraintsViolated Then Debug.Assert(candidate.IsGeneric) Debug.Assert(candidate.UnderlyingSymbol.Kind = SymbolKind.Method) Dim method = DirectCast(candidate.UnderlyingSymbol, MethodSymbol) ' TODO: Dev10 uses the location of the type parameter or argument that ' violated the constraint, rather than the entire invocation expression. Dim succeeded = method.CheckConstraints(diagnosticLocation, diagnostics, template:=GetNewCompoundUseSiteInfo(diagnostics)) Debug.Assert(Not succeeded) Return End If If candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt IsNot Nothing AndAlso candidateAnalysisResult.TypeArgumentInferenceDiagnosticsOpt.HasAnyErrors Then Return End If ' Traverse the parameters, converting corresponding arguments ' as appropriate. Dim argIndex As Integer Dim candidateIsAProperty As Boolean = (candidateSymbol.Kind = SymbolKind.Property) For paramIndex = 0 To candidate.ParameterCount - 1 Step 1 Dim param As ParameterSymbol = candidate.Parameters(paramIndex) Dim isByRef As Boolean = param.IsByRef Dim targetType As TypeSymbol = param.Type Dim argument As BoundExpression = Nothing If param.IsParamArray AndAlso paramIndex = candidate.ParameterCount - 1 Then If targetType.Kind <> SymbolKind.ArrayType Then If targetType.Kind <> SymbolKind.ErrorType Then ' ERRID_ParamArrayWrongType ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_ParamArrayWrongType) End If someArgumentsBad = True Continue For ElseIf someParamArrayArgumentsBad Then Continue For End If If paramArrayItems.Count = 1 Then Dim paramArrayArgument = arguments(paramArrayItems(0)) '§11.8.2 Applicable Methods 'If the conversion from the type of the argument expression to the paramarray type is narrowing, 'then the method is only applicable in its expanded form. Dim arrayConversion As KeyValuePair(Of ConversionKind, MethodSymbol) = Nothing If allowUnexpandedParamArrayForm AndAlso Not (Not paramArrayArgument.HasErrors AndAlso OverloadResolution.CanPassToParamArray(paramArrayArgument, targetType, arrayConversion, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded)) Then allowUnexpandedParamArrayForm = False End If '§11.8.2 Applicable Methods 'If the argument expression is the literal Nothing, then the method is only applicable in its unexpanded form If allowExpandedParamArrayForm AndAlso paramArrayArgument.IsNothingLiteral() Then allowExpandedParamArrayForm = False End If Else ' Unexpanded form is not applicable: there are either more than one value or no values. If Not allowExpandedParamArrayForm Then If paramArrayItems.Count = 0 Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument1, CustomSymbolDisplayFormatter.ShortErrorName(param)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument3, CustomSymbolDisplayFormatter.ShortErrorName(param), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument2, CustomSymbolDisplayFormatter.ShortErrorName(param), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If Else If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_TooManyArgs) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_TooManyArgs2, candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_TooManyArgs1, If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If End If someArgumentsBad = True Continue For End If allowUnexpandedParamArrayForm = False End If If allowUnexpandedParamArrayForm Then argument = arguments(paramArrayItems(0)) ReportByValConversionErrors(param, argument, targetType, reportNarrowingConversions, diagnostics) ElseIf allowExpandedParamArrayForm Then Dim arrayType = DirectCast(targetType, ArrayTypeSymbol) If Not arrayType.IsSZArray Then ' ERRID_ParamArrayWrongType ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_ParamArrayWrongType) someArgumentsBad = True Continue For End If Dim arrayElementType = arrayType.ElementType For i As Integer = 0 To paramArrayItems.Count - 1 Step 1 argument = arguments(paramArrayItems(i)) ReportByValConversionErrors(param, argument, arrayElementType, reportNarrowingConversions, diagnostics) Next Else Debug.Assert(paramArrayItems.Count = 1) Dim paramArrayArgument = arguments(paramArrayItems(0)) ReportDiagnostic(diagnostics, paramArrayArgument.Syntax, ERRID.ERR_ParamArrayArgumentMismatch) End If Continue For End If argIndex = parameterToArgumentMap(paramIndex) argument = If(argIndex = -1, Nothing, arguments(argIndex)) ' Argument nothing when the argument syntax is missing or BoundKind.OmittedArgument when the argument list contains commas ' for the missing syntax so we have to test for both. If argument Is Nothing OrElse argument.Kind = BoundKind.OmittedArgument Then If argument Is Nothing AndAlso skippedSomeArguments Then someArgumentsBad = True Continue For End If 'See Section 3 of §11.8.2 Applicable Methods ' Deal with Optional arguments ' Need to handle optional arguments here, there could be conversion errors, etc. ' reducedExtensionReceiverOpt is used to determine the default value of a CallerArgumentExpression when it refers to the first parameter of an extension method. ' Don't bother with correctly determining the correct value for this case since we're in an error case anyway. argument = GetArgumentForParameterDefaultValue(param, node, diagnostics, callerInfoOpt, parameterToArgumentMap, arguments, reducedExtensionReceiverOpt:=Nothing) If argument Is Nothing Then If Not includeMethodNameInErrorMessages Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument1, CustomSymbolDisplayFormatter.ShortErrorName(param)) ElseIf candidateIsExtension Then ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument3, CustomSymbolDisplayFormatter.ShortErrorName(param), candidateSymbol, candidateSymbol.ContainingType) Else ReportDiagnostic(diagnostics, diagnosticLocation, ERRID.ERR_OmittedArgument2, CustomSymbolDisplayFormatter.ShortErrorName(param), If(representCandidateInDiagnosticsOpt, candidateSymbol)) End If someArgumentsBad = True Continue For End If End If Debug.Assert(Not isByRef OrElse param.IsExplicitByRef OrElse targetType.IsStringType()) ' Arguments for properties are always passed with ByVal semantics. Even if ' parameter in metadata is defined ByRef, we always pass corresponding argument ' through a temp without copy-back. Unlike with method calls, we rely on CodeGen ' to introduce the temp (easy to do since there is no copy-back around it), ' this allows us to keep the BoundPropertyAccess node simpler and allows to avoid ' A LOT of complexity in UseTwiceRewriter, which we would otherwise have around ' the temps. ' Non-string arguments for implicitly ByRef string parameters of Declare functions ' are passed through a temp without copy-back. If isByRef AndAlso Not candidateIsAProperty AndAlso (param.IsExplicitByRef OrElse (argument.Type IsNot Nothing AndAlso argument.Type.IsStringType())) Then ReportByRefConversionErrors(candidate, param, argument, targetType, reportNarrowingConversions, diagnostics, diagnosticNode:=node, delegateSymbol:=delegateSymbol) Else ReportByValConversionErrors(param, argument, targetType, reportNarrowingConversions, diagnostics, diagnosticNode:=node, delegateSymbol:=delegateSymbol) End If Next Finally paramArrayItems.Free() parameterToArgumentMap.Free() End Try End Sub ''' <summary> ''' Should be in sync with OverloadResolution.MatchArgumentToByRefParameter ''' </summary> Private Sub ReportByRefConversionErrors( candidate As OverloadResolution.Candidate, param As ParameterSymbol, argument As BoundExpression, targetType As TypeSymbol, reportNarrowingConversions As Boolean, diagnostics As BindingDiagnosticBag, Optional diagnosticNode As SyntaxNode = Nothing, Optional delegateSymbol As Symbol = Nothing ) ' TODO: Do we need to do more thorough check for error types here, i.e. dig into generics, ' arrays, etc., detect types from unreferenced assemblies, ... ? If targetType.IsErrorType() OrElse argument.HasErrors Then ' UNDONE: should HasErrors really always cause argument mismatch [petergo, 3/9/2011] Return End If If argument.IsSupportingAssignment() Then If Not (argument.IsLValue() AndAlso targetType.IsSameTypeIgnoringAll(argument.Type)) Then If Not ReportByValConversionErrors(param, argument, targetType, reportNarrowingConversions, diagnostics, diagnosticNode:=diagnosticNode, delegateSymbol:=delegateSymbol) Then ' Check copy back conversion Dim boundTemp = New BoundRValuePlaceholder(argument.Syntax, targetType) Dim copyBackType = argument.GetTypeOfAssignmentTarget() Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(boundTemp, copyBackType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If Conversions.NoConversion(conv.Key) Then ' Possible only with user-defined conversions, I think. CreateConversionAndReportDiagnostic(argument.Syntax, boundTemp, conv, False, copyBackType, diagnostics, copybackConversionParamName:=param.Name) ElseIf Conversions.IsNarrowingConversion(conv.Key) Then Debug.Assert((conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0) If OptionStrict = VisualBasic.OptionStrict.On Then CreateConversionAndReportDiagnostic(argument.Syntax, boundTemp, conv, False, copyBackType, diagnostics, copybackConversionParamName:=param.Name) ElseIf reportNarrowingConversions Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_ArgumentCopyBackNarrowing3, CustomSymbolDisplayFormatter.ShortErrorName(param), targetType, copyBackType) End If End If End If End If Else ' No copy back needed ' If we are inside a lambda in a constructor and are passing ByRef a non-LValue field, which ' would be an LValue field, if it were referred to in the constructor outside of a lambda, ' we need to report an error because the operation will result in a simulated pass by ' ref (through a temp, without a copy back), which might be not the intent. If Report_ERRID_ReadOnlyInClosure(argument) Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_ReadOnlyInClosure) End If ReportByValConversionErrors(param, argument, targetType, reportNarrowingConversions, diagnostics, diagnosticNode:=diagnosticNode, delegateSymbol:=delegateSymbol) End If End Sub ''' <summary> ''' Should be in sync with OverloadResolution.MatchArgumentToByValParameter. ''' </summary> Private Function ReportByValConversionErrors( param As ParameterSymbol, argument As BoundExpression, targetType As TypeSymbol, reportNarrowingConversions As Boolean, diagnostics As BindingDiagnosticBag, Optional diagnosticNode As SyntaxNode = Nothing, Optional delegateSymbol As Symbol = Nothing ) As Boolean ' TODO: Do we need to do more thorough check for error types here, i.e. dig into generics, ' arrays, etc., detect types from unreferenced assemblies, ... ? If targetType.IsErrorType() OrElse argument.HasErrors Then ' UNDONE: should HasErrors really always cause argument mismatch [petergo, 3/9/2011] Return True End If Dim conv As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(argument, targetType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) If Conversions.NoConversion(conv.Key) Then If delegateSymbol Is Nothing Then CreateConversionAndReportDiagnostic(argument.Syntax, argument, conv, False, targetType, diagnostics) Else ' in case of delegates, use the operand of the AddressOf as location for this error CreateConversionAndReportDiagnostic(diagnosticNode, argument, conv, False, targetType, diagnostics) End If Return True End If Dim requiresNarrowingConversion As Boolean = False If Conversions.IsNarrowingConversion(conv.Key) Then If (conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) = 0 Then If OptionStrict = VisualBasic.OptionStrict.On Then If delegateSymbol Is Nothing Then CreateConversionAndReportDiagnostic(argument.Syntax, argument, conv, False, targetType, diagnostics) Else ' in case of delegates, use the operand of the AddressOf as location for this error ' because delegates have different error messages in case there is one or more candidates for narrowing ' indicate this as well. CreateConversionAndReportDiagnostic(diagnosticNode, argument, conv, False, targetType, diagnostics) End If Return True End If End If requiresNarrowingConversion = True ElseIf (conv.Key And ConversionKind.InvolvesNarrowingFromNumericConstant) <> 0 Then ' Dev10 overload resolution treats conversions that involve narrowing from numeric constant type ' as narrowing. requiresNarrowingConversion = True End If If reportNarrowingConversions AndAlso requiresNarrowingConversion Then Dim err As ERRID = ERRID.ERR_ArgumentNarrowing3 Dim targetDelegateType = targetType.DelegateOrExpressionDelegate(Me) If argument.Kind = BoundKind.QueryLambda AndAlso targetDelegateType IsNot Nothing Then Dim invoke As MethodSymbol = targetDelegateType.DelegateInvokeMethod If invoke IsNot Nothing AndAlso Not invoke.IsSub Then err = ERRID.ERR_NestedFunctionArgumentNarrowing3 argument = DirectCast(argument, BoundQueryLambda).Expression targetType = invoke.ReturnType End If End If If argument.Type Is Nothing Then ReportDiagnostic(diagnostics, argument.Syntax, ERRID.ERR_ArgumentNarrowing2, CustomSymbolDisplayFormatter.ShortErrorName(param), targetType) Else ReportDiagnostic(diagnostics, argument.Syntax, err, CustomSymbolDisplayFormatter.ShortErrorName(param), argument.Type, targetType) End If End If Return False End Function ''' <summary> ''' Should be kept in sync with OverloadResolution.MatchArguments, which populates ''' data this function operates on. ''' </summary> Private Function PassArguments( node As SyntaxNode, ByRef candidate As OverloadResolution.CandidateAnalysisResult, arguments As ImmutableArray(Of BoundExpression), diagnostics As BindingDiagnosticBag ) As (Arguments As ImmutableArray(Of BoundExpression), DefaultArguments As BitVector) Debug.Assert(candidate.State = OverloadResolution.CandidateAnalysisResultState.Applicable) If (arguments.IsDefault) Then arguments = ImmutableArray(Of BoundExpression).Empty End If Dim paramCount As Integer = candidate.Candidate.ParameterCount Dim parameterToArgumentMap = ArrayBuilder(Of Integer).GetInstance(paramCount, -1) Dim argumentsInOrder = ArrayBuilder(Of BoundExpression).GetInstance(paramCount) Dim defaultArguments = BitVector.Null Dim paramArrayItems As ArrayBuilder(Of Integer) = Nothing If candidate.IsExpandedParamArrayForm Then paramArrayItems = ArrayBuilder(Of Integer).GetInstance() End If Dim paramIndex As Integer ' For each parameter figure out matching argument. If candidate.ArgsToParamsOpt.IsDefaultOrEmpty Then Dim regularParamCount As Integer = paramCount If candidate.IsExpandedParamArrayForm Then regularParamCount -= 1 End If For i As Integer = 0 To Math.Min(regularParamCount, arguments.Length) - 1 Step 1 If arguments(i).Kind <> BoundKind.OmittedArgument Then parameterToArgumentMap(i) = i End If Next If candidate.IsExpandedParamArrayForm Then For i As Integer = regularParamCount To arguments.Length - 1 Step 1 paramArrayItems.Add(i) Next End If Else Dim argsToParams = candidate.ArgsToParamsOpt For i As Integer = 0 To argsToParams.Length - 1 Step 1 paramIndex = argsToParams(i) If arguments(i).Kind <> BoundKind.OmittedArgument Then If (candidate.IsExpandedParamArrayForm AndAlso paramIndex = candidate.Candidate.ParameterCount - 1) Then paramArrayItems.Add(i) Else parameterToArgumentMap(paramIndex) = i End If End If Next End If ' Traverse the parameters, converting corresponding arguments ' as appropriate. Dim candidateIsAProperty As Boolean = (candidate.Candidate.UnderlyingSymbol.Kind = SymbolKind.Property) For paramIndex = 0 To paramCount - 1 Step 1 Dim param As ParameterSymbol = candidate.Candidate.Parameters(paramIndex) Dim targetType As TypeSymbol = param.Type Dim argument As BoundExpression = Nothing Dim conversion As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.Identity Dim conversionBack As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.Identity If candidate.IsExpandedParamArrayForm AndAlso paramIndex = candidate.Candidate.ParameterCount - 1 Then Dim arrayElementType = DirectCast(targetType, ArrayTypeSymbol).ElementType Dim items = ArrayBuilder(Of BoundExpression).GetInstance(paramArrayItems.Count) For i As Integer = 0 To paramArrayItems.Count - 1 Step 1 items.Add(PassArgumentByVal(arguments(paramArrayItems(i)), If(candidate.ConversionsOpt.IsDefaultOrEmpty, Conversions.Identity, candidate.ConversionsOpt(paramArrayItems(i))), arrayElementType, diagnostics)) Next ' Create the bound array and ensure that it is marked as compiler generated. argument = New BoundArrayCreation(node, True, (New BoundExpression() {New BoundLiteral(node, ConstantValue.Create(items.Count), GetSpecialType(SpecialType.System_Int32, node, diagnostics)).MakeCompilerGenerated()}).AsImmutableOrNull(), New BoundArrayInitialization(node, items.ToImmutableAndFree(), targetType).MakeCompilerGenerated(), Nothing, Nothing, targetType).MakeCompilerGenerated() Else Dim argIndex As Integer argIndex = parameterToArgumentMap(paramIndex) argument = If(argIndex = -1, Nothing, arguments(argIndex)) If argument IsNot Nothing AndAlso paramIndex = candidate.Candidate.ParameterCount - 1 AndAlso param.IsParamArray Then argument = ApplyImplicitConversion(argument.Syntax, targetType, argument, diagnostics) ' Leave both conversions at identity since we already applied the conversion ElseIf argIndex > -1 Then If Not candidate.ConversionsOpt.IsDefaultOrEmpty Then conversion = candidate.ConversionsOpt(argIndex) End If If Not candidate.ConversionsBackOpt.IsDefaultOrEmpty Then conversionBack = candidate.ConversionsBackOpt(argIndex) End If End If End If Dim argumentIsDefaultValue As Boolean = False If argument Is Nothing Then Debug.Assert(Not candidate.OptionalArguments.IsEmpty, "Optional arguments expected") If defaultArguments.IsNull Then defaultArguments = BitVector.Create(paramCount) End If ' Deal with Optional arguments Dim defaultArgument As OverloadResolution.OptionalArgument = candidate.OptionalArguments(paramIndex) argument = defaultArgument.DefaultValue diagnostics.AddDependencies(defaultArgument.Dependencies) argumentIsDefaultValue = True defaultArguments(paramIndex) = True Debug.Assert(argument IsNot Nothing) conversion = defaultArgument.Conversion Dim argType = argument.Type If argType IsNot Nothing Then ' Report usesiteerror if it exists. Dim useSiteInfo = argType.GetUseSiteInfo ReportUseSite(diagnostics, argument.Syntax, useSiteInfo) End If End If ' Arguments for properties are always passed with ByVal semantics. Even if ' parameter in metadata is defined ByRef, we always pass corresponding argument ' through a temp without copy-back. Unlike with method calls, we rely on CodeGen ' to introduce the temp (easy to do since there is no copy-back around it), ' this allows us to keep the BoundPropertyAccess node simpler and allows to avoid ' A LOT of complexity in UseTwiceRewriter, which we would otherwise have around ' the temps. Debug.Assert(Not argumentIsDefaultValue OrElse argument.WasCompilerGenerated) Dim adjustedArgument As BoundExpression = PassArgument(argument, conversion, candidateIsAProperty, conversionBack, targetType, param, diagnostics) ' Keep SemanticModel happy. If argumentIsDefaultValue AndAlso adjustedArgument IsNot argument Then adjustedArgument.SetWasCompilerGenerated() End If argumentsInOrder.Add(adjustedArgument) Next If paramArrayItems IsNot Nothing Then paramArrayItems.Free() End If parameterToArgumentMap.Free() Return (argumentsInOrder.ToImmutableAndFree(), defaultArguments) End Function Private Function PassArgument( argument As BoundExpression, conversionTo As KeyValuePair(Of ConversionKind, MethodSymbol), forceByValueSemantics As Boolean, conversionFrom As KeyValuePair(Of ConversionKind, MethodSymbol), targetType As TypeSymbol, param As ParameterSymbol, diagnostics As BindingDiagnosticBag ) As BoundExpression Debug.Assert(Not param.IsByRef OrElse param.IsExplicitByRef OrElse targetType.IsStringType()) ' Non-string arguments for implicitly ByRef string parameters of Declare functions ' are passed through a temp without copy-back. If param.IsByRef AndAlso Not forceByValueSemantics AndAlso (param.IsExplicitByRef OrElse (argument.Type IsNot Nothing AndAlso argument.Type.IsStringType())) Then Return PassArgumentByRef(param.IsOut, argument, conversionTo, conversionFrom, targetType, param.Name, diagnostics) Else Return PassArgumentByVal(argument, conversionTo, targetType, diagnostics) End If End Function Private Function PassArgumentByRef( isOutParameter As Boolean, argument As BoundExpression, conversionTo As KeyValuePair(Of ConversionKind, MethodSymbol), conversionFrom As KeyValuePair(Of ConversionKind, MethodSymbol), targetType As TypeSymbol, parameterName As String, diagnostics As BindingDiagnosticBag ) As BoundExpression #If DEBUG Then Dim checkAgainst As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(argument, targetType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Debug.Assert(conversionTo.Key = checkAgainst.Key) Debug.Assert(Equals(conversionTo.Value, checkAgainst.Value)) #End If ' TODO: Fields of MarshalByRef object are passed via temp. Dim isLValue As Boolean = argument.IsLValue() If isLValue AndAlso argument.Kind = BoundKind.PropertyAccess Then argument = argument.SetAccessKind(PropertyAccessKind.Get) End If If isLValue AndAlso Conversions.IsIdentityConversion(conversionTo.Key) Then 'Nothing to do Debug.Assert(Conversions.IsIdentityConversion(conversionFrom.Key)) Return argument ElseIf isLValue OrElse argument.IsSupportingAssignment() Then ' Need to allocate a temp of the target type, ' init it with argument's value, ' pass it ByRef, ' copy value back after the call. Dim inPlaceholder = New BoundByRefArgumentPlaceholder(argument.Syntax, isOutParameter, argument.Type, argument.HasErrors).MakeCompilerGenerated() Dim inConversion = CreateConversionAndReportDiagnostic(argument.Syntax, inPlaceholder, conversionTo, False, targetType, diagnostics) Dim outPlaceholder = New BoundRValuePlaceholder(argument.Syntax, targetType).MakeCompilerGenerated() Dim copyBackType = argument.GetTypeOfAssignmentTarget() #If DEBUG Then checkAgainst = Conversions.ClassifyConversion(outPlaceholder, copyBackType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Debug.Assert(conversionFrom.Key = checkAgainst.Key) Debug.Assert(Equals(conversionFrom.Value, checkAgainst.Value)) #End If Dim outConversion = CreateConversionAndReportDiagnostic(argument.Syntax, outPlaceholder, conversionFrom, False, copyBackType, diagnostics, copybackConversionParamName:=parameterName).MakeCompilerGenerated() ' since we are going to assign to a latebound invocation ' force its arguments to be rvalues. If argument.Kind = BoundKind.LateInvocation Then argument = MakeArgsRValues(DirectCast(argument, BoundLateInvocation), diagnostics) End If Dim copyBackExpression = BindAssignment(argument.Syntax, argument, outConversion, diagnostics) Debug.Assert(copyBackExpression.HasErrors OrElse (copyBackExpression.Kind = BoundKind.AssignmentOperator AndAlso DirectCast(copyBackExpression, BoundAssignmentOperator).Right Is outConversion)) If Not isLValue Then If argument.IsLateBound() Then argument = argument.SetLateBoundAccessKind(LateBoundAccessKind.Get Or LateBoundAccessKind.Set) Else ' Diagnostics for PropertyAccessKind.Set case has been reported when we called BindAssignment. WarnOnRecursiveAccess(argument, PropertyAccessKind.Get, diagnostics) argument = argument.SetAccessKind(PropertyAccessKind.Get Or PropertyAccessKind.Set) End If End If Return New BoundByRefArgumentWithCopyBack(argument.Syntax, argument, inConversion, inPlaceholder, outConversion, outPlaceholder, targetType, copyBackExpression.HasErrors).MakeCompilerGenerated() Else Dim propertyAccess = TryCast(argument, BoundPropertyAccess) If propertyAccess IsNot Nothing AndAlso propertyAccess.AccessKind <> PropertyAccessKind.Get AndAlso propertyAccess.PropertySymbol.SetMethod?.IsInitOnly Then Debug.Assert(Not propertyAccess.IsWriteable) ' Used to be writable prior to VB 16.9, which caused a use-site error while binding an assignment above. InternalSyntax.Parser.CheckFeatureAvailability(diagnostics, argument.Syntax.Location, DirectCast(argument.Syntax.SyntaxTree.Options, VisualBasicParseOptions).LanguageVersion, InternalSyntax.Feature.InitOnlySettersUsage) End If ' Need to allocate a temp of the target type, ' init it with argument's value, ' pass it ByRef. Code gen will do this. Return PassArgumentByVal(argument, conversionTo, targetType, diagnostics) End If End Function ' when latebound invocation acts as an LHS in an assignment ' its arguments are always passed ByVal since property parameters ' are always treated as ByVal ' This method is used to force the arguments to be RValues Private Function MakeArgsRValues(ByVal invocation As BoundLateInvocation, diagnostics As BindingDiagnosticBag) As BoundLateInvocation Dim args = invocation.ArgumentsOpt If Not args.IsEmpty Then Dim argBuilder As ArrayBuilder(Of BoundExpression) = Nothing For i As Integer = 0 To args.Length - 1 Dim arg = args(i) Dim newArg = MakeRValue(arg, diagnostics) If argBuilder Is Nothing AndAlso arg IsNot newArg Then argBuilder = ArrayBuilder(Of BoundExpression).GetInstance argBuilder.AddRange(args, i) End If If argBuilder IsNot Nothing Then argBuilder.Add(newArg) End If Next If argBuilder IsNot Nothing Then invocation = invocation.Update(invocation.Member, argBuilder.ToImmutableAndFree, invocation.ArgumentNamesOpt, invocation.AccessKind, invocation.MethodOrPropertyGroupOpt, invocation.Type) End If End If Return invocation End Function Friend Function PassArgumentByVal( argument As BoundExpression, conversion As KeyValuePair(Of ConversionKind, MethodSymbol), targetType As TypeSymbol, diagnostics As BindingDiagnosticBag ) As BoundExpression #If DEBUG Then Dim checkAgainst As KeyValuePair(Of ConversionKind, MethodSymbol) = Conversions.ClassifyConversion(argument, targetType, Me, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Debug.Assert(conversion.Key = checkAgainst.Key) Debug.Assert(Equals(conversion.Value, checkAgainst.Value)) #End If argument = CreateConversionAndReportDiagnostic(argument.Syntax, argument, conversion, False, targetType, diagnostics) Debug.Assert(Not argument.IsLValue) Return argument End Function ' Given a list of arguments, create arrays of the bound arguments and the names of those arguments. Private Sub BindArgumentsAndNames( argumentListOpt As ArgumentListSyntax, ByRef boundArguments As ImmutableArray(Of BoundExpression), ByRef argumentNames As ImmutableArray(Of String), ByRef argumentNamesLocations As ImmutableArray(Of Location), diagnostics As BindingDiagnosticBag ) Dim args As ImmutableArray(Of ArgumentSyntax) = Nothing If argumentListOpt IsNot Nothing Then Dim arguments = argumentListOpt.Arguments Dim argsArr(arguments.Count - 1) As ArgumentSyntax For i = 0 To argsArr.Length - 1 argsArr(i) = arguments(i) Next args = argsArr.AsImmutableOrNull End If BindArgumentsAndNames( args, boundArguments, argumentNames, argumentNamesLocations, diagnostics ) End Sub ' Given a list of arguments, create arrays of the bound arguments and the names of those arguments. Private Sub BindArgumentsAndNames( arguments As ImmutableArray(Of ArgumentSyntax), ByRef boundArguments As ImmutableArray(Of BoundExpression), ByRef argumentNames As ImmutableArray(Of String), ByRef argumentNamesLocations As ImmutableArray(Of Location), diagnostics As BindingDiagnosticBag ) ' With SeparatedSyntaxList, it is most efficient to iterate with foreach and not to access Count. If arguments.IsDefaultOrEmpty Then boundArguments = s_noArguments argumentNames = Nothing argumentNamesLocations = Nothing Else Dim boundArgumentsBuilder As ArrayBuilder(Of BoundExpression) = ArrayBuilder(Of BoundExpression).GetInstance Dim argumentNamesBuilder As ArrayBuilder(Of String) = Nothing Dim argumentNamesLocationsBuilder As ArrayBuilder(Of Location) = Nothing Dim argCount As Integer = 0 Dim argumentSyntax As ArgumentSyntax For Each argumentSyntax In arguments Select Case argumentSyntax.Kind Case SyntaxKind.SimpleArgument Dim simpleArgument = DirectCast(argumentSyntax, SimpleArgumentSyntax) boundArgumentsBuilder.Add(BindValue(simpleArgument.Expression, diagnostics)) If simpleArgument.IsNamed Then ' The common case is no named arguments. So we defer all work until the first named argument is seen. If argumentNamesBuilder Is Nothing Then argumentNamesBuilder = ArrayBuilder(Of String).GetInstance() argumentNamesLocationsBuilder = ArrayBuilder(Of Location).GetInstance() For i = 0 To argCount - 1 argumentNamesBuilder.Add(Nothing) argumentNamesLocationsBuilder.Add(Nothing) Next i End If Dim id = simpleArgument.NameColonEquals.Name.Identifier If id.ValueText.Length > 0 Then argumentNamesBuilder.Add(id.ValueText) Else argumentNamesBuilder.Add(Nothing) End If argumentNamesLocationsBuilder.Add(id.GetLocation()) ElseIf argumentNamesBuilder IsNot Nothing Then argumentNamesBuilder.Add(Nothing) argumentNamesLocationsBuilder.Add(Nothing) End If Case SyntaxKind.OmittedArgument boundArgumentsBuilder.Add(New BoundOmittedArgument(argumentSyntax, Nothing)) If argumentNamesBuilder IsNot Nothing Then argumentNamesBuilder.Add(Nothing) argumentNamesLocationsBuilder.Add(Nothing) End If Case SyntaxKind.RangeArgument ' NOTE: Redim statement supports range argument, like: Redim x(0 To 3)(0 To 6) ' This behavior is misleading, because the 'range' (0 To 3) is actually ' being ignored and only upper bound is being used. ' TODO: revise (add warning/error?) Dim rangeArgument = DirectCast(argumentSyntax, RangeArgumentSyntax) CheckRangeArgumentLowerBound(rangeArgument, diagnostics) boundArgumentsBuilder.Add(BindValue(rangeArgument.UpperBound, diagnostics)) If argumentNamesBuilder IsNot Nothing Then argumentNamesBuilder.Add(Nothing) argumentNamesLocationsBuilder.Add(Nothing) End If Case Else Throw ExceptionUtilities.UnexpectedValue(argumentSyntax.Kind) End Select argCount += 1 Next boundArguments = boundArgumentsBuilder.ToImmutableAndFree argumentNames = If(argumentNamesBuilder Is Nothing, Nothing, argumentNamesBuilder.ToImmutableAndFree) argumentNamesLocations = If(argumentNamesLocationsBuilder Is Nothing, Nothing, argumentNamesLocationsBuilder.ToImmutableAndFree) End If End Sub Friend Function GetArgumentForParameterDefaultValue(param As ParameterSymbol, syntax As SyntaxNode, diagnostics As BindingDiagnosticBag, callerInfoOpt As SyntaxNode, parameterToArgumentMap As ArrayBuilder(Of Integer), arguments As ImmutableArray(Of BoundExpression), reducedExtensionReceiverOpt As BoundExpression) As BoundExpression Dim defaultArgument As BoundExpression = Nothing ' See Section 3 of §11.8.2 Applicable Methods ' Deal with Optional arguments. HasDefaultValue is true if the parameter is optional and has a default value. Dim defaultConstantValue As ConstantValue = If(param.IsOptional, param.ExplicitDefaultConstantValue(DefaultParametersInProgress), Nothing) If defaultConstantValue IsNot Nothing Then If callerInfoOpt IsNot Nothing AndAlso callerInfoOpt.SyntaxTree IsNot Nothing AndAlso Not callerInfoOpt.SyntaxTree.IsEmbeddedOrMyTemplateTree() AndAlso Not SuppressCallerInfo Then Dim isCallerLineNumber As Boolean = param.IsCallerLineNumber Dim isCallerMemberName As Boolean = param.IsCallerMemberName Dim isCallerFilePath As Boolean = param.IsCallerFilePath Dim callerArgumentExpressionParameterIndex As Integer = param.CallerArgumentExpressionParameterIndex Dim isCallerArgumentExpression = callerArgumentExpressionParameterIndex > -1 OrElse (reducedExtensionReceiverOpt IsNot Nothing AndAlso callerArgumentExpressionParameterIndex > -2) If isCallerLineNumber OrElse isCallerMemberName OrElse isCallerFilePath OrElse isCallerArgumentExpression Then Dim callerInfoValue As ConstantValue = Nothing If isCallerLineNumber Then callerInfoValue = ConstantValue.Create(callerInfoOpt.SyntaxTree.GetDisplayLineNumber(GetCallerLocation(callerInfoOpt))) ElseIf isCallerMemberName Then Dim container As Symbol = ContainingMember While container IsNot Nothing Select Case container.Kind Case SymbolKind.Field, SymbolKind.Property, SymbolKind.Event Exit While Case SymbolKind.Method If container.IsLambdaMethod Then container = container.ContainingSymbol Else Dim propertyOrEvent As Symbol = DirectCast(container, MethodSymbol).AssociatedSymbol If propertyOrEvent IsNot Nothing Then container = propertyOrEvent End If Exit While End If Case Else container = container.ContainingSymbol End Select End While If container IsNot Nothing AndAlso container.Name IsNot Nothing Then callerInfoValue = ConstantValue.Create(container.Name) End If ElseIf isCallerFilePath Then callerInfoValue = ConstantValue.Create(callerInfoOpt.SyntaxTree.GetDisplayPath(callerInfoOpt.Span, Me.Compilation.Options.SourceReferenceResolver)) Else Debug.Assert(callerArgumentExpressionParameterIndex > -1 OrElse (reducedExtensionReceiverOpt IsNot Nothing AndAlso callerArgumentExpressionParameterIndex > -2)) Dim argumentSyntax As SyntaxNode = Nothing If callerArgumentExpressionParameterIndex = -1 Then argumentSyntax = reducedExtensionReceiverOpt.Syntax Else Dim argumentIndex = parameterToArgumentMap(callerArgumentExpressionParameterIndex) Debug.Assert(argumentIndex < arguments.Length) If argumentIndex > -1 Then argumentSyntax = arguments(argumentIndex).Syntax End If End If If argumentSyntax IsNot Nothing Then callerInfoValue = ConstantValue.Create(argumentSyntax.ToString()) End If End If If callerInfoValue IsNot Nothing Then ' Use the value only if it will not cause errors. Dim ignoreDiagnostics = New BindingDiagnosticBag(DiagnosticBag.GetInstance()) Dim literal As BoundLiteral If callerInfoValue.Discriminator = ConstantValueTypeDiscriminator.Int32 Then literal = New BoundLiteral(syntax, callerInfoValue, GetSpecialType(SpecialType.System_Int32, syntax, ignoreDiagnostics)) Else Debug.Assert(callerInfoValue.Discriminator = ConstantValueTypeDiscriminator.String) literal = New BoundLiteral(syntax, callerInfoValue, GetSpecialType(SpecialType.System_String, syntax, ignoreDiagnostics)) End If Dim convertedValue As BoundExpression = ApplyImplicitConversion(syntax, param.Type, literal, ignoreDiagnostics) If Not convertedValue.HasErrors AndAlso Not ignoreDiagnostics.HasAnyErrors Then ' Dev11 #248795: Caller info should be omitted if user defined conversion is involved. If Not (convertedValue.Kind = BoundKind.Conversion AndAlso (DirectCast(convertedValue, BoundConversion).ConversionKind And ConversionKind.UserDefined) <> 0) Then defaultConstantValue = callerInfoValue End If End If ignoreDiagnostics.Free() End If End If End If ' For compatibility with the native compiler bad metadata constants should be treated as default(T). This ' is a possible outcome of running an obfuscator over a valid DLL If defaultConstantValue.IsBad Then defaultConstantValue = ConstantValue.Null End If Dim defaultSpecialType = defaultConstantValue.SpecialType Dim defaultArgumentType As TypeSymbol = Nothing ' Constant has a type. Dim paramNullableUnderlyingTypeOrSelf As TypeSymbol = param.Type.GetNullableUnderlyingTypeOrSelf() If param.HasOptionCompare Then ' If the argument has the OptionCompareAttribute ' then use the setting for Option Compare [Binary|Text] ' Other languages will use the default value specified. If Me.OptionCompareText Then defaultConstantValue = ConstantValue.Create(1) Else defaultConstantValue = ConstantValue.Default(SpecialType.System_Int32) End If If paramNullableUnderlyingTypeOrSelf.GetEnumUnderlyingTypeOrSelf().SpecialType = SpecialType.System_Int32 Then defaultArgumentType = paramNullableUnderlyingTypeOrSelf Else defaultArgumentType = GetSpecialType(SpecialType.System_Int32, syntax, diagnostics) End If ElseIf defaultSpecialType <> SpecialType.None Then If paramNullableUnderlyingTypeOrSelf.GetEnumUnderlyingTypeOrSelf().SpecialType = defaultSpecialType Then ' Enum default values are encoded as the underlying primitive type. If the underlying types match then ' use the parameter's enum type. defaultArgumentType = paramNullableUnderlyingTypeOrSelf Else 'Use the primitive type. defaultArgumentType = GetSpecialType(defaultSpecialType, syntax, diagnostics) End If Else ' No type in constant. Constant should be nothing Debug.Assert(defaultConstantValue.IsNothing) End If defaultArgument = New BoundLiteral(syntax, defaultConstantValue, defaultArgumentType) ElseIf param.IsOptional Then ' Handle optional object type argument when no default value is specified. ' Section 3 of §11.8.2 Applicable Methods If param.Type.SpecialType = SpecialType.System_Object Then Dim methodSymbol As MethodSymbol = Nothing If param.IsMarshalAsObject Then ' Nothing defaultArgument = New BoundLiteral(syntax, ConstantValue.Null, Nothing) ElseIf param.IsIDispatchConstant Then ' new DispatchWrapper(nothing) methodSymbol = DirectCast(GetWellKnownTypeMember(WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor, syntax, diagnostics), MethodSymbol) ElseIf param.IsIUnknownConstant Then ' new UnknownWrapper(nothing) methodSymbol = DirectCast(GetWellKnownTypeMember(WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor, syntax, diagnostics), MethodSymbol) Else defaultArgument = New BoundOmittedArgument(syntax, param.Type) End If If methodSymbol IsNot Nothing Then Dim argument = New BoundLiteral(syntax, ConstantValue.Null, param.Type).MakeCompilerGenerated() defaultArgument = New BoundObjectCreationExpression(syntax, methodSymbol, ImmutableArray.Create(Of BoundExpression)(argument), Nothing, methodSymbol.ContainingType) End If Else defaultArgument = New BoundLiteral(syntax, ConstantValue.Null, Nothing) End If End If Return defaultArgument?.MakeCompilerGenerated() End Function Private Shared Function GetCallerLocation(syntax As SyntaxNode) As TextSpan Select Case syntax.Kind Case SyntaxKind.SimpleMemberAccessExpression Return DirectCast(syntax, MemberAccessExpressionSyntax).Name.Span Case SyntaxKind.DictionaryAccessExpression Return DirectCast(syntax, MemberAccessExpressionSyntax).OperatorToken.Span Case Else Return syntax.Span End Select End Function ''' <summary> ''' Return true if the node is an immediate child of a call statement. ''' </summary> Private Shared Function IsCallStatementContext(node As InvocationExpressionSyntax) As Boolean Dim parent As VisualBasicSyntaxNode = node.Parent ' Dig through conditional access If parent IsNot Nothing AndAlso parent.Kind = SyntaxKind.ConditionalAccessExpression Then Dim conditional = DirectCast(parent, ConditionalAccessExpressionSyntax) If conditional.WhenNotNull Is node Then parent = conditional.Parent End If End If Return parent IsNot Nothing AndAlso (parent.Kind = SyntaxKind.CallStatement OrElse parent.Kind = SyntaxKind.ExpressionStatement) End Function End Class End Namespace
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SpeculativeTCompletionProviderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public class SpeculativeTCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(SpeculativeTCompletionProvider); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IsCommitCharacterTest() { const string markup = @" class C { $$ }"; await VerifyCommonCommitCharactersAsync(markup, textTypedSoFar: ""); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void IsTextualTriggerCharacterTest() => TestCommonIsTextualTriggerCharacter(); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SendEnterThroughToEditorTest() { const string markup = @" class C { $$ }"; await VerifySendEnterThroughToEnterAsync(markup, "T", sendThroughEnterOption: EnterKeyRule.Never, expected: false); await VerifySendEnterThroughToEnterAsync(markup, "T", sendThroughEnterOption: EnterKeyRule.AfterFullyTypedWord, expected: true); await VerifySendEnterThroughToEnterAsync(markup, "T", sendThroughEnterOption: EnterKeyRule.Always, expected: true); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InClass() { var markup = @" class C { $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InInterface() { var markup = @" interface I { $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InStruct() { var markup = @" struct S { $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInNamespace() { var markup = @" namespace N { $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInEnum() { var markup = @" enum E { $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterDelegate() { var markup = @" class C { delegate $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterVoid() { var markup = @" class C { void $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterInt() { var markup = @" class C { int $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InGeneric() { var markup = @" using System; class C { Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] public async Task InRef0() { var markup = @" using System; class C { ref $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] public async Task InRef1() { var markup = @" using System; class C { ref T$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] public async Task InRefGeneric0() { var markup = @" using System; class C { ref Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] public async Task InRefGeneric1() { var markup = @" using System; class C { ref Func<$$> }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] public async Task InRefGeneric2() { var markup = @" using System; class C { ref Func<T$$> }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] public async Task InRefGeneric3() { var markup = @" using System; class C { ref Func<int, $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] public async Task InRefReadonlyGeneric() { var markup = @" using System; class C { ref readonly Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37268, "https://github.com/dotnet/roslyn/issues/37268")] public async Task InQualifiedGeneric0() { var markup = @" using System; class C { System.Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37268, "https://github.com/dotnet/roslyn/issues/37268")] public async Task InQualifiedGeneric1() { var markup = @" using System; class C { System.Collections.Generic.List<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] [WorkItem(37268, "https://github.com/dotnet/roslyn/issues/37268")] public async Task InRefAndQualifiedGeneric0() { var markup = @" using System; class C { ref System.Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] [WorkItem(37268, "https://github.com/dotnet/roslyn/issues/37268")] public async Task InRefAndQualifiedGeneric1() { var markup = @" using System; class C { internal ref System.Func<int,$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] [WorkItem(37268, "https://github.com/dotnet/roslyn/issues/37268")] public async Task InRefAndQualifiedNestedGeneric0() { var markup = @" using System; class C { partial ref System.Func<Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] [WorkItem(37268, "https://github.com/dotnet/roslyn/issues/37268")] public async Task InRefAndQualifiedNestedGeneric1() { var markup = @" using System; class C { private ref Func<System.Func<int,$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] [WorkItem(37268, "https://github.com/dotnet/roslyn/issues/37268")] public async Task InRefAndQualifiedNestedGeneric2() { var markup = @" using System; class C { public ref Func<int, System.Func<int,$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] [WorkItem(37268, "https://github.com/dotnet/roslyn/issues/37268")] public async Task InRefAndQualifiedNestedGeneric3() { var markup = @" using System; class C { private protected ref Func<int, System.Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InTuple0() { var markup = @" using System; class C { protected ($$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task TupleInMethod0() { var markup = @" using System; class C { void M() { ($$ } }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task TupleInMethod1() { var markup = @" using System; class C { void M() { var a = 0; ($$ } }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task TupleInMethod2() { var markup = @" using System; class C { void M() { ($$) } }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task TupleInMethod3() { var markup = @" using System; class C { void M() { var a = 0; (T$$) a = 1; } }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InTupleNot0() { var markup = @" using System; class C { protected sealed (int $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InTuple1() { var markup = @" using System; class C { sealed (int, $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InTupleNot1() { var markup = @" using System; class C { virtual (int x, C $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InTupleGeneric0() { var markup = @" using System; class C { (Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InTupleGeneric1() { var markup = @" using System; class C { (int, Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InTupleGeneric2() { var markup = @" using System; class C { (int, Func<int, $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InGenericTuple0() { var markup = @" using System; class C { Func<($$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InGenericTuple1() { var markup = @" using System; class C { Func<int, ($$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InGenericTuple1Not() { var markup = @" using System; class C { Func<int, (T $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InGenericTuple2() { var markup = @" using System; class C { Func<(int, $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InGenericTuple2Not() { var markup = @" using System; class C { Func<(C c, int $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InGenericTuple3() { var markup = @" using System; class C { Func<int, (int,$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InGenericTuple3Not() { var markup = @" using System; class C { Func<C, (int, C $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InRefTupleQualifiedNestedGeneric0() { var markup = @" using System; class C { ref (Func<System.Func<int,$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InRefTupleQualifiedNestedGeneric1() { var markup = @" using System; class C { ref (C c, Func<System.Func<int,$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InRefTupleQualifiedNestedGeneric2() { var markup = @" using System; class C { ref (C c, Func<int, System.Func<(int,T$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InRefTupleQualifiedNestedGeneric3() { var markup = @" using System; class C { ref (C c, System.Func<Func<int,(T$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InRefTupleQualifiedNestedGeneric4() { var markup = @" using System; class C { ref (System.Func<(int,C), (Func<int,T$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InRefTupleQualifiedNestedGeneric5() { var markup = @" using System; class C { ref readonly (System.Func<(int, (C, (Func<int,T$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InRefTupleQualifiedNestedGeneric6() { var markup = @" using System; class C { ref readonly (System.Collections.Generic.List<(int, (C, (Func<int,T$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InNestedGeneric1() { var markup = @" using System; class C { Func<Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InNestedGeneric2() { var markup = @" using System; class C { Func<Func<int,$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InScript() { var markup = @"$$"; await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterVoidInScript() { var markup = @"void $$"; await VerifyItemIsAbsentAsync(markup, "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterIntInScript() { var markup = @"int $$"; await VerifyItemIsAbsentAsync(markup, "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InGenericInScript() { var markup = @" using System; Func<$$ "; await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InNestedGenericInScript1() { var markup = @" using System; Func<Func<$$ "; await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InNestedGenericInScript2() { var markup = @" using System; Func<Func<int,$$ "; await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInComment() { var markup = @" class C { // $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInXmlDocComment() { var markup = @" class C { /// <summary> /// $$ /// </summary> void Goo() { } }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsyncTask() { var markup = @" using System.Threading.Tasks; class Program { async Task<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OkAfterAsync() { var markup = @" using System.Threading.Tasks; class Program { async $$ }"; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(968256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968256")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task UnionOfItemsFromBothContexts() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO void goo() { #endif $$ #if GOO } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; await VerifyItemInLinkedFilesAsync(markup, "T", null); } [WorkItem(1020654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020654")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsyncTaskWithBraceCompletion() { var markup = @" using System.Threading.Tasks; class Program { async Task<$$> }"; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")] [Fact] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionReturnType() { var markup = @" class C { public void M() { $$ } }"; await VerifyItemExistsAsync(markup, "T"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionAfterAyncTask() { var markup = @" class C { public void M() { async Task<$$> } }"; await VerifyItemExistsAsync(markup, "T"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionAfterAsync() { var markup = @" class C { public void M() { async $$ } }"; await VerifyItemExistsAsync(markup, "T"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders { public class SpeculativeTCompletionProviderTests : AbstractCSharpCompletionProviderTests { internal override Type GetCompletionProviderType() => typeof(SpeculativeTCompletionProvider); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task IsCommitCharacterTest() { const string markup = @" class C { $$ }"; await VerifyCommonCommitCharactersAsync(markup, textTypedSoFar: ""); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public void IsTextualTriggerCharacterTest() => TestCommonIsTextualTriggerCharacter(); [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task SendEnterThroughToEditorTest() { const string markup = @" class C { $$ }"; await VerifySendEnterThroughToEnterAsync(markup, "T", sendThroughEnterOption: EnterKeyRule.Never, expected: false); await VerifySendEnterThroughToEnterAsync(markup, "T", sendThroughEnterOption: EnterKeyRule.AfterFullyTypedWord, expected: true); await VerifySendEnterThroughToEnterAsync(markup, "T", sendThroughEnterOption: EnterKeyRule.Always, expected: true); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InClass() { var markup = @" class C { $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InInterface() { var markup = @" interface I { $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InStruct() { var markup = @" struct S { $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInNamespace() { var markup = @" namespace N { $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInEnum() { var markup = @" enum E { $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterDelegate() { var markup = @" class C { delegate $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterVoid() { var markup = @" class C { void $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterInt() { var markup = @" class C { int $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InGeneric() { var markup = @" using System; class C { Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] public async Task InRef0() { var markup = @" using System; class C { ref $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] public async Task InRef1() { var markup = @" using System; class C { ref T$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] public async Task InRefGeneric0() { var markup = @" using System; class C { ref Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] public async Task InRefGeneric1() { var markup = @" using System; class C { ref Func<$$> }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] public async Task InRefGeneric2() { var markup = @" using System; class C { ref Func<T$$> }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] public async Task InRefGeneric3() { var markup = @" using System; class C { ref Func<int, $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] public async Task InRefReadonlyGeneric() { var markup = @" using System; class C { ref readonly Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37268, "https://github.com/dotnet/roslyn/issues/37268")] public async Task InQualifiedGeneric0() { var markup = @" using System; class C { System.Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37268, "https://github.com/dotnet/roslyn/issues/37268")] public async Task InQualifiedGeneric1() { var markup = @" using System; class C { System.Collections.Generic.List<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] [WorkItem(37268, "https://github.com/dotnet/roslyn/issues/37268")] public async Task InRefAndQualifiedGeneric0() { var markup = @" using System; class C { ref System.Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] [WorkItem(37268, "https://github.com/dotnet/roslyn/issues/37268")] public async Task InRefAndQualifiedGeneric1() { var markup = @" using System; class C { internal ref System.Func<int,$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] [WorkItem(37268, "https://github.com/dotnet/roslyn/issues/37268")] public async Task InRefAndQualifiedNestedGeneric0() { var markup = @" using System; class C { partial ref System.Func<Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] [WorkItem(37268, "https://github.com/dotnet/roslyn/issues/37268")] public async Task InRefAndQualifiedNestedGeneric1() { var markup = @" using System; class C { private ref Func<System.Func<int,$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] [WorkItem(37268, "https://github.com/dotnet/roslyn/issues/37268")] public async Task InRefAndQualifiedNestedGeneric2() { var markup = @" using System; class C { public ref Func<int, System.Func<int,$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37224, "https://github.com/dotnet/roslyn/issues/37224")] [WorkItem(37268, "https://github.com/dotnet/roslyn/issues/37268")] public async Task InRefAndQualifiedNestedGeneric3() { var markup = @" using System; class C { private protected ref Func<int, System.Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InTuple0() { var markup = @" using System; class C { protected ($$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task TupleInMethod0() { var markup = @" using System; class C { void M() { ($$ } }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task TupleInMethod1() { var markup = @" using System; class C { void M() { var a = 0; ($$ } }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task TupleInMethod2() { var markup = @" using System; class C { void M() { ($$) } }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task TupleInMethod3() { var markup = @" using System; class C { void M() { var a = 0; (T$$) a = 1; } }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InTupleNot0() { var markup = @" using System; class C { protected sealed (int $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InTuple1() { var markup = @" using System; class C { sealed (int, $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InTupleNot1() { var markup = @" using System; class C { virtual (int x, C $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InTupleGeneric0() { var markup = @" using System; class C { (Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InTupleGeneric1() { var markup = @" using System; class C { (int, Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InTupleGeneric2() { var markup = @" using System; class C { (int, Func<int, $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InGenericTuple0() { var markup = @" using System; class C { Func<($$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InGenericTuple1() { var markup = @" using System; class C { Func<int, ($$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InGenericTuple1Not() { var markup = @" using System; class C { Func<int, (T $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InGenericTuple2() { var markup = @" using System; class C { Func<(int, $$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InGenericTuple2Not() { var markup = @" using System; class C { Func<(C c, int $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InGenericTuple3() { var markup = @" using System; class C { Func<int, (int,$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InGenericTuple3Not() { var markup = @" using System; class C { Func<C, (int, C $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InRefTupleQualifiedNestedGeneric0() { var markup = @" using System; class C { ref (Func<System.Func<int,$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InRefTupleQualifiedNestedGeneric1() { var markup = @" using System; class C { ref (C c, Func<System.Func<int,$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InRefTupleQualifiedNestedGeneric2() { var markup = @" using System; class C { ref (C c, Func<int, System.Func<(int,T$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InRefTupleQualifiedNestedGeneric3() { var markup = @" using System; class C { ref (C c, System.Func<Func<int,(T$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InRefTupleQualifiedNestedGeneric4() { var markup = @" using System; class C { ref (System.Func<(int,C), (Func<int,T$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InRefTupleQualifiedNestedGeneric5() { var markup = @" using System; class C { ref readonly (System.Func<(int, (C, (Func<int,T$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] [WorkItem(37361, "https://github.com/dotnet/roslyn/issues/37361")] public async Task InRefTupleQualifiedNestedGeneric6() { var markup = @" using System; class C { ref readonly (System.Collections.Generic.List<(int, (C, (Func<int,T$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InNestedGeneric1() { var markup = @" using System; class C { Func<Func<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InNestedGeneric2() { var markup = @" using System; class C { Func<Func<int,$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InScript() { var markup = @"$$"; await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterVoidInScript() { var markup = @"void $$"; await VerifyItemIsAbsentAsync(markup, "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotAfterIntInScript() { var markup = @"int $$"; await VerifyItemIsAbsentAsync(markup, "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InGenericInScript() { var markup = @" using System; Func<$$ "; await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InNestedGenericInScript1() { var markup = @" using System; Func<Func<$$ "; await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task InNestedGenericInScript2() { var markup = @" using System; Func<Func<int,$$ "; await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInComment() { var markup = @" class C { // $$ }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task NotInXmlDocComment() { var markup = @" class C { /// <summary> /// $$ /// </summary> void Goo() { } }"; await VerifyItemIsAbsentAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsyncTask() { var markup = @" using System.Threading.Tasks; class Program { async Task<$$ }"; await VerifyItemExistsAsync(markup, "T"); } [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task OkAfterAsync() { var markup = @" using System.Threading.Tasks; class Program { async $$ }"; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(968256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968256")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task UnionOfItemsFromBothContexts() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""CurrentDocument.cs""><![CDATA[ class C { #if GOO void goo() { #endif $$ #if GOO } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/> </Project> </Workspace>"; await VerifyItemInLinkedFilesAsync(markup, "T", null); } [WorkItem(1020654, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020654")] [Fact, Trait(Traits.Feature, Traits.Features.Completion)] public async Task AfterAsyncTaskWithBraceCompletion() { var markup = @" using System.Threading.Tasks; class Program { async Task<$$> }"; await VerifyItemExistsAsync(markup, "T"); } [WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")] [Fact] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionReturnType() { var markup = @" class C { public void M() { $$ } }"; await VerifyItemExistsAsync(markup, "T"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionAfterAyncTask() { var markup = @" class C { public void M() { async Task<$$> } }"; await VerifyItemExistsAsync(markup, "T"); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14525")] [CompilerTrait(CompilerFeature.LocalFunctions)] public async Task LocalFunctionAfterAsync() { var markup = @" class C { public void M() { async $$ } }"; await VerifyItemExistsAsync(markup, "T"); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/EditorFeatures/VisualBasic/BraceMatching/OpenCloseBraceBraceMatcher.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.BraceMatching <ExportBraceMatcher(LanguageNames.VisualBasic)> Friend Class OpenCloseBraceBraceMatcher Inherits AbstractVisualBasicBraceMatcher <ImportingConstructor()> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.ComponentModel.Composition Imports Microsoft.CodeAnalysis.Host.Mef Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.BraceMatching <ExportBraceMatcher(LanguageNames.VisualBasic)> Friend Class OpenCloseBraceBraceMatcher Inherits AbstractVisualBasicBraceMatcher <ImportingConstructor()> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() MyBase.New(SyntaxKind.OpenBraceToken, SyntaxKind.CloseBraceToken) End Sub End Class End Namespace
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Workspaces/Core/Portable/Differencing/Edit.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Differencing { /// <summary> /// Represents an edit operation on a tree or a sequence of nodes. /// </summary> /// <typeparam name="TNode">Tree node.</typeparam> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] public struct Edit<TNode> : IEquatable<Edit<TNode>> { private readonly TreeComparer<TNode> _comparer; private readonly EditKind _kind; private readonly TNode _oldNode; private readonly TNode _newNode; internal Edit(EditKind kind, TreeComparer<TNode> comparer, TNode oldNode, TNode newNode) { Debug.Assert((oldNode == null || oldNode.Equals(null)) == (kind == EditKind.Insert)); Debug.Assert((newNode == null || newNode.Equals(null)) == (kind == EditKind.Delete)); Debug.Assert((oldNode == null || oldNode.Equals(null)) || (newNode == null || newNode.Equals(null)) || !comparer.TreesEqual(oldNode, newNode)); _comparer = comparer; _kind = kind; _oldNode = oldNode; _newNode = newNode; } public EditKind Kind => _kind; /// <summary> /// Insert: /// default(TNode). /// /// Delete: /// Deleted node. /// /// Move, Update: /// Node in the old tree/sequence. /// </summary> public TNode OldNode => _oldNode; /// <summary> /// Insert: /// Inserted node. /// /// Delete: /// default(TNode) /// /// Move, Update: /// Node in the new tree/sequence. /// </summary> public TNode NewNode => _newNode; public override bool Equals(object obj) => obj is Edit<TNode> && Equals((Edit<TNode>)obj); public bool Equals(Edit<TNode> other) { return _kind == other._kind && (_oldNode == null) ? other._oldNode == null : _oldNode.Equals(other._oldNode) && (_newNode == null) ? other._newNode == null : _newNode.Equals(other._newNode); } public override int GetHashCode() { var hash = (int)_kind; if (_oldNode != null) { hash = Hash.Combine(_oldNode.GetHashCode(), hash); } if (_newNode != null) { hash = Hash.Combine(_newNode.GetHashCode(), hash); } return hash; } // Has to be 'internal' for now as it's used by EnC test tool internal string GetDebuggerDisplay() { var result = Kind.ToString(); switch (Kind) { case EditKind.Delete: return result + " [" + _oldNode.ToString() + "]" + DisplayPosition(_oldNode); case EditKind.Insert: return result + " [" + _newNode.ToString() + "]" + DisplayPosition(_newNode); case EditKind.Update: return result + " [" + _oldNode.ToString() + "]" + DisplayPosition(_oldNode) + " -> [" + _newNode.ToString() + "]" + DisplayPosition(_newNode); case EditKind.Move: case EditKind.Reorder: return result + " [" + _oldNode.ToString() + "]" + DisplayPosition(_oldNode) + " -> " + DisplayPosition(_newNode); } return result; } private string DisplayPosition(TNode node) => "@" + _comparer.GetSpan(node).Start; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Differencing { /// <summary> /// Represents an edit operation on a tree or a sequence of nodes. /// </summary> /// <typeparam name="TNode">Tree node.</typeparam> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] public struct Edit<TNode> : IEquatable<Edit<TNode>> { private readonly TreeComparer<TNode> _comparer; private readonly EditKind _kind; private readonly TNode _oldNode; private readonly TNode _newNode; internal Edit(EditKind kind, TreeComparer<TNode> comparer, TNode oldNode, TNode newNode) { Debug.Assert((oldNode == null || oldNode.Equals(null)) == (kind == EditKind.Insert)); Debug.Assert((newNode == null || newNode.Equals(null)) == (kind == EditKind.Delete)); Debug.Assert((oldNode == null || oldNode.Equals(null)) || (newNode == null || newNode.Equals(null)) || !comparer.TreesEqual(oldNode, newNode)); _comparer = comparer; _kind = kind; _oldNode = oldNode; _newNode = newNode; } public EditKind Kind => _kind; /// <summary> /// Insert: /// default(TNode). /// /// Delete: /// Deleted node. /// /// Move, Update: /// Node in the old tree/sequence. /// </summary> public TNode OldNode => _oldNode; /// <summary> /// Insert: /// Inserted node. /// /// Delete: /// default(TNode) /// /// Move, Update: /// Node in the new tree/sequence. /// </summary> public TNode NewNode => _newNode; public override bool Equals(object obj) => obj is Edit<TNode> && Equals((Edit<TNode>)obj); public bool Equals(Edit<TNode> other) { return _kind == other._kind && (_oldNode == null) ? other._oldNode == null : _oldNode.Equals(other._oldNode) && (_newNode == null) ? other._newNode == null : _newNode.Equals(other._newNode); } public override int GetHashCode() { var hash = (int)_kind; if (_oldNode != null) { hash = Hash.Combine(_oldNode.GetHashCode(), hash); } if (_newNode != null) { hash = Hash.Combine(_newNode.GetHashCode(), hash); } return hash; } // Has to be 'internal' for now as it's used by EnC test tool internal string GetDebuggerDisplay() { var result = Kind.ToString(); switch (Kind) { case EditKind.Delete: return result + " [" + _oldNode.ToString() + "]" + DisplayPosition(_oldNode); case EditKind.Insert: return result + " [" + _newNode.ToString() + "]" + DisplayPosition(_newNode); case EditKind.Update: return result + " [" + _oldNode.ToString() + "]" + DisplayPosition(_oldNode) + " -> [" + _newNode.ToString() + "]" + DisplayPosition(_newNode); case EditKind.Move: case EditKind.Reorder: return result + " [" + _oldNode.ToString() + "]" + DisplayPosition(_oldNode) + " -> " + DisplayPosition(_newNode); } return result; } private string DisplayPosition(TNode node) => "@" + _comparer.GetSpan(node).Start; } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Workspaces/MSBuildTest/Resources/Issue29122/Proj2/ClassLibrary2.vbproj
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{65D39B82-9F22-4350-9BFF-3988C367809B}</ProjectGuid> <OutputType>Library</OutputType> <RootNamespace>ClassLibrary2</RootNamespace> <AssemblyName>ClassLibrary2</AssemblyName> <FileAlignment>512</FileAlignment> <MyType>Windows</MyType> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <TargetFrameworkProfile /> <RestorePackages>true</RestorePackages> </PropertyGroup> <PropertyGroup> <OptionExplicit>On</OptionExplicit> </PropertyGroup> <PropertyGroup> <OptionCompare>Binary</OptionCompare> </PropertyGroup> <PropertyGroup> <OptionStrict>On</OptionStrict> </PropertyGroup> <PropertyGroup> <OptionInfer>On</OptionInfer> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' "> <DebugSymbols>true</DebugSymbols> <DefineDebug>true</DefineDebug> <DefineTrace>true</DefineTrace> <OutputPath>..\Dev\Modules\</OutputPath> <NoWarn> </NoWarn> <DebugType>full</DebugType> <PlatformTarget>x86</PlatformTarget> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' "> <DebugType>pdbonly</DebugType> <DefineDebug>false</DefineDebug> <DefineTrace>true</DefineTrace> <Optimize>true</Optimize> <OutputPath>..\Dev\Modules\</OutputPath> <NoWarn> </NoWarn> <PlatformTarget>x86</PlatformTarget> </PropertyGroup> <ItemGroup> <Compile Include="Class1.vb" /> <Compile Include="My Project\AssemblyInfo.vb" /> <Compile Include="My Project\Application.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Application.myapp</DependentUpon> </Compile> <Compile Include="My Project\Resources.Designer.vb"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> <DependentUpon>Resources.resx</DependentUpon> </Compile> <Compile Include="My Project\Settings.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Settings.settings</DependentUpon> <DesignTimeSharedInput>True</DesignTimeSharedInput> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Include="My Project\Resources.resx"> <Generator>VbMyResourcesResXFileCodeGenerator</Generator> <LastGenOutput>Resources.Designer.vb</LastGenOutput> <CustomToolNamespace>My.Resources</CustomToolNamespace> <SubType>Designer</SubType> </EmbeddedResource> </ItemGroup> <ItemGroup> <None Include="My Project\Application.myapp"> <Generator>MyApplicationCodeGenerator</Generator> <LastGenOutput>Application.Designer.vb</LastGenOutput> </None> <None Include="My Project\Settings.settings"> <Generator>SettingsSingleFileGenerator</Generator> <CustomToolNamespace>My</CustomToolNamespace> <LastGenOutput>Settings.Designer.vb</LastGenOutput> </None> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Proj1\ClassLibrary1.vbproj"> <Project>{f8ae35ab-1ac5-4381-bb3e-0645519695f5}</Project> <Name>ClassLibrary1</Name> <Private>False</Private> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProjectGuid>{65D39B82-9F22-4350-9BFF-3988C367809B}</ProjectGuid> <OutputType>Library</OutputType> <RootNamespace>ClassLibrary2</RootNamespace> <AssemblyName>ClassLibrary2</AssemblyName> <FileAlignment>512</FileAlignment> <MyType>Windows</MyType> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> <TargetFrameworkProfile /> <RestorePackages>true</RestorePackages> </PropertyGroup> <PropertyGroup> <OptionExplicit>On</OptionExplicit> </PropertyGroup> <PropertyGroup> <OptionCompare>Binary</OptionCompare> </PropertyGroup> <PropertyGroup> <OptionStrict>On</OptionStrict> </PropertyGroup> <PropertyGroup> <OptionInfer>On</OptionInfer> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' "> <DebugSymbols>true</DebugSymbols> <DefineDebug>true</DefineDebug> <DefineTrace>true</DefineTrace> <OutputPath>..\Dev\Modules\</OutputPath> <NoWarn> </NoWarn> <DebugType>full</DebugType> <PlatformTarget>x86</PlatformTarget> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' "> <DebugType>pdbonly</DebugType> <DefineDebug>false</DefineDebug> <DefineTrace>true</DefineTrace> <Optimize>true</Optimize> <OutputPath>..\Dev\Modules\</OutputPath> <NoWarn> </NoWarn> <PlatformTarget>x86</PlatformTarget> </PropertyGroup> <ItemGroup> <Compile Include="Class1.vb" /> <Compile Include="My Project\AssemblyInfo.vb" /> <Compile Include="My Project\Application.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Application.myapp</DependentUpon> </Compile> <Compile Include="My Project\Resources.Designer.vb"> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> <DependentUpon>Resources.resx</DependentUpon> </Compile> <Compile Include="My Project\Settings.Designer.vb"> <AutoGen>True</AutoGen> <DependentUpon>Settings.settings</DependentUpon> <DesignTimeSharedInput>True</DesignTimeSharedInput> </Compile> </ItemGroup> <ItemGroup> <EmbeddedResource Include="My Project\Resources.resx"> <Generator>VbMyResourcesResXFileCodeGenerator</Generator> <LastGenOutput>Resources.Designer.vb</LastGenOutput> <CustomToolNamespace>My.Resources</CustomToolNamespace> <SubType>Designer</SubType> </EmbeddedResource> </ItemGroup> <ItemGroup> <None Include="My Project\Application.myapp"> <Generator>MyApplicationCodeGenerator</Generator> <LastGenOutput>Application.Designer.vb</LastGenOutput> </None> <None Include="My Project\Settings.settings"> <Generator>SettingsSingleFileGenerator</Generator> <CustomToolNamespace>My</CustomToolNamespace> <LastGenOutput>Settings.Designer.vb</LastGenOutput> </None> </ItemGroup> <ItemGroup> <ProjectReference Include="..\Proj1\ClassLibrary1.vbproj"> <Project>{f8ae35ab-1ac5-4381-bb3e-0645519695f5}</Project> <Name>ClassLibrary1</Name> <Private>False</Private> </ProjectReference> </ItemGroup> <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" /> </Project>
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Features/CSharp/Portable/Structure/Providers/DisabledTextTriviaStructureProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Shared.Collections; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class DisabledTextTriviaStructureProvider : AbstractSyntaxTriviaStructureProvider { public override void CollectBlockSpans( SyntaxTrivia trivia, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { CollectBlockSpans(trivia.SyntaxTree, trivia, ref spans, cancellationToken); } public static void CollectBlockSpans( SyntaxTree syntaxTree, SyntaxTrivia trivia, ref TemporaryArray<BlockSpan> spans, CancellationToken cancellationToken) { // We'll always be leading trivia of some token. var startPos = trivia.FullSpan.Start; var parentTriviaList = trivia.Token.LeadingTrivia; var indexInParent = parentTriviaList.IndexOf(trivia); // Note: in some error cases (for example when all future tokens end up being skipped) // the parser may end up attaching pre-processor directives as trailing trivia to a // preceding token. if (indexInParent < 0) { parentTriviaList = trivia.Token.TrailingTrivia; indexInParent = parentTriviaList.IndexOf(trivia); } if (indexInParent <= 0) { return; } if (!parentTriviaList[indexInParent - 1].IsKind(SyntaxKind.IfDirectiveTrivia) && !parentTriviaList[indexInParent - 1].IsKind(SyntaxKind.ElifDirectiveTrivia) && !parentTriviaList[indexInParent - 1].IsKind(SyntaxKind.ElseDirectiveTrivia)) { return; } var endTrivia = GetCorrespondingEndTrivia(trivia, parentTriviaList, indexInParent); var endPos = GetEndPositionExludingLastNewLine(syntaxTree, endTrivia, cancellationToken); var span = TextSpan.FromBounds(startPos, endPos); spans.Add(new BlockSpan( isCollapsible: true, textSpan: span, type: BlockTypes.PreprocessorRegion, bannerText: CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } private static int GetEndPositionExludingLastNewLine(SyntaxTree syntaxTree, SyntaxTrivia trivia, CancellationToken cancellationToken) { var endPos = trivia.FullSpan.End; var text = syntaxTree.GetText(cancellationToken); return endPos >= 2 && text[endPos - 1] == '\n' && text[endPos - 2] == '\r' ? endPos - 2 : endPos >= 1 && SyntaxFacts.IsNewLine(text[endPos - 1]) ? endPos - 1 : endPos; } private static SyntaxTrivia GetCorrespondingEndTrivia( SyntaxTrivia trivia, SyntaxTriviaList triviaList, int index) { // Look through our parent token's trivia, to extend the span to the end of the last // disabled trivia. // // The issue is that if there are other pre-processor directives (like #regions or // #lines) mixed in the disabled code, they will be interleaved. Keep walking past // them to the next thing that will actually end a disabled block. When we encounter // one, we must also consider which opening block they end. In case of nested pre-processor // directives, the inner most end block should match the inner most open block and so on. var nestedIfDirectiveTrivia = 0; for (var i = index; i < triviaList.Count; i++) { var currentTrivia = triviaList[i]; switch (currentTrivia.Kind()) { case SyntaxKind.IfDirectiveTrivia: // Hit a nested #if directive. Keep track of this so we can ensure // that our actual disabled region reached the right end point. nestedIfDirectiveTrivia++; continue; case SyntaxKind.EndIfDirectiveTrivia: if (nestedIfDirectiveTrivia > 0) { // This #endif corresponded to a nested #if, pop our stack // and keep searching. nestedIfDirectiveTrivia--; continue; } // Found an #endif corresponding to our original #if/#elif/#else region we // started with. Mark up to the trivia before this as the range to collapse. return triviaList[i - 1]; case SyntaxKind.ElseDirectiveTrivia: case SyntaxKind.ElifDirectiveTrivia: if (nestedIfDirectiveTrivia > 0) { // This #else/#elif corresponded to a nested #if, ignore as // they're not relevant to the original construct we started // on. continue; } // We found the next #else/#elif corresponding to our original #if/#elif/#else // region we started with. Mark up to the trivia before this as the range // to collapse. return triviaList[i - 1]; } } // Couldn't find a future trivia to collapse up to. Just collapse the original // disabled text trivia we started with. return trivia; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Shared.Collections; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class DisabledTextTriviaStructureProvider : AbstractSyntaxTriviaStructureProvider { public override void CollectBlockSpans( SyntaxTrivia trivia, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { CollectBlockSpans(trivia.SyntaxTree, trivia, ref spans, cancellationToken); } public static void CollectBlockSpans( SyntaxTree syntaxTree, SyntaxTrivia trivia, ref TemporaryArray<BlockSpan> spans, CancellationToken cancellationToken) { // We'll always be leading trivia of some token. var startPos = trivia.FullSpan.Start; var parentTriviaList = trivia.Token.LeadingTrivia; var indexInParent = parentTriviaList.IndexOf(trivia); // Note: in some error cases (for example when all future tokens end up being skipped) // the parser may end up attaching pre-processor directives as trailing trivia to a // preceding token. if (indexInParent < 0) { parentTriviaList = trivia.Token.TrailingTrivia; indexInParent = parentTriviaList.IndexOf(trivia); } if (indexInParent <= 0) { return; } if (!parentTriviaList[indexInParent - 1].IsKind(SyntaxKind.IfDirectiveTrivia) && !parentTriviaList[indexInParent - 1].IsKind(SyntaxKind.ElifDirectiveTrivia) && !parentTriviaList[indexInParent - 1].IsKind(SyntaxKind.ElseDirectiveTrivia)) { return; } var endTrivia = GetCorrespondingEndTrivia(trivia, parentTriviaList, indexInParent); var endPos = GetEndPositionExludingLastNewLine(syntaxTree, endTrivia, cancellationToken); var span = TextSpan.FromBounds(startPos, endPos); spans.Add(new BlockSpan( isCollapsible: true, textSpan: span, type: BlockTypes.PreprocessorRegion, bannerText: CSharpStructureHelpers.Ellipsis, autoCollapse: true)); } private static int GetEndPositionExludingLastNewLine(SyntaxTree syntaxTree, SyntaxTrivia trivia, CancellationToken cancellationToken) { var endPos = trivia.FullSpan.End; var text = syntaxTree.GetText(cancellationToken); return endPos >= 2 && text[endPos - 1] == '\n' && text[endPos - 2] == '\r' ? endPos - 2 : endPos >= 1 && SyntaxFacts.IsNewLine(text[endPos - 1]) ? endPos - 1 : endPos; } private static SyntaxTrivia GetCorrespondingEndTrivia( SyntaxTrivia trivia, SyntaxTriviaList triviaList, int index) { // Look through our parent token's trivia, to extend the span to the end of the last // disabled trivia. // // The issue is that if there are other pre-processor directives (like #regions or // #lines) mixed in the disabled code, they will be interleaved. Keep walking past // them to the next thing that will actually end a disabled block. When we encounter // one, we must also consider which opening block they end. In case of nested pre-processor // directives, the inner most end block should match the inner most open block and so on. var nestedIfDirectiveTrivia = 0; for (var i = index; i < triviaList.Count; i++) { var currentTrivia = triviaList[i]; switch (currentTrivia.Kind()) { case SyntaxKind.IfDirectiveTrivia: // Hit a nested #if directive. Keep track of this so we can ensure // that our actual disabled region reached the right end point. nestedIfDirectiveTrivia++; continue; case SyntaxKind.EndIfDirectiveTrivia: if (nestedIfDirectiveTrivia > 0) { // This #endif corresponded to a nested #if, pop our stack // and keep searching. nestedIfDirectiveTrivia--; continue; } // Found an #endif corresponding to our original #if/#elif/#else region we // started with. Mark up to the trivia before this as the range to collapse. return triviaList[i - 1]; case SyntaxKind.ElseDirectiveTrivia: case SyntaxKind.ElifDirectiveTrivia: if (nestedIfDirectiveTrivia > 0) { // This #else/#elif corresponded to a nested #if, ignore as // they're not relevant to the original construct we started // on. continue; } // We found the next #else/#elif corresponding to our original #if/#elif/#else // region we started with. Mark up to the trivia before this as the range // to collapse. return triviaList[i - 1]; } } // Couldn't find a future trivia to collapse up to. Just collapse the original // disabled text trivia we started with. return trivia; } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/EditorFeatures/CSharpTest2/Recommendations/SByteKeywordRecommenderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class SByteKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStackAlloc() { await VerifyKeywordAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInMemberContext() { await VerifyKeywordAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInMemberContext() { await VerifyKeywordAsync( @"class C { ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInMemberContext() { await VerifyKeywordAsync( @"class C { ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEnumBaseTypes() { await VerifyKeywordAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IGoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInBaseList() { await VerifyAbsenceAsync( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType_InBaseList() { await VerifyKeywordAsync( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPartial() { await VerifyAbsenceAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStatic() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterVirtualPublic() { await VerifyKeywordAsync( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThis() { await VerifyKeywordAsync( @"static class C { public static void Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOut() { await VerifyKeywordAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaRef() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaOut() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterParams() { await VerifyKeywordAsync( @"class C { void Goo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInImplicitOperator() { await VerifyKeywordAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExplicitOperator() { await VerifyKeywordAsync( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracket() { await VerifyKeywordAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracketComma() { await VerifyKeywordAsync( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTypeOf() { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInSizeOf() { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContext() { await VerifyKeywordAsync(@" class Program { /// <see cref=""$$""> static void Main(string[] args) { } }"); } [WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContextNotAfterDot() { await VerifyAbsenceAsync(@" /// <see cref=""System.$$"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsyncAsType() => await VerifyKeywordAsync(@"class c { async async $$ }"); [WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCrefTypeParameter() { await VerifyAbsenceAsync(@" using System; /// <see cref=""List{$$}"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task Preselection() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { Helper($$) } static void Helper(sbyte x) { } } "); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinType() { await VerifyKeywordAsync(@" class Program { ($$ }"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinMember() { await VerifyKeywordAsync(@" class Program { void Method() { ($$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerType() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))] public async Task TestAfterKeywordIndicatingLocalFunction(string keyword) { await VerifyKeywordAsync(AddInsideMethod($@" {keyword} $$")); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class SByteKeywordRecommenderTests : KeywordRecommenderTests { [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAtRoot_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterClass_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"class C { } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalStatement_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterGlobalVariableDeclaration_Interactive() { await VerifyKeywordAsync(SourceCodeKind.Script, @"int i = 0; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInUsingAlias() { await VerifyAbsenceAsync( @"using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInGlobalUsingAlias() { await VerifyAbsenceAsync( @"global using Goo = $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterStackAlloc() { await VerifyKeywordAsync( @"class C { int* goo = stackalloc $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFixedStatement() { await VerifyKeywordAsync( @"fixed ($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDelegateReturnType() { await VerifyKeywordAsync( @"public delegate $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCastType2() { await VerifyKeywordAsync(AddInsideMethod( @"var str = (($$)items) as string;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInMemberContext() { await VerifyKeywordAsync( @"class C { const $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInMemberContext() { await VerifyKeywordAsync( @"class C { ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInMemberContext() { await VerifyKeywordAsync( @"class C { ref readonly $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"const $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyInStatementContext() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"const $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int local;")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefReadonlyLocalFunction() { await VerifyKeywordAsync(AddInsideMethod( @"ref readonly $$ int Function();")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRefExpression() { await VerifyKeywordAsync(AddInsideMethod( @"ref int x = ref $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInEmptyStatement() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestEnumBaseTypes() { await VerifyKeywordAsync( @"enum E : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType1() { await VerifyKeywordAsync(AddInsideMethod( @"IList<$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType2() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType3() { await VerifyKeywordAsync(AddInsideMethod( @"IList<int[],$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType4() { await VerifyKeywordAsync(AddInsideMethod( @"IList<IGoo<int?,byte*>,$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInBaseList() { await VerifyAbsenceAsync( @"class C : $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInGenericType_InBaseList() { await VerifyKeywordAsync( @"class C : IList<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo is $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAs() { await VerifyKeywordAsync(AddInsideMethod( @"var v = goo as $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethod() { await VerifyKeywordAsync( @"class C { void Goo() {} $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterField() { await VerifyKeywordAsync( @"class C { int i; $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterProperty() { await VerifyKeywordAsync( @"class C { int i { get; } $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAttribute() { await VerifyKeywordAsync( @"class C { [goo] $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideStruct() { await VerifyKeywordAsync( @"struct S { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideInterface() { await VerifyKeywordAsync( @"interface I { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInsideClass() { await VerifyKeywordAsync( @"class C { $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterPartial() => await VerifyAbsenceAsync(@"partial $$"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterNestedPartial() { await VerifyAbsenceAsync( @"class C { partial $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedAbstract() { await VerifyKeywordAsync( @"class C { abstract $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedInternal() { await VerifyKeywordAsync( @"class C { internal $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStaticPublic() { await VerifyKeywordAsync( @"class C { static public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublicStatic() { await VerifyKeywordAsync( @"class C { public static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterVirtualPublic() { await VerifyKeywordAsync( @"class C { virtual public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPublic() { await VerifyKeywordAsync( @"class C { public $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedPrivate() { await VerifyKeywordAsync( @"class C { private $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedProtected() { await VerifyKeywordAsync( @"class C { protected $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedSealed() { await VerifyKeywordAsync( @"class C { sealed $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNestedStatic() { await VerifyKeywordAsync( @"class C { static $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInLocalVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"$$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"for ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInForeachVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"foreach ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInUsingVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"using ($$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFromVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInJoinVariableDeclaration() { await VerifyKeywordAsync(AddInsideMethod( @"var q = from a in b join $$")); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodOpenParen() { await VerifyKeywordAsync( @"class C { void Goo($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodComma() { await VerifyKeywordAsync( @"class C { void Goo(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterMethodAttribute() { await VerifyKeywordAsync( @"class C { void Goo(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorOpenParen() { await VerifyKeywordAsync( @"class C { public C($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorComma() { await VerifyKeywordAsync( @"class C { public C(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterConstructorAttribute() { await VerifyKeywordAsync( @"class C { public C(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateOpenParen() { await VerifyKeywordAsync( @"delegate void D($$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateComma() { await VerifyKeywordAsync( @"delegate void D(int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterDelegateAttribute() { await VerifyKeywordAsync( @"delegate void D(int i, [Goo]$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterThis() { await VerifyKeywordAsync( @"static class C { public static void Goo(this $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterRef() { await VerifyKeywordAsync( @"class C { void Goo(ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterOut() { await VerifyKeywordAsync( @"class C { void Goo(out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaRef() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterLambdaOut() { await VerifyKeywordAsync( @"class C { void Goo() { System.Func<int, int> f = (out $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterParams() { await VerifyKeywordAsync( @"class C { void Goo(params $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInImplicitOperator() { await VerifyKeywordAsync( @"class C { public static implicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInExplicitOperator() { await VerifyKeywordAsync( @"class C { public static explicit operator $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracket() { await VerifyKeywordAsync( @"class C { int this[$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterIndexerBracketComma() { await VerifyKeywordAsync( @"class C { int this[int i, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterNewInExpression() { await VerifyKeywordAsync(AddInsideMethod( @"new $$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTypeOf() { await VerifyKeywordAsync(AddInsideMethod( @"typeof($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInDefault() { await VerifyKeywordAsync(AddInsideMethod( @"default($$")); } [WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInSizeOf() { await VerifyKeywordAsync(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInObjectInitializerMemberContext() { await VerifyAbsenceAsync(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContext() { await VerifyKeywordAsync(@" class Program { /// <see cref=""$$""> static void Main(string[] args) { } }"); } [WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInCrefContextNotAfterDot() { await VerifyAbsenceAsync(@" /// <see cref=""System.$$"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsync() => await VerifyKeywordAsync(@"class c { async $$ }"); [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestAfterAsyncAsType() => await VerifyKeywordAsync(@"class c { async async $$ }"); [WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotInCrefTypeParameter() { await VerifyAbsenceAsync(@" using System; /// <see cref=""List{$$}"" /> class C { } "); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task Preselection() { await VerifyKeywordAsync(@" class Program { static void Main(string[] args) { Helper($$) } static void Helper(sbyte x) { } } "); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinType() { await VerifyKeywordAsync(@" class Program { ($$ }"); } [WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")] [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInTupleWithinMember() { await VerifyKeywordAsync(@" class Program { void Method() { ($$ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerType() { await VerifyKeywordAsync(@" class C { delegate*<$$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterComma() { await VerifyKeywordAsync(@" class C { delegate*<int, $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestInFunctionPointerTypeAfterModifier() { await VerifyKeywordAsync(@" class C { delegate*<ref $$"); } [Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public async Task TestNotAfterDelegateAsterisk() { await VerifyAbsenceAsync(@" class C { delegate*$$"); } [WorkItem(53585, "https://github.com/dotnet/roslyn/issues/53585")] [Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] [ClassData(typeof(TheoryDataKeywordsIndicatingLocalFunction))] public async Task TestAfterKeywordIndicatingLocalFunction(string keyword) { await VerifyKeywordAsync(AddInsideMethod($@" {keyword} $$")); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxKindExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class SyntaxKindExtensions { /// <summary> /// Determine if the given <see cref="SyntaxKind"/> array contains the given kind. /// </summary> /// <param name="kinds">Array to search</param> /// <param name="kind">Sought value</param> /// <returns>True if <paramref name = "kinds"/> contains the value<paramref name= "kind"/>.</returns> /// <remarks>PERF: Not using Array.IndexOf here because it results in a call to IndexOf on the /// default EqualityComparer for SyntaxKind.The default comparer for SyntaxKind is the /// ObjectEqualityComparer which results in boxing allocations.</remarks> public static bool Contains(this SyntaxKind[] kinds, SyntaxKind kind) { foreach (var k in kinds) { if (k == kind) { return true; } } return false; } public static SyntaxKind MapCompoundAssignmentKindToBinaryExpressionKind(this SyntaxKind syntaxKind) { switch (syntaxKind) { case SyntaxKind.AddAssignmentExpression: return SyntaxKind.AddExpression; case SyntaxKind.SubtractAssignmentExpression: return SyntaxKind.SubtractExpression; case SyntaxKind.MultiplyAssignmentExpression: return SyntaxKind.MultiplyExpression; case SyntaxKind.DivideAssignmentExpression: return SyntaxKind.DivideExpression; case SyntaxKind.ModuloAssignmentExpression: return SyntaxKind.ModuloExpression; case SyntaxKind.AndAssignmentExpression: return SyntaxKind.BitwiseAndExpression; case SyntaxKind.ExclusiveOrAssignmentExpression: return SyntaxKind.ExclusiveOrExpression; case SyntaxKind.OrAssignmentExpression: return SyntaxKind.BitwiseOrExpression; case SyntaxKind.LeftShiftAssignmentExpression: return SyntaxKind.LeftShiftExpression; case SyntaxKind.RightShiftAssignmentExpression: return SyntaxKind.RightShiftExpression; case SyntaxKind.CoalesceAssignmentExpression: return SyntaxKind.CoalesceExpression; default: Debug.Fail($"Unhandled compound assignment kind: {syntaxKind}"); return SyntaxKind.None; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class SyntaxKindExtensions { /// <summary> /// Determine if the given <see cref="SyntaxKind"/> array contains the given kind. /// </summary> /// <param name="kinds">Array to search</param> /// <param name="kind">Sought value</param> /// <returns>True if <paramref name = "kinds"/> contains the value<paramref name= "kind"/>.</returns> /// <remarks>PERF: Not using Array.IndexOf here because it results in a call to IndexOf on the /// default EqualityComparer for SyntaxKind.The default comparer for SyntaxKind is the /// ObjectEqualityComparer which results in boxing allocations.</remarks> public static bool Contains(this SyntaxKind[] kinds, SyntaxKind kind) { foreach (var k in kinds) { if (k == kind) { return true; } } return false; } public static SyntaxKind MapCompoundAssignmentKindToBinaryExpressionKind(this SyntaxKind syntaxKind) { switch (syntaxKind) { case SyntaxKind.AddAssignmentExpression: return SyntaxKind.AddExpression; case SyntaxKind.SubtractAssignmentExpression: return SyntaxKind.SubtractExpression; case SyntaxKind.MultiplyAssignmentExpression: return SyntaxKind.MultiplyExpression; case SyntaxKind.DivideAssignmentExpression: return SyntaxKind.DivideExpression; case SyntaxKind.ModuloAssignmentExpression: return SyntaxKind.ModuloExpression; case SyntaxKind.AndAssignmentExpression: return SyntaxKind.BitwiseAndExpression; case SyntaxKind.ExclusiveOrAssignmentExpression: return SyntaxKind.ExclusiveOrExpression; case SyntaxKind.OrAssignmentExpression: return SyntaxKind.BitwiseOrExpression; case SyntaxKind.LeftShiftAssignmentExpression: return SyntaxKind.LeftShiftExpression; case SyntaxKind.RightShiftAssignmentExpression: return SyntaxKind.RightShiftExpression; case SyntaxKind.CoalesceAssignmentExpression: return SyntaxKind.CoalesceExpression; default: Debug.Fail($"Unhandled compound assignment kind: {syntaxKind}"); return SyntaxKind.None; } } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/VisualStudio/CSharp/Impl/Options/Formatting/WrappingViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { /// <summary> /// Interaction logic for FormattingWrappingOptionPage.xaml /// </summary> internal class WrappingViewModel : AbstractOptionPreviewViewModel { private const string s_blockPreview = @" class C { //[ public int Goo { get; set; } //] }"; private const string s_declarationPreview = @" class C{ void goo() { //[ int i = 0; string name = ""John""; //] } }"; public WrappingViewModel(OptionStore optionStore, IServiceProvider serviceProvider) : base(optionStore, serviceProvider, LanguageNames.CSharp) { Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.WrappingPreserveSingleLine, CSharpVSResources.Leave_block_on_single_line, s_blockPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, CSharpVSResources.Leave_statements_and_member_declarations_on_the_same_line, s_declarationPreview, this, optionStore)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { /// <summary> /// Interaction logic for FormattingWrappingOptionPage.xaml /// </summary> internal class WrappingViewModel : AbstractOptionPreviewViewModel { private const string s_blockPreview = @" class C { //[ public int Goo { get; set; } //] }"; private const string s_declarationPreview = @" class C{ void goo() { //[ int i = 0; string name = ""John""; //] } }"; public WrappingViewModel(OptionStore optionStore, IServiceProvider serviceProvider) : base(optionStore, serviceProvider, LanguageNames.CSharp) { Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.WrappingPreserveSingleLine, CSharpVSResources.Leave_block_on_single_line, s_blockPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, CSharpVSResources.Leave_statements_and_member_declarations_on_the_same_line, s_declarationPreview, this, optionStore)); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/VisualStudio/Core/Def/Implementation/InheritanceMargin/MarginGlyph/MenuItemViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { internal abstract class MenuItemViewModel { /// <summary> /// Display content for the target. /// </summary> public string DisplayContent { get; } /// <summary> /// ImageMoniker shown in the menu. /// </summary> public ImageMoniker ImageMoniker { get; } /// <summary> /// AutomationName for the MenuItem. /// </summary> public string AutomationName { get; } protected MenuItemViewModel(string displayContent, ImageMoniker imageMoniker, string automationName) { ImageMoniker = imageMoniker; DisplayContent = displayContent; AutomationName = automationName; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.VisualStudio.Imaging.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin.MarginGlyph { internal abstract class MenuItemViewModel { /// <summary> /// Display content for the target. /// </summary> public string DisplayContent { get; } /// <summary> /// ImageMoniker shown in the menu. /// </summary> public ImageMoniker ImageMoniker { get; } /// <summary> /// AutomationName for the MenuItem. /// </summary> public string AutomationName { get; } protected MenuItemViewModel(string displayContent, ImageMoniker imageMoniker, string automationName) { ImageMoniker = imageMoniker; DisplayContent = displayContent; AutomationName = automationName; } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/Shared/GlobalAssemblyCacheHelpers/GlobalAssemblyCache.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Globalization; using System.Reflection; namespace Microsoft.CodeAnalysis { /// <summary> /// Provides APIs to enumerate and look up assemblies stored in the Global Assembly Cache. /// </summary> internal abstract class GlobalAssemblyCache { internal static readonly GlobalAssemblyCache Instance = CreateInstance(); private static GlobalAssemblyCache CreateInstance() { if (Type.GetType("Mono.Runtime") != null) { return new MonoGlobalAssemblyCache(); } else { return new ClrGlobalAssemblyCache(); } } /// <summary> /// Represents the current Processor architecture. /// </summary> public static readonly ImmutableArray<ProcessorArchitecture> CurrentArchitectures = (IntPtr.Size == 4) ? ImmutableArray.Create(ProcessorArchitecture.None, ProcessorArchitecture.MSIL, ProcessorArchitecture.X86) : ImmutableArray.Create(ProcessorArchitecture.None, ProcessorArchitecture.MSIL, ProcessorArchitecture.Amd64); /// <summary> /// Enumerates assemblies in the GAC returning those that match given partial name and /// architecture. /// </summary> /// <param name="partialName">Optional partial name.</param> /// <param name="architectureFilter">Optional architecture filter.</param> public abstract IEnumerable<AssemblyIdentity> GetAssemblyIdentities(AssemblyName partialName, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)); /// <summary> /// Enumerates assemblies in the GAC returning those that match given partial name and /// architecture. /// </summary> /// <param name="partialName">The optional partial name.</param> /// <param name="architectureFilter">The optional architecture filter.</param> public abstract IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName = null, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)); /// <summary> /// Enumerates assemblies in the GAC returning their simple names. /// </summary> /// <param name="architectureFilter">Optional architecture filter.</param> /// <returns>Unique simple names of GAC assemblies.</returns> public abstract IEnumerable<string> GetAssemblySimpleNames(ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)); /// <summary> /// Looks up specified partial assembly name in the GAC and returns the best matching <see cref="AssemblyIdentity"/>. /// </summary> /// <param name="displayName">The display name of an assembly</param> /// <param name="architectureFilter">The optional processor architecture</param> /// <param name="preferredCulture">The optional preferred culture information</param> /// <returns>An assembly identity or null, if <paramref name="displayName"/> can't be resolved.</returns> /// <exception cref="ArgumentNullException"><paramref name="displayName"/> is null.</exception> public AssemblyIdentity ResolvePartialName( string displayName, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>), CultureInfo preferredCulture = null) { string location; return ResolvePartialName(displayName, out location, architectureFilter, preferredCulture); } /// <summary> /// Looks up specified partial assembly name in the GAC and returns the best matching <see cref="AssemblyIdentity"/>. /// </summary> /// <param name="displayName">The display name of an assembly</param> /// <param name="location">Full path name of the resolved assembly</param> /// <param name="architectureFilter">The optional processor architecture</param> /// <param name="preferredCulture">The optional preferred culture information</param> /// <returns>An assembly identity or null, if <paramref name="displayName"/> can't be resolved.</returns> /// <exception cref="ArgumentNullException"><paramref name="displayName"/> is null.</exception> public abstract AssemblyIdentity ResolvePartialName( string displayName, out string location, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>), CultureInfo preferredCulture = 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.Generic; using System.Collections.Immutable; using System.Globalization; using System.Reflection; namespace Microsoft.CodeAnalysis { /// <summary> /// Provides APIs to enumerate and look up assemblies stored in the Global Assembly Cache. /// </summary> internal abstract class GlobalAssemblyCache { internal static readonly GlobalAssemblyCache Instance = CreateInstance(); private static GlobalAssemblyCache CreateInstance() { if (Type.GetType("Mono.Runtime") != null) { return new MonoGlobalAssemblyCache(); } else { return new ClrGlobalAssemblyCache(); } } /// <summary> /// Represents the current Processor architecture. /// </summary> public static readonly ImmutableArray<ProcessorArchitecture> CurrentArchitectures = (IntPtr.Size == 4) ? ImmutableArray.Create(ProcessorArchitecture.None, ProcessorArchitecture.MSIL, ProcessorArchitecture.X86) : ImmutableArray.Create(ProcessorArchitecture.None, ProcessorArchitecture.MSIL, ProcessorArchitecture.Amd64); /// <summary> /// Enumerates assemblies in the GAC returning those that match given partial name and /// architecture. /// </summary> /// <param name="partialName">Optional partial name.</param> /// <param name="architectureFilter">Optional architecture filter.</param> public abstract IEnumerable<AssemblyIdentity> GetAssemblyIdentities(AssemblyName partialName, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)); /// <summary> /// Enumerates assemblies in the GAC returning those that match given partial name and /// architecture. /// </summary> /// <param name="partialName">The optional partial name.</param> /// <param name="architectureFilter">The optional architecture filter.</param> public abstract IEnumerable<AssemblyIdentity> GetAssemblyIdentities(string partialName = null, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)); /// <summary> /// Enumerates assemblies in the GAC returning their simple names. /// </summary> /// <param name="architectureFilter">Optional architecture filter.</param> /// <returns>Unique simple names of GAC assemblies.</returns> public abstract IEnumerable<string> GetAssemblySimpleNames(ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>)); /// <summary> /// Looks up specified partial assembly name in the GAC and returns the best matching <see cref="AssemblyIdentity"/>. /// </summary> /// <param name="displayName">The display name of an assembly</param> /// <param name="architectureFilter">The optional processor architecture</param> /// <param name="preferredCulture">The optional preferred culture information</param> /// <returns>An assembly identity or null, if <paramref name="displayName"/> can't be resolved.</returns> /// <exception cref="ArgumentNullException"><paramref name="displayName"/> is null.</exception> public AssemblyIdentity ResolvePartialName( string displayName, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>), CultureInfo preferredCulture = null) { string location; return ResolvePartialName(displayName, out location, architectureFilter, preferredCulture); } /// <summary> /// Looks up specified partial assembly name in the GAC and returns the best matching <see cref="AssemblyIdentity"/>. /// </summary> /// <param name="displayName">The display name of an assembly</param> /// <param name="location">Full path name of the resolved assembly</param> /// <param name="architectureFilter">The optional processor architecture</param> /// <param name="preferredCulture">The optional preferred culture information</param> /// <returns>An assembly identity or null, if <paramref name="displayName"/> can't be resolved.</returns> /// <exception cref="ArgumentNullException"><paramref name="displayName"/> is null.</exception> public abstract AssemblyIdentity ResolvePartialName( string displayName, out string location, ImmutableArray<ProcessorArchitecture> architectureFilter = default(ImmutableArray<ProcessorArchitecture>), CultureInfo preferredCulture = null); } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/Core/Portable/Diagnostic/CommonDiagnosticComparer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal sealed class CommonDiagnosticComparer : IEqualityComparer<Diagnostic> { internal static readonly CommonDiagnosticComparer Instance = new CommonDiagnosticComparer(); private CommonDiagnosticComparer() { } public bool Equals(Diagnostic? x, Diagnostic? y) { if (object.ReferenceEquals(x, y)) { return true; } if (x == null || y == null) { return false; } return x.Location == y.Location && x.Id == y.Id; } public int GetHashCode(Diagnostic obj) { if (object.ReferenceEquals(obj, null)) { return 0; } return Hash.Combine(obj.Location, obj.Id.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.Collections.Generic; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal sealed class CommonDiagnosticComparer : IEqualityComparer<Diagnostic> { internal static readonly CommonDiagnosticComparer Instance = new CommonDiagnosticComparer(); private CommonDiagnosticComparer() { } public bool Equals(Diagnostic? x, Diagnostic? y) { if (object.ReferenceEquals(x, y)) { return true; } if (x == null || y == null) { return false; } return x.Location == y.Location && x.Id == y.Id; } public int GetHashCode(Diagnostic obj) { if (object.ReferenceEquals(obj, null)) { return 0; } return Hash.Combine(obj.Location, obj.Id.GetHashCode()); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Features/Core/Portable/Shared/Options/ServiceFeatureOnOffOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Options; namespace Microsoft.CodeAnalysis.Shared.Options { internal static class ServiceFeatureOnOffOptions { /// <summary> /// This option is used by TypeScript. /// </summary> #pragma warning disable RS0030 // Do not used banned APIs - to avoid a binary breaking API change. public static readonly PerLanguageOption<bool> RemoveDocumentDiagnosticsOnDocumentClose = new( "ServiceFeatureOnOffOptions", "RemoveDocumentDiagnosticsOnDocumentClose", defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RemoveDocumentDiagnosticsOnDocumentClose")); #pragma warning restore RS0030 // Do not used banned APIs } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Options; namespace Microsoft.CodeAnalysis.Shared.Options { internal static class ServiceFeatureOnOffOptions { /// <summary> /// This option is used by TypeScript. /// </summary> #pragma warning disable RS0030 // Do not used banned APIs - to avoid a binary breaking API change. public static readonly PerLanguageOption<bool> RemoveDocumentDiagnosticsOnDocumentClose = new( "ServiceFeatureOnOffOptions", "RemoveDocumentDiagnosticsOnDocumentClose", defaultValue: false, storageLocation: new RoamingProfileStorageLocation("TextEditor.%LANGUAGE%.Specific.RemoveDocumentDiagnosticsOnDocumentClose")); #pragma warning restore RS0030 // Do not used banned APIs } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_MultipleLocalDeclarations.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode? VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node) { return VisitMultipleLocalDeclarationsBase(node); } public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) { return VisitMultipleLocalDeclarationsBase(node); } private BoundNode? VisitMultipleLocalDeclarationsBase(BoundMultipleLocalDeclarationsBase node) { ArrayBuilder<BoundStatement>? inits = null; foreach (var decl in node.LocalDeclarations) { var init = VisitLocalDeclaration(decl); if (init != null) { if (inits == null) { inits = ArrayBuilder<BoundStatement>.GetInstance(); } inits.Add((BoundStatement)init); } } if (inits != null) { return BoundStatementList.Synthesized(node.Syntax, node.HasErrors, inits.ToImmutableAndFree()); } else { // no initializers return null; // TODO: but what if hasErrors? Have we lost that? } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp { internal sealed partial class LocalRewriter { public override BoundNode? VisitMultipleLocalDeclarations(BoundMultipleLocalDeclarations node) { return VisitMultipleLocalDeclarationsBase(node); } public override BoundNode? VisitUsingLocalDeclarations(BoundUsingLocalDeclarations node) { return VisitMultipleLocalDeclarationsBase(node); } private BoundNode? VisitMultipleLocalDeclarationsBase(BoundMultipleLocalDeclarationsBase node) { ArrayBuilder<BoundStatement>? inits = null; foreach (var decl in node.LocalDeclarations) { var init = VisitLocalDeclaration(decl); if (init != null) { if (inits == null) { inits = ArrayBuilder<BoundStatement>.GetInstance(); } inits.Add((BoundStatement)init); } } if (inits != null) { return BoundStatementList.Synthesized(node.Syntax, node.HasErrors, inits.ToImmutableAndFree()); } else { // no initializers return null; // TODO: but what if hasErrors? Have we lost that? } } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/EditorFeatures/CSharpTest/EncapsulateField/EncapsulateFieldCommandHandlerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Xml.Linq; using Microsoft.CodeAnalysis.Editor.CSharp.EncapsulateField; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EncapsulateField { [UseExportProvider] public class EncapsulateFieldCommandHandlerTests { [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public void EncapsulatePrivateField() { var text = @" class C { private int f$$ield; private void goo() { field = 3; } }"; var expected = @" class C { private int field; public int Field { get { return field; } set { field = value; } } private void goo() { Field = 3; } }"; using var state = EncapsulateFieldTestState.Create(text); state.AssertEncapsulateAs(expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public void EncapsulateNonPrivateField() { var text = @" class C { protected int fi$$eld; private void goo() { field = 3; } }"; var expected = @" class C { private int field; protected int Field { get { return field; } set { field = value; } } private void goo() { Field = 3; } }"; using var state = EncapsulateFieldTestState.Create(text); state.AssertEncapsulateAs(expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public void DialogShownIfNotFieldsFound() { var text = @" class$$ C { private int field; private void goo() { field = 3; } }"; using var state = EncapsulateFieldTestState.Create(text); state.AssertError(); } [WorkItem(1086632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1086632")] [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public void EncapsulateTwoFields() { var text = @" class Program { [|static int A = 1; static int B = A;|] static void Main(string[] args) { System.Console.WriteLine(A); System.Console.WriteLine(B); } } "; var expected = @" class Program { static int A = 1; static int B = A1; public static int A1 { get { return A; } set { A = value; } } public static int B1 { get { return B; } set { B = value; } } static void Main(string[] args) { System.Console.WriteLine(A1); System.Console.WriteLine(B1); } } "; using var state = EncapsulateFieldTestState.Create(text); state.AssertEncapsulateAs(expected); } [WpfFact] [Trait(Traits.Feature, Traits.Features.EncapsulateField)] [Trait(Traits.Feature, Traits.Features.Interactive)] public void EncapsulateFieldCommandDisabledInSubmission() { using var workspace = TestWorkspace.Create(XElement.Parse(@" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> class C { object $$goo; } </Submission> </Workspace> "), workspaceKind: WorkspaceKind.Interactive, composition: EditorTestCompositions.EditorFeaturesWpf); // Force initialization. workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList(); var textView = workspace.Documents.Single().GetTextView(); var handler = workspace.ExportProvider.GetCommandHandler<EncapsulateFieldCommandHandler>(PredefinedCommandHandlerNames.EncapsulateField, ContentTypeNames.CSharpContentType); var state = handler.GetCommandState(new EncapsulateFieldCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Xml.Linq; using Microsoft.CodeAnalysis.Editor.CSharp.EncapsulateField; using Microsoft.CodeAnalysis.Editor.UnitTests; using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.EncapsulateField { [UseExportProvider] public class EncapsulateFieldCommandHandlerTests { [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public void EncapsulatePrivateField() { var text = @" class C { private int f$$ield; private void goo() { field = 3; } }"; var expected = @" class C { private int field; public int Field { get { return field; } set { field = value; } } private void goo() { Field = 3; } }"; using var state = EncapsulateFieldTestState.Create(text); state.AssertEncapsulateAs(expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public void EncapsulateNonPrivateField() { var text = @" class C { protected int fi$$eld; private void goo() { field = 3; } }"; var expected = @" class C { private int field; protected int Field { get { return field; } set { field = value; } } private void goo() { Field = 3; } }"; using var state = EncapsulateFieldTestState.Create(text); state.AssertEncapsulateAs(expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public void DialogShownIfNotFieldsFound() { var text = @" class$$ C { private int field; private void goo() { field = 3; } }"; using var state = EncapsulateFieldTestState.Create(text); state.AssertError(); } [WorkItem(1086632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1086632")] [WpfFact, Trait(Traits.Feature, Traits.Features.EncapsulateField)] public void EncapsulateTwoFields() { var text = @" class Program { [|static int A = 1; static int B = A;|] static void Main(string[] args) { System.Console.WriteLine(A); System.Console.WriteLine(B); } } "; var expected = @" class Program { static int A = 1; static int B = A1; public static int A1 { get { return A; } set { A = value; } } public static int B1 { get { return B; } set { B = value; } } static void Main(string[] args) { System.Console.WriteLine(A1); System.Console.WriteLine(B1); } } "; using var state = EncapsulateFieldTestState.Create(text); state.AssertEncapsulateAs(expected); } [WpfFact] [Trait(Traits.Feature, Traits.Features.EncapsulateField)] [Trait(Traits.Feature, Traits.Features.Interactive)] public void EncapsulateFieldCommandDisabledInSubmission() { using var workspace = TestWorkspace.Create(XElement.Parse(@" <Workspace> <Submission Language=""C#"" CommonReferences=""true""> class C { object $$goo; } </Submission> </Workspace> "), workspaceKind: WorkspaceKind.Interactive, composition: EditorTestCompositions.EditorFeaturesWpf); // Force initialization. workspace.GetOpenDocumentIds().Select(id => workspace.GetTestDocument(id).GetTextView()).ToList(); var textView = workspace.Documents.Single().GetTextView(); var handler = workspace.ExportProvider.GetCommandHandler<EncapsulateFieldCommandHandler>(PredefinedCommandHandlerNames.EncapsulateField, ContentTypeNames.CSharpContentType); var state = handler.GetCommandState(new EncapsulateFieldCommandArgs(textView, textView.TextBuffer)); Assert.True(state.IsUnspecified); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/Core/Portable/Syntax/InternalSyntax/GreenNodeExtensions.cs
// Licensed to the .NET Foundation under one or more 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.Syntax.InternalSyntax { internal static class GreenNodeExtensions { internal static SyntaxList<T> ToGreenList<T>(this SyntaxNode? node) where T : GreenNode { return node != null ? ToGreenList<T>(node.Green) : default(SyntaxList<T>); } internal static SeparatedSyntaxList<T> ToGreenSeparatedList<T>(this SyntaxNode? node) where T : GreenNode { return node != null ? new SeparatedSyntaxList<T>(ToGreenList<T>(node.Green)) : default(SeparatedSyntaxList<T>); } internal static SyntaxList<T> ToGreenList<T>(this GreenNode? node) where T : GreenNode { return new SyntaxList<T>(node); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { internal static class GreenNodeExtensions { internal static SyntaxList<T> ToGreenList<T>(this SyntaxNode? node) where T : GreenNode { return node != null ? ToGreenList<T>(node.Green) : default(SyntaxList<T>); } internal static SeparatedSyntaxList<T> ToGreenSeparatedList<T>(this SyntaxNode? node) where T : GreenNode { return node != null ? new SeparatedSyntaxList<T>(ToGreenList<T>(node.Green)) : default(SeparatedSyntaxList<T>); } internal static SyntaxList<T> ToGreenList<T>(this GreenNode? node) where T : GreenNode { return new SyntaxList<T>(node); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Features/Core/Portable/GenerateMember/GenerateConstructor/GenerateConstructorHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor { internal static class GenerateConstructorHelpers { public static bool CanDelegateTo<TExpressionSyntax>( SemanticDocument document, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<TExpressionSyntax?> expressions, IMethodSymbol constructor) where TExpressionSyntax : SyntaxNode { // Look for constructors in this specified type that are: // 1. Accessible. We obviously need our constructor to be able to call that other constructor. // 2. Won't cause a cycle. i.e. if we're generating a new constructor from an existing constructor, // then we don't want it calling back into us. // 3. Are compatible with the parameters we're generating for this constructor. Compatible means there // exists an implicit conversion from the new constructor's parameter types to the existing // constructor's parameter types. var semanticFacts = document.Document.GetRequiredLanguageService<ISemanticFactsService>(); var semanticModel = document.SemanticModel; var compilation = semanticModel.Compilation; return constructor.Parameters.Length == parameters.Length && constructor.Parameters.SequenceEqual(parameters, (p1, p2) => p1.RefKind == p2.RefKind) && IsSymbolAccessible(compilation, constructor) && IsCompatible(semanticFacts, semanticModel, constructor, expressions); } private static bool IsSymbolAccessible(Compilation compilation, ISymbol symbol) { if (symbol == null) return false; if (symbol is IPropertySymbol { SetMethod: { } setMethod } property && !IsSymbolAccessible(compilation, setMethod)) { 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 compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo(symbol.ContainingAssembly); default: return false; } } private static bool IsCompatible<TExpressionSyntax>( ISemanticFactsService semanticFacts, SemanticModel semanticModel, IMethodSymbol constructor, ImmutableArray<TExpressionSyntax?> expressions) where TExpressionSyntax : SyntaxNode { Debug.Assert(constructor.Parameters.Length == expressions.Length); // Resolve the constructor into our semantic model's compilation; if the constructor we're looking at is from // another project with a different language. var constructorInCompilation = (IMethodSymbol?)SymbolKey.Create(constructor).Resolve(semanticModel.Compilation).Symbol; if (constructorInCompilation == null) { // If the constructor can't be mapped into our invocation project, we'll just bail. // Note the logic in this method doesn't handle a complicated case where: // // 1. Project A has some public type. // 2. Project B references A, and has one constructor that uses the public type from A. // 3. Project C, which references B but not A, has an invocation of B's constructor passing some // parameters. // // The algorithm of this class tries to map the constructor in B (that we might delegate to) into // C, but that constructor might not be mappable if the public type from A is not available. // However, theoretically the public type from A could have a user-defined conversion. // The alternative approach might be to map the type of the parameters back into B, and then // classify the conversions in Project B, but that'll run into other issues if the experssions // don't have a natural type (like default). We choose to ignore all complicated cases here. return false; } for (var i = 0; i < constructorInCompilation.Parameters.Length; i++) { var constructorParameter = constructorInCompilation.Parameters[i]; if (constructorParameter == null) return false; // In VB the argument may not have been specified at all if the parameter is optional if (expressions[i] is null && constructorParameter.IsOptional) continue; var conversion = semanticFacts.ClassifyConversion(semanticModel, expressions[i], constructorParameter.Type); if (!conversion.IsIdentity && !conversion.IsImplicit) return false; } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor { internal static class GenerateConstructorHelpers { public static bool CanDelegateTo<TExpressionSyntax>( SemanticDocument document, ImmutableArray<IParameterSymbol> parameters, ImmutableArray<TExpressionSyntax?> expressions, IMethodSymbol constructor) where TExpressionSyntax : SyntaxNode { // Look for constructors in this specified type that are: // 1. Accessible. We obviously need our constructor to be able to call that other constructor. // 2. Won't cause a cycle. i.e. if we're generating a new constructor from an existing constructor, // then we don't want it calling back into us. // 3. Are compatible with the parameters we're generating for this constructor. Compatible means there // exists an implicit conversion from the new constructor's parameter types to the existing // constructor's parameter types. var semanticFacts = document.Document.GetRequiredLanguageService<ISemanticFactsService>(); var semanticModel = document.SemanticModel; var compilation = semanticModel.Compilation; return constructor.Parameters.Length == parameters.Length && constructor.Parameters.SequenceEqual(parameters, (p1, p2) => p1.RefKind == p2.RefKind) && IsSymbolAccessible(compilation, constructor) && IsCompatible(semanticFacts, semanticModel, constructor, expressions); } private static bool IsSymbolAccessible(Compilation compilation, ISymbol symbol) { if (symbol == null) return false; if (symbol is IPropertySymbol { SetMethod: { } setMethod } property && !IsSymbolAccessible(compilation, setMethod)) { 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 compilation.Assembly.IsSameAssemblyOrHasFriendAccessTo(symbol.ContainingAssembly); default: return false; } } private static bool IsCompatible<TExpressionSyntax>( ISemanticFactsService semanticFacts, SemanticModel semanticModel, IMethodSymbol constructor, ImmutableArray<TExpressionSyntax?> expressions) where TExpressionSyntax : SyntaxNode { Debug.Assert(constructor.Parameters.Length == expressions.Length); // Resolve the constructor into our semantic model's compilation; if the constructor we're looking at is from // another project with a different language. var constructorInCompilation = (IMethodSymbol?)SymbolKey.Create(constructor).Resolve(semanticModel.Compilation).Symbol; if (constructorInCompilation == null) { // If the constructor can't be mapped into our invocation project, we'll just bail. // Note the logic in this method doesn't handle a complicated case where: // // 1. Project A has some public type. // 2. Project B references A, and has one constructor that uses the public type from A. // 3. Project C, which references B but not A, has an invocation of B's constructor passing some // parameters. // // The algorithm of this class tries to map the constructor in B (that we might delegate to) into // C, but that constructor might not be mappable if the public type from A is not available. // However, theoretically the public type from A could have a user-defined conversion. // The alternative approach might be to map the type of the parameters back into B, and then // classify the conversions in Project B, but that'll run into other issues if the experssions // don't have a natural type (like default). We choose to ignore all complicated cases here. return false; } for (var i = 0; i < constructorInCompilation.Parameters.Length; i++) { var constructorParameter = constructorInCompilation.Parameters[i]; if (constructorParameter == null) return false; // In VB the argument may not have been specified at all if the parameter is optional if (expressions[i] is null && constructorParameter.IsOptional) continue; var conversion = semanticFacts.ClassifyConversion(semanticModel, expressions[i], constructorParameter.Type); if (!conversion.IsIdentity && !conversion.IsImplicit) return false; } return true; } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/EditorFeatures/VisualBasic/LineCommit/CommitFormatter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.CodeCleanup.Providers Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Indentation Imports Microsoft.CodeAnalysis.Internal.Log Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit <Export(GetType(ICommitFormatter))> Friend Class CommitFormatter Implements ICommitFormatter Private Shared ReadOnly s_codeCleanupPredicate As Func(Of ICodeCleanupProvider, Boolean) = Function(p) Return p.Name <> PredefinedCodeCleanupProviderNames.Simplification AndAlso p.Name <> PredefinedCodeCleanupProviderNames.Format End Function <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Sub CommitRegion(spanToFormat As SnapshotSpan, isExplicitFormat As Boolean, useSemantics As Boolean, dirtyRegion As SnapshotSpan, baseSnapshot As ITextSnapshot, baseTree As SyntaxTree, cancellationToken As CancellationToken) Implements ICommitFormatter.CommitRegion Using (Logger.LogBlock(FunctionId.LineCommit_CommitRegion, cancellationToken)) Dim buffer = spanToFormat.Snapshot.TextBuffer Dim currentSnapshot = buffer.CurrentSnapshot ' make sure things are current spanToFormat = spanToFormat.TranslateTo(currentSnapshot, SpanTrackingMode.EdgeInclusive) dirtyRegion = dirtyRegion.TranslateTo(currentSnapshot, SpanTrackingMode.EdgeInclusive) ' Use frozen partial semantics here. We're operating on the UI thread, and we don't want to block the ' user indefinitely while getting full semantics for this projects (which can require building all ' projects we depend on). Dim document = currentSnapshot.AsText().GetDocumentWithFrozenPartialSemantics(cancellationToken) If document Is Nothing Then Return End If Dim inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService(Of IInferredIndentationService)() Dim documentOptions = inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, isExplicitFormat, cancellationToken).WaitAndGetResult(cancellationToken) If Not (isExplicitFormat OrElse documentOptions.GetOption(FeatureOnOffOptions.PrettyListing)) Then Return End If Dim textSpanToFormat = spanToFormat.Span.ToTextSpan() If AbortForDiagnostics(document, cancellationToken) Then Return End If ' create commit formatting cleanup provider that has line commit specific behavior Dim commitFormattingCleanup = GetCommitFormattingCleanupProvider( document, documentOptions, spanToFormat, baseSnapshot, baseTree, dirtyRegion, document.GetSyntaxTreeSynchronously(cancellationToken), cancellationToken) Dim codeCleanups = CodeCleaner.GetDefaultProviders(document). WhereAsArray(s_codeCleanupPredicate). Concat(commitFormattingCleanup) Dim finalDocument As Document If useSemantics OrElse isExplicitFormat Then finalDocument = CodeCleaner.CleanupAsync(document, textSpanToFormat, codeCleanups, cancellationToken).WaitAndGetResult(cancellationToken) Else Dim root = document.GetSyntaxRootSynchronously(cancellationToken) Dim newRoot = CodeCleaner.CleanupAsync(root, textSpanToFormat, document.Project.Solution.Workspace, codeCleanups, cancellationToken).WaitAndGetResult(cancellationToken) If root Is newRoot Then finalDocument = document Else Dim text As SourceText = Nothing If newRoot.SyntaxTree IsNot Nothing AndAlso newRoot.SyntaxTree.TryGetText(text) Then finalDocument = document.WithText(text) Else finalDocument = document.WithSyntaxRoot(newRoot) End If End If End If finalDocument.Project.Solution.Workspace.ApplyDocumentChanges(finalDocument, cancellationToken) End Using End Sub Private Shared Function AbortForDiagnostics(document As Document, cancellationToken As CancellationToken) As Boolean Const UnterminatedStringId = "BC30648" Dim tree = document.GetSyntaxTreeSynchronously(cancellationToken) ' If we have any unterminated strings that overlap what we're trying to format, then ' bail out. It's quite likely the unterminated string will cause a bunch of code to ' swap between real code and string literals, and committing will just cause problems. Dim diagnostics = tree.GetDiagnostics(cancellationToken).Where( Function(d) d.Descriptor.Id = UnterminatedStringId) Return diagnostics.Any() End Function Private Shared Function GetCommitFormattingCleanupProvider( document As Document, documentOptions As DocumentOptionSet, spanToFormat As SnapshotSpan, oldSnapshot As ITextSnapshot, oldTree As SyntaxTree, newDirtySpan As SnapshotSpan, newTree As SyntaxTree, cancellationToken As CancellationToken) As ICodeCleanupProvider Dim oldDirtySpan = newDirtySpan.TranslateTo(oldSnapshot, SpanTrackingMode.EdgeInclusive) ' based on changes made to dirty spans, get right formatting rules to apply Dim rules = GetFormattingRules(document, documentOptions, spanToFormat, oldDirtySpan, oldTree, newDirtySpan, newTree, cancellationToken) Return New SimpleCodeCleanupProvider(PredefinedCodeCleanupProviderNames.Format, Function(doc, spans, c) FormatAsync(doc, spans, documentOptions, rules, c), Function(r, spans, w, c) Format(r, spans, w, documentOptions, rules, c)) End Function Private Shared Async Function FormatAsync(document As Document, spans As ImmutableArray(Of TextSpan), options As OptionSet, rules As IEnumerable(Of AbstractFormattingRule), cancellationToken As CancellationToken) As Task(Of Document) ' if old text already exist, use fast path for formatting Dim oldText As SourceText = Nothing If document.TryGetText(oldText) Then Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim newText = oldText.WithChanges(Formatter.GetFormattedTextChanges(root, spans, document.Project.Solution.Workspace, options, rules, cancellationToken)) Return document.WithText(newText) End If Return Await Formatter.FormatAsync(document, spans, options, rules, cancellationToken).ConfigureAwait(False) End Function Private Shared Function Format(root As SyntaxNode, spans As ImmutableArray(Of TextSpan), workspace As Workspace, options As OptionSet, rules As IEnumerable(Of AbstractFormattingRule), cancellationToken As CancellationToken) As SyntaxNode ' if old text already exist, use fast path for formatting Dim oldText As SourceText = Nothing If root.SyntaxTree IsNot Nothing AndAlso root.SyntaxTree.TryGetText(oldText) Then Dim changes = Formatter.GetFormattedTextChanges(root, spans, workspace, options, rules, cancellationToken) ' no change If changes.Count = 0 Then Return root End If Return root.SyntaxTree.WithChangedText(oldText.WithChanges(changes)).GetRoot(cancellationToken) End If Return Formatter.Format(root, spans, workspace, options, rules, cancellationToken) End Function Private Shared Function GetFormattingRules( document As Document, documentOptions As DocumentOptionSet, spanToFormat As SnapshotSpan, oldDirtySpan As SnapshotSpan, oldTree As SyntaxTree, newDirtySpan As SnapshotSpan, newTree As SyntaxTree, cancellationToken As CancellationToken) As IEnumerable(Of AbstractFormattingRule) ' if the span we are going to format is same as the span that got changed, don't bother to do anything special. ' just do full format of the span. If spanToFormat = newDirtySpan Then Return Formatter.GetDefaultFormattingRules(document) End If If oldTree Is Nothing OrElse newTree Is Nothing Then Return Formatter.GetDefaultFormattingRules(document) End If ' TODO: remove this in dev14 ' ' workaround for VB razor case. ' if we are under VB razor, we always use anchor operation otherwise, due to our double formatting, everything will just get messed. ' this is really a hacky workaround we should remove this in dev14 Dim formattingRuleService = document.Project.Solution.Workspace.Services.GetService(Of IHostDependentFormattingRuleFactoryService)() If formattingRuleService IsNot Nothing Then If formattingRuleService.ShouldUseBaseIndentation(document) Then Return Formatter.GetDefaultFormattingRules(document) End If End If ' when commit formatter formats given span, it formats the span with or without anchor operations. ' the way we determine which formatting rules are used for the span is based on whether the region user has changed would change indentation ' following the dirty (committed) region. if indentation has changed, we will format with anchor operations. if not, we will format without anchor operations. ' ' for example, for the code below '[ ]|If True And ' False Then| ' Dim a = 1 ' if the [] is changed, when line commit runs, it sees indentation right after the commit (|If .. Then|) is same, so formatter will run without anchor operations, ' meaning, "False Then" will stay as it is even if "If True And" is moved due to change in [] ' ' if the [] is changed to '[ If True Then ' ]|If True And ' False Then| ' Dim a = 1 ' when line commit runs, it sees that indentation after the commit is changed (due to inserted "If True Then"), so formatter runs with anchor operations, ' meaning, "False Then" will move along with "If True And" ' ' for now, do very simple checking. basically, we see whether we get same number of indent operation for the give span. alternative, but little bit ' more expensive and complex, we can actually calculate indentation right after the span, and see whether that is changed. not sure whether that much granularity ' is needed. If GetNumberOfIndentOperations(document, documentOptions, oldTree, oldDirtySpan, cancellationToken) = GetNumberOfIndentOperations(document, documentOptions, newTree, newDirtySpan, cancellationToken) Then Return (New NoAnchorFormatterRule()).Concat(Formatter.GetDefaultFormattingRules(document)) End If Return Formatter.GetDefaultFormattingRules(document) End Function Private Shared Function GetNumberOfIndentOperations(document As Document, documentOptions As DocumentOptionSet, SyntaxTree As SyntaxTree, Span As SnapshotSpan, CancellationToken As CancellationToken) As Integer ' find containing statement of the end point, and use its end point as position to get indent operation Dim containingStatement = ContainingStatementInfo.GetInfo(Span.End, SyntaxTree, CancellationToken) Dim endPosition = If(containingStatement Is Nothing, Span.End.Position + 1, containingStatement.TextSpan.End + 1) ' get token right after given span Dim token = SyntaxTree.GetRoot(CancellationToken).FindToken(Math.Min(endPosition, SyntaxTree.GetRoot(CancellationToken).FullSpan.End)) Dim node = token.Parent Dim optionService = document.Project.Solution.Workspace.Services.GetRequiredService(Of IOptionService)() Dim options = documentOptions.AsAnalyzerConfigOptions(optionService, node?.Language) ' collect all indent operation Dim operations = New List(Of IndentBlockOperation)() While node IsNot Nothing operations.AddRange(FormattingOperations.GetIndentBlockOperations( Formatter.GetDefaultFormattingRules(document), node, options)) node = node.Parent End While ' get number of indent operation that affects the token. Return operations.Where(Function(o) o.TextSpan.Contains(token.SpanStart)).Count() End Function Private Class NoAnchorFormatterRule Inherits CompatAbstractFormattingRule Public Overrides Sub AddAnchorIndentationOperationsSlow(list As List(Of AnchorIndentationOperation), node As SyntaxNode, ByRef nextOperation As NextAnchorIndentationOperationAction) ' no anchor/relative formatting Return End Sub End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.ComponentModel.Composition Imports System.Threading Imports Microsoft.CodeAnalysis.CodeCleanup Imports Microsoft.CodeAnalysis.CodeCleanup.Providers Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.Formatting.Rules Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.Indentation Imports Microsoft.CodeAnalysis.Internal.Log Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Text Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit <Export(GetType(ICommitFormatter))> Friend Class CommitFormatter Implements ICommitFormatter Private Shared ReadOnly s_codeCleanupPredicate As Func(Of ICodeCleanupProvider, Boolean) = Function(p) Return p.Name <> PredefinedCodeCleanupProviderNames.Simplification AndAlso p.Name <> PredefinedCodeCleanupProviderNames.Format End Function <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Sub CommitRegion(spanToFormat As SnapshotSpan, isExplicitFormat As Boolean, useSemantics As Boolean, dirtyRegion As SnapshotSpan, baseSnapshot As ITextSnapshot, baseTree As SyntaxTree, cancellationToken As CancellationToken) Implements ICommitFormatter.CommitRegion Using (Logger.LogBlock(FunctionId.LineCommit_CommitRegion, cancellationToken)) Dim buffer = spanToFormat.Snapshot.TextBuffer Dim currentSnapshot = buffer.CurrentSnapshot ' make sure things are current spanToFormat = spanToFormat.TranslateTo(currentSnapshot, SpanTrackingMode.EdgeInclusive) dirtyRegion = dirtyRegion.TranslateTo(currentSnapshot, SpanTrackingMode.EdgeInclusive) ' Use frozen partial semantics here. We're operating on the UI thread, and we don't want to block the ' user indefinitely while getting full semantics for this projects (which can require building all ' projects we depend on). Dim document = currentSnapshot.AsText().GetDocumentWithFrozenPartialSemantics(cancellationToken) If document Is Nothing Then Return End If Dim inferredIndentationService = document.Project.Solution.Workspace.Services.GetRequiredService(Of IInferredIndentationService)() Dim documentOptions = inferredIndentationService.GetDocumentOptionsWithInferredIndentationAsync(document, isExplicitFormat, cancellationToken).WaitAndGetResult(cancellationToken) If Not (isExplicitFormat OrElse documentOptions.GetOption(FeatureOnOffOptions.PrettyListing)) Then Return End If Dim textSpanToFormat = spanToFormat.Span.ToTextSpan() If AbortForDiagnostics(document, cancellationToken) Then Return End If ' create commit formatting cleanup provider that has line commit specific behavior Dim commitFormattingCleanup = GetCommitFormattingCleanupProvider( document, documentOptions, spanToFormat, baseSnapshot, baseTree, dirtyRegion, document.GetSyntaxTreeSynchronously(cancellationToken), cancellationToken) Dim codeCleanups = CodeCleaner.GetDefaultProviders(document). WhereAsArray(s_codeCleanupPredicate). Concat(commitFormattingCleanup) Dim finalDocument As Document If useSemantics OrElse isExplicitFormat Then finalDocument = CodeCleaner.CleanupAsync(document, textSpanToFormat, codeCleanups, cancellationToken).WaitAndGetResult(cancellationToken) Else Dim root = document.GetSyntaxRootSynchronously(cancellationToken) Dim newRoot = CodeCleaner.CleanupAsync(root, textSpanToFormat, document.Project.Solution.Workspace, codeCleanups, cancellationToken).WaitAndGetResult(cancellationToken) If root Is newRoot Then finalDocument = document Else Dim text As SourceText = Nothing If newRoot.SyntaxTree IsNot Nothing AndAlso newRoot.SyntaxTree.TryGetText(text) Then finalDocument = document.WithText(text) Else finalDocument = document.WithSyntaxRoot(newRoot) End If End If End If finalDocument.Project.Solution.Workspace.ApplyDocumentChanges(finalDocument, cancellationToken) End Using End Sub Private Shared Function AbortForDiagnostics(document As Document, cancellationToken As CancellationToken) As Boolean Const UnterminatedStringId = "BC30648" Dim tree = document.GetSyntaxTreeSynchronously(cancellationToken) ' If we have any unterminated strings that overlap what we're trying to format, then ' bail out. It's quite likely the unterminated string will cause a bunch of code to ' swap between real code and string literals, and committing will just cause problems. Dim diagnostics = tree.GetDiagnostics(cancellationToken).Where( Function(d) d.Descriptor.Id = UnterminatedStringId) Return diagnostics.Any() End Function Private Shared Function GetCommitFormattingCleanupProvider( document As Document, documentOptions As DocumentOptionSet, spanToFormat As SnapshotSpan, oldSnapshot As ITextSnapshot, oldTree As SyntaxTree, newDirtySpan As SnapshotSpan, newTree As SyntaxTree, cancellationToken As CancellationToken) As ICodeCleanupProvider Dim oldDirtySpan = newDirtySpan.TranslateTo(oldSnapshot, SpanTrackingMode.EdgeInclusive) ' based on changes made to dirty spans, get right formatting rules to apply Dim rules = GetFormattingRules(document, documentOptions, spanToFormat, oldDirtySpan, oldTree, newDirtySpan, newTree, cancellationToken) Return New SimpleCodeCleanupProvider(PredefinedCodeCleanupProviderNames.Format, Function(doc, spans, c) FormatAsync(doc, spans, documentOptions, rules, c), Function(r, spans, w, c) Format(r, spans, w, documentOptions, rules, c)) End Function Private Shared Async Function FormatAsync(document As Document, spans As ImmutableArray(Of TextSpan), options As OptionSet, rules As IEnumerable(Of AbstractFormattingRule), cancellationToken As CancellationToken) As Task(Of Document) ' if old text already exist, use fast path for formatting Dim oldText As SourceText = Nothing If document.TryGetText(oldText) Then Dim root = Await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(False) Dim newText = oldText.WithChanges(Formatter.GetFormattedTextChanges(root, spans, document.Project.Solution.Workspace, options, rules, cancellationToken)) Return document.WithText(newText) End If Return Await Formatter.FormatAsync(document, spans, options, rules, cancellationToken).ConfigureAwait(False) End Function Private Shared Function Format(root As SyntaxNode, spans As ImmutableArray(Of TextSpan), workspace As Workspace, options As OptionSet, rules As IEnumerable(Of AbstractFormattingRule), cancellationToken As CancellationToken) As SyntaxNode ' if old text already exist, use fast path for formatting Dim oldText As SourceText = Nothing If root.SyntaxTree IsNot Nothing AndAlso root.SyntaxTree.TryGetText(oldText) Then Dim changes = Formatter.GetFormattedTextChanges(root, spans, workspace, options, rules, cancellationToken) ' no change If changes.Count = 0 Then Return root End If Return root.SyntaxTree.WithChangedText(oldText.WithChanges(changes)).GetRoot(cancellationToken) End If Return Formatter.Format(root, spans, workspace, options, rules, cancellationToken) End Function Private Shared Function GetFormattingRules( document As Document, documentOptions As DocumentOptionSet, spanToFormat As SnapshotSpan, oldDirtySpan As SnapshotSpan, oldTree As SyntaxTree, newDirtySpan As SnapshotSpan, newTree As SyntaxTree, cancellationToken As CancellationToken) As IEnumerable(Of AbstractFormattingRule) ' if the span we are going to format is same as the span that got changed, don't bother to do anything special. ' just do full format of the span. If spanToFormat = newDirtySpan Then Return Formatter.GetDefaultFormattingRules(document) End If If oldTree Is Nothing OrElse newTree Is Nothing Then Return Formatter.GetDefaultFormattingRules(document) End If ' TODO: remove this in dev14 ' ' workaround for VB razor case. ' if we are under VB razor, we always use anchor operation otherwise, due to our double formatting, everything will just get messed. ' this is really a hacky workaround we should remove this in dev14 Dim formattingRuleService = document.Project.Solution.Workspace.Services.GetService(Of IHostDependentFormattingRuleFactoryService)() If formattingRuleService IsNot Nothing Then If formattingRuleService.ShouldUseBaseIndentation(document) Then Return Formatter.GetDefaultFormattingRules(document) End If End If ' when commit formatter formats given span, it formats the span with or without anchor operations. ' the way we determine which formatting rules are used for the span is based on whether the region user has changed would change indentation ' following the dirty (committed) region. if indentation has changed, we will format with anchor operations. if not, we will format without anchor operations. ' ' for example, for the code below '[ ]|If True And ' False Then| ' Dim a = 1 ' if the [] is changed, when line commit runs, it sees indentation right after the commit (|If .. Then|) is same, so formatter will run without anchor operations, ' meaning, "False Then" will stay as it is even if "If True And" is moved due to change in [] ' ' if the [] is changed to '[ If True Then ' ]|If True And ' False Then| ' Dim a = 1 ' when line commit runs, it sees that indentation after the commit is changed (due to inserted "If True Then"), so formatter runs with anchor operations, ' meaning, "False Then" will move along with "If True And" ' ' for now, do very simple checking. basically, we see whether we get same number of indent operation for the give span. alternative, but little bit ' more expensive and complex, we can actually calculate indentation right after the span, and see whether that is changed. not sure whether that much granularity ' is needed. If GetNumberOfIndentOperations(document, documentOptions, oldTree, oldDirtySpan, cancellationToken) = GetNumberOfIndentOperations(document, documentOptions, newTree, newDirtySpan, cancellationToken) Then Return (New NoAnchorFormatterRule()).Concat(Formatter.GetDefaultFormattingRules(document)) End If Return Formatter.GetDefaultFormattingRules(document) End Function Private Shared Function GetNumberOfIndentOperations(document As Document, documentOptions As DocumentOptionSet, SyntaxTree As SyntaxTree, Span As SnapshotSpan, CancellationToken As CancellationToken) As Integer ' find containing statement of the end point, and use its end point as position to get indent operation Dim containingStatement = ContainingStatementInfo.GetInfo(Span.End, SyntaxTree, CancellationToken) Dim endPosition = If(containingStatement Is Nothing, Span.End.Position + 1, containingStatement.TextSpan.End + 1) ' get token right after given span Dim token = SyntaxTree.GetRoot(CancellationToken).FindToken(Math.Min(endPosition, SyntaxTree.GetRoot(CancellationToken).FullSpan.End)) Dim node = token.Parent Dim optionService = document.Project.Solution.Workspace.Services.GetRequiredService(Of IOptionService)() Dim options = documentOptions.AsAnalyzerConfigOptions(optionService, node?.Language) ' collect all indent operation Dim operations = New List(Of IndentBlockOperation)() While node IsNot Nothing operations.AddRange(FormattingOperations.GetIndentBlockOperations( Formatter.GetDefaultFormattingRules(document), node, options)) node = node.Parent End While ' get number of indent operation that affects the token. Return operations.Where(Function(o) o.TextSpan.Contains(token.SpanStart)).Count() End Function Private Class NoAnchorFormatterRule Inherits CompatAbstractFormattingRule Public Overrides Sub AddAnchorIndentationOperationsSlow(list As List(Of AnchorIndentationOperation), node As SyntaxNode, ByRef nextOperation As NextAnchorIndentationOperationAction) ' no anchor/relative formatting Return End Sub End Class End Class End Namespace
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Workspaces/VisualBasic/Portable/Simplification/Reducers/VisualBasicCastReducer.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicCastReducer Inherits AbstractVisualBasicReducer Private Shared ReadOnly s_pool As ObjectPool(Of IReductionRewriter) = New ObjectPool(Of IReductionRewriter)(Function() New Rewriter(s_pool)) Public Sub New() MyBase.New(s_pool) End Sub Private Shared ReadOnly s_simplifyCast As Func(Of CastExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode) = AddressOf SimplifyCast Private Overloads Shared Function SimplifyCast( node As CastExpressionSyntax, semanticModel As SemanticModel, optionSet As OptionSet, cancellationToken As CancellationToken ) As ExpressionSyntax If Not node.IsUnnecessaryCast(semanticModel, cancellationToken) Then Return node End If Return node.Uncast() End Function Private Shared ReadOnly s_simplifyPredefinedCast As Func(Of PredefinedCastExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode) = AddressOf SimplifyPredefinedCast Private Overloads Shared Function SimplifyPredefinedCast( node As PredefinedCastExpressionSyntax, semanticModel As SemanticModel, optionSet As OptionSet, cancellationToken As CancellationToken ) As ExpressionSyntax If Not node.IsUnnecessaryCast(semanticModel, cancellationToken) Then Return node End If Return node.Uncast() End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Simplification Partial Friend Class VisualBasicCastReducer Inherits AbstractVisualBasicReducer Private Shared ReadOnly s_pool As ObjectPool(Of IReductionRewriter) = New ObjectPool(Of IReductionRewriter)(Function() New Rewriter(s_pool)) Public Sub New() MyBase.New(s_pool) End Sub Private Shared ReadOnly s_simplifyCast As Func(Of CastExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode) = AddressOf SimplifyCast Private Overloads Shared Function SimplifyCast( node As CastExpressionSyntax, semanticModel As SemanticModel, optionSet As OptionSet, cancellationToken As CancellationToken ) As ExpressionSyntax If Not node.IsUnnecessaryCast(semanticModel, cancellationToken) Then Return node End If Return node.Uncast() End Function Private Shared ReadOnly s_simplifyPredefinedCast As Func(Of PredefinedCastExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode) = AddressOf SimplifyPredefinedCast Private Overloads Shared Function SimplifyPredefinedCast( node As PredefinedCastExpressionSyntax, semanticModel As SemanticModel, optionSet As OptionSet, cancellationToken As CancellationToken ) As ExpressionSyntax If Not node.IsUnnecessaryCast(semanticModel, cancellationToken) Then Return node End If Return node.Uncast() End Function End Class End Namespace
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/Core/CodeAnalysisTest/Collections/TestExtensionsMethods.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections.Immutable/tests/TestExtensionsMethods.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { internal static partial class TestExtensionsMethods { internal static void ValidateDefaultThisBehavior(Action a) { Assert.Throws<NullReferenceException>(a); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections.Immutable/tests/TestExtensionsMethods.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { internal static partial class TestExtensionsMethods { internal static void ValidateDefaultThisBehavior(Action a) { Assert.Throws<NullReferenceException>(a); } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/VisualStudio/Core/Def/Implementation/FindReferences/Entries/DocumentSpanEntry.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Media; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.Editor.QuickInfo; using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.FindUsages { internal partial class StreamingFindUsagesPresenter { /// <summary> /// Entry to show for a particular source location. The row will show the classified /// contents of that line, and hovering will reveal a tooltip showing that line along /// with a few lines above/below it. /// </summary> private sealed class DocumentSpanEntry : AbstractDocumentSpanEntry, ISupportsNavigation { private readonly HighlightSpanKind _spanKind; private readonly ExcerptResult _excerptResult; private readonly SymbolReferenceKinds _symbolReferenceKinds; private readonly ImmutableDictionary<string, string> _customColumnsData; private readonly string _rawProjectName; private readonly List<string> _projectFlavors = new(); private string? _cachedProjectName; private DocumentSpanEntry( AbstractTableDataSourceFindUsagesContext context, RoslynDefinitionBucket definitionBucket, string rawProjectName, string? projectFlavor, Guid projectGuid, HighlightSpanKind spanKind, MappedSpanResult mappedSpanResult, ExcerptResult excerptResult, SourceText lineText, SymbolUsageInfo symbolUsageInfo, ImmutableDictionary<string, string> customColumnsData) : base(context, definitionBucket, projectGuid, lineText, mappedSpanResult) { _spanKind = spanKind; _excerptResult = excerptResult; _symbolReferenceKinds = symbolUsageInfo.ToSymbolReferenceKinds(); _customColumnsData = customColumnsData; _rawProjectName = rawProjectName; this.AddFlavor(projectFlavor); } protected override string GetProjectName() { // Check if we have any flavors. If we have at least 2, combine with the project name // so the user can know htat in the UI. lock (_projectFlavors) { if (_cachedProjectName == null) { _cachedProjectName = _projectFlavors.Count < 2 ? _rawProjectName : $"{_rawProjectName} ({string.Join(", ", _projectFlavors)})"; } return _cachedProjectName; } } private void AddFlavor(string? projectFlavor) { if (projectFlavor == null) return; lock (_projectFlavors) { if (_projectFlavors.Contains(projectFlavor)) return; _projectFlavors.Add(projectFlavor); _projectFlavors.Sort(); _cachedProjectName = null; } } public static DocumentSpanEntry? TryCreate( AbstractTableDataSourceFindUsagesContext context, RoslynDefinitionBucket definitionBucket, Guid guid, string projectName, string? projectFlavor, string? filePath, TextSpan sourceSpan, HighlightSpanKind spanKind, MappedSpanResult mappedSpanResult, ExcerptResult excerptResult, SourceText lineText, SymbolUsageInfo symbolUsageInfo, ImmutableDictionary<string, string> customColumnsData) { var entry = new DocumentSpanEntry( context, definitionBucket, projectName, projectFlavor, guid, spanKind, mappedSpanResult, excerptResult, lineText, symbolUsageInfo, customColumnsData); // Because of things like linked files, we may have a reference up in multiple // different locations that are effectively at the exact same navigation location // for the user. i.e. they're the same file/span. Showing multiple entries for these // is just noisy and gets worse and worse with shared projects and whatnot. So, we // collapse things down to only show a single entry for each unique file/span pair. var winningEntry = definitionBucket.GetOrAddEntry(filePath, sourceSpan, entry); // If we were the one that successfully added this entry to the bucket, then pass us // back out to be put in the ui. if (winningEntry == entry) return entry; // We were not the winner. Add our flavor to the entry that already exists, but throw // away the item we created as we do not want to add it to the ui. winningEntry.AddFlavor(projectFlavor); return null; } protected override IList<System.Windows.Documents.Inline> CreateLineTextInlines() { var propertyId = _spanKind == HighlightSpanKind.Definition ? DefinitionHighlightTag.TagId : _spanKind == HighlightSpanKind.WrittenReference ? WrittenReferenceHighlightTag.TagId : ReferenceHighlightTag.TagId; var properties = Presenter.FormatMapService .GetEditorFormatMap("text") .GetProperties(propertyId); // Remove additive classified spans before creating classified text. // Otherwise the text will be repeated since there are two classifications // for the same span. Additive classifications should not change the foreground // color, so the resulting classified text will retain the proper look. var classifiedSpans = _excerptResult.ClassifiedSpans.WhereAsArray( cs => !ClassificationTypeNames.AdditiveTypeNames.Contains(cs.ClassificationType)); var classifiedTexts = classifiedSpans.SelectAsArray( cs => new ClassifiedText(cs.ClassificationType, _excerptResult.Content.ToString(cs.TextSpan))); var inlines = classifiedTexts.ToInlines( Presenter.ClassificationFormatMap, Presenter.TypeMap, runCallback: (run, classifiedText, position) => { if (properties["Background"] is Brush highlightBrush) { if (position == _excerptResult.MappedSpan.Start) { run.SetValue( System.Windows.Documents.TextElement.BackgroundProperty, highlightBrush); } } }); return inlines; } public override bool TryCreateColumnContent(string columnName, [NotNullWhen(true)] out FrameworkElement? content) { if (base.TryCreateColumnContent(columnName, out content)) { // this lazy tooltip causes whole solution to be kept in memory until find all reference result gets cleared. // solution is never supposed to be kept alive for long time, meaning there is bunch of conditional weaktable or weak reference // keyed by solution/project/document or corresponding states. this will cause all those to be kept alive in memory as well. // probably we need to dig in to see how expensvie it is to support this var controlService = _excerptResult.Document.Project.Solution.Workspace.Services.GetRequiredService<IContentControlService>(); controlService.AttachToolTipToControl(content, () => CreateDisposableToolTip(_excerptResult.Document, _excerptResult.Span)); return true; } return false; } protected override object? GetValueWorker(string keyName) { if (keyName == StandardTableKeyNames2.SymbolKind) { return _symbolReferenceKinds; } if (_customColumnsData.TryGetValue(keyName, out var value)) { return value; } return base.GetValueWorker(keyName); } private DisposableToolTip CreateDisposableToolTip(Document document, TextSpan sourceSpan) { Presenter.AssertIsForeground(); var controlService = document.Project.Solution.Workspace.Services.GetRequiredService<IContentControlService>(); var sourceText = document.GetTextSynchronously(CancellationToken.None); var excerptService = document.Services.GetService<IDocumentExcerptService>(); if (excerptService != null) { var excerpt = Presenter.ThreadingContext.JoinableTaskFactory.Run(() => excerptService.TryExcerptAsync(document, sourceSpan, ExcerptMode.Tooltip, CancellationToken.None)); if (excerpt != null) { // get tooltip from excerpt service var clonedBuffer = excerpt.Value.Content.CreateTextBufferWithRoslynContentType(document.Project.Solution.Workspace); SetHighlightSpan(_spanKind, clonedBuffer, excerpt.Value.MappedSpan); SetStaticClassifications(clonedBuffer, excerpt.Value.ClassifiedSpans); return controlService.CreateDisposableToolTip(clonedBuffer, EnvironmentColors.ToolWindowBackgroundBrushKey); } } // get default behavior var textBuffer = document.CloneTextBuffer(sourceText); SetHighlightSpan(_spanKind, textBuffer, sourceSpan); var contentSpan = GetRegionSpanForReference(sourceText, sourceSpan); return controlService.CreateDisposableToolTip(document, textBuffer, contentSpan, EnvironmentColors.ToolWindowBackgroundBrushKey); } private void SetStaticClassifications(ITextBuffer textBuffer, ImmutableArray<ClassifiedSpan> classifiedSpans) { var key = PredefinedPreviewTaggerKeys.StaticClassificationSpansKey; textBuffer.Properties.RemoveProperty(key); textBuffer.Properties.AddProperty(key, classifiedSpans); } private static void SetHighlightSpan(HighlightSpanKind spanKind, ITextBuffer textBuffer, TextSpan span) { // Create an appropriate highlight span on that buffer for the reference. var key = spanKind == HighlightSpanKind.Definition ? PredefinedPreviewTaggerKeys.DefinitionHighlightingSpansKey : spanKind == HighlightSpanKind.WrittenReference ? PredefinedPreviewTaggerKeys.WrittenReferenceHighlightingSpansKey : PredefinedPreviewTaggerKeys.ReferenceHighlightingSpansKey; textBuffer.Properties.RemoveProperty(key); textBuffer.Properties.AddProperty(key, new NormalizedSnapshotSpanCollection(span.ToSnapshotSpan(textBuffer.CurrentSnapshot))); } private static Span GetRegionSpanForReference(SourceText sourceText, TextSpan sourceSpan) { const int AdditionalLineCountPerSide = 3; var referenceSpan = sourceSpan; var lineNumber = sourceText.Lines.GetLineFromPosition(referenceSpan.Start).LineNumber; var firstLineNumber = Math.Max(0, lineNumber - AdditionalLineCountPerSide); var lastLineNumber = Math.Min(sourceText.Lines.Count - 1, lineNumber + AdditionalLineCountPerSide); return Span.FromBounds( sourceText.Lines[firstLineNumber].Start, sourceText.Lines[lastLineNumber].End); } public bool CanNavigateTo() { if (_excerptResult.Document is SourceGeneratedDocument) { var workspace = _excerptResult.Document.Project.Solution.Workspace; var documentNavigationService = workspace.Services.GetService<IDocumentNavigationService>(); return documentNavigationService != null; } return false; } public Task NavigateToAsync(bool isPreview, CancellationToken cancellationToken) { Contract.ThrowIfFalse(CanNavigateTo()); // If the document is a source generated document, we need to do the navigation ourselves; // this is because the file path given to the table control isn't a real file path to a file // on disk. var solution = _excerptResult.Document.Project.Solution; var workspace = solution.Workspace; var documentNavigationService = workspace.Services.GetRequiredService<IDocumentNavigationService>(); return documentNavigationService.TryNavigateToSpanAsync( workspace, _excerptResult.Document.Id, _excerptResult.Span, solution.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, isPreview), cancellationToken); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Media; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.Editor.QuickInfo; using Microsoft.CodeAnalysis.Editor.ReferenceHighlighting; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.PlatformUI; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.FindUsages { internal partial class StreamingFindUsagesPresenter { /// <summary> /// Entry to show for a particular source location. The row will show the classified /// contents of that line, and hovering will reveal a tooltip showing that line along /// with a few lines above/below it. /// </summary> private sealed class DocumentSpanEntry : AbstractDocumentSpanEntry, ISupportsNavigation { private readonly HighlightSpanKind _spanKind; private readonly ExcerptResult _excerptResult; private readonly SymbolReferenceKinds _symbolReferenceKinds; private readonly ImmutableDictionary<string, string> _customColumnsData; private readonly string _rawProjectName; private readonly List<string> _projectFlavors = new(); private string? _cachedProjectName; private DocumentSpanEntry( AbstractTableDataSourceFindUsagesContext context, RoslynDefinitionBucket definitionBucket, string rawProjectName, string? projectFlavor, Guid projectGuid, HighlightSpanKind spanKind, MappedSpanResult mappedSpanResult, ExcerptResult excerptResult, SourceText lineText, SymbolUsageInfo symbolUsageInfo, ImmutableDictionary<string, string> customColumnsData) : base(context, definitionBucket, projectGuid, lineText, mappedSpanResult) { _spanKind = spanKind; _excerptResult = excerptResult; _symbolReferenceKinds = symbolUsageInfo.ToSymbolReferenceKinds(); _customColumnsData = customColumnsData; _rawProjectName = rawProjectName; this.AddFlavor(projectFlavor); } protected override string GetProjectName() { // Check if we have any flavors. If we have at least 2, combine with the project name // so the user can know htat in the UI. lock (_projectFlavors) { if (_cachedProjectName == null) { _cachedProjectName = _projectFlavors.Count < 2 ? _rawProjectName : $"{_rawProjectName} ({string.Join(", ", _projectFlavors)})"; } return _cachedProjectName; } } private void AddFlavor(string? projectFlavor) { if (projectFlavor == null) return; lock (_projectFlavors) { if (_projectFlavors.Contains(projectFlavor)) return; _projectFlavors.Add(projectFlavor); _projectFlavors.Sort(); _cachedProjectName = null; } } public static DocumentSpanEntry? TryCreate( AbstractTableDataSourceFindUsagesContext context, RoslynDefinitionBucket definitionBucket, Guid guid, string projectName, string? projectFlavor, string? filePath, TextSpan sourceSpan, HighlightSpanKind spanKind, MappedSpanResult mappedSpanResult, ExcerptResult excerptResult, SourceText lineText, SymbolUsageInfo symbolUsageInfo, ImmutableDictionary<string, string> customColumnsData) { var entry = new DocumentSpanEntry( context, definitionBucket, projectName, projectFlavor, guid, spanKind, mappedSpanResult, excerptResult, lineText, symbolUsageInfo, customColumnsData); // Because of things like linked files, we may have a reference up in multiple // different locations that are effectively at the exact same navigation location // for the user. i.e. they're the same file/span. Showing multiple entries for these // is just noisy and gets worse and worse with shared projects and whatnot. So, we // collapse things down to only show a single entry for each unique file/span pair. var winningEntry = definitionBucket.GetOrAddEntry(filePath, sourceSpan, entry); // If we were the one that successfully added this entry to the bucket, then pass us // back out to be put in the ui. if (winningEntry == entry) return entry; // We were not the winner. Add our flavor to the entry that already exists, but throw // away the item we created as we do not want to add it to the ui. winningEntry.AddFlavor(projectFlavor); return null; } protected override IList<System.Windows.Documents.Inline> CreateLineTextInlines() { var propertyId = _spanKind == HighlightSpanKind.Definition ? DefinitionHighlightTag.TagId : _spanKind == HighlightSpanKind.WrittenReference ? WrittenReferenceHighlightTag.TagId : ReferenceHighlightTag.TagId; var properties = Presenter.FormatMapService .GetEditorFormatMap("text") .GetProperties(propertyId); // Remove additive classified spans before creating classified text. // Otherwise the text will be repeated since there are two classifications // for the same span. Additive classifications should not change the foreground // color, so the resulting classified text will retain the proper look. var classifiedSpans = _excerptResult.ClassifiedSpans.WhereAsArray( cs => !ClassificationTypeNames.AdditiveTypeNames.Contains(cs.ClassificationType)); var classifiedTexts = classifiedSpans.SelectAsArray( cs => new ClassifiedText(cs.ClassificationType, _excerptResult.Content.ToString(cs.TextSpan))); var inlines = classifiedTexts.ToInlines( Presenter.ClassificationFormatMap, Presenter.TypeMap, runCallback: (run, classifiedText, position) => { if (properties["Background"] is Brush highlightBrush) { if (position == _excerptResult.MappedSpan.Start) { run.SetValue( System.Windows.Documents.TextElement.BackgroundProperty, highlightBrush); } } }); return inlines; } public override bool TryCreateColumnContent(string columnName, [NotNullWhen(true)] out FrameworkElement? content) { if (base.TryCreateColumnContent(columnName, out content)) { // this lazy tooltip causes whole solution to be kept in memory until find all reference result gets cleared. // solution is never supposed to be kept alive for long time, meaning there is bunch of conditional weaktable or weak reference // keyed by solution/project/document or corresponding states. this will cause all those to be kept alive in memory as well. // probably we need to dig in to see how expensvie it is to support this var controlService = _excerptResult.Document.Project.Solution.Workspace.Services.GetRequiredService<IContentControlService>(); controlService.AttachToolTipToControl(content, () => CreateDisposableToolTip(_excerptResult.Document, _excerptResult.Span)); return true; } return false; } protected override object? GetValueWorker(string keyName) { if (keyName == StandardTableKeyNames2.SymbolKind) { return _symbolReferenceKinds; } if (_customColumnsData.TryGetValue(keyName, out var value)) { return value; } return base.GetValueWorker(keyName); } private DisposableToolTip CreateDisposableToolTip(Document document, TextSpan sourceSpan) { Presenter.AssertIsForeground(); var controlService = document.Project.Solution.Workspace.Services.GetRequiredService<IContentControlService>(); var sourceText = document.GetTextSynchronously(CancellationToken.None); var excerptService = document.Services.GetService<IDocumentExcerptService>(); if (excerptService != null) { var excerpt = Presenter.ThreadingContext.JoinableTaskFactory.Run(() => excerptService.TryExcerptAsync(document, sourceSpan, ExcerptMode.Tooltip, CancellationToken.None)); if (excerpt != null) { // get tooltip from excerpt service var clonedBuffer = excerpt.Value.Content.CreateTextBufferWithRoslynContentType(document.Project.Solution.Workspace); SetHighlightSpan(_spanKind, clonedBuffer, excerpt.Value.MappedSpan); SetStaticClassifications(clonedBuffer, excerpt.Value.ClassifiedSpans); return controlService.CreateDisposableToolTip(clonedBuffer, EnvironmentColors.ToolWindowBackgroundBrushKey); } } // get default behavior var textBuffer = document.CloneTextBuffer(sourceText); SetHighlightSpan(_spanKind, textBuffer, sourceSpan); var contentSpan = GetRegionSpanForReference(sourceText, sourceSpan); return controlService.CreateDisposableToolTip(document, textBuffer, contentSpan, EnvironmentColors.ToolWindowBackgroundBrushKey); } private void SetStaticClassifications(ITextBuffer textBuffer, ImmutableArray<ClassifiedSpan> classifiedSpans) { var key = PredefinedPreviewTaggerKeys.StaticClassificationSpansKey; textBuffer.Properties.RemoveProperty(key); textBuffer.Properties.AddProperty(key, classifiedSpans); } private static void SetHighlightSpan(HighlightSpanKind spanKind, ITextBuffer textBuffer, TextSpan span) { // Create an appropriate highlight span on that buffer for the reference. var key = spanKind == HighlightSpanKind.Definition ? PredefinedPreviewTaggerKeys.DefinitionHighlightingSpansKey : spanKind == HighlightSpanKind.WrittenReference ? PredefinedPreviewTaggerKeys.WrittenReferenceHighlightingSpansKey : PredefinedPreviewTaggerKeys.ReferenceHighlightingSpansKey; textBuffer.Properties.RemoveProperty(key); textBuffer.Properties.AddProperty(key, new NormalizedSnapshotSpanCollection(span.ToSnapshotSpan(textBuffer.CurrentSnapshot))); } private static Span GetRegionSpanForReference(SourceText sourceText, TextSpan sourceSpan) { const int AdditionalLineCountPerSide = 3; var referenceSpan = sourceSpan; var lineNumber = sourceText.Lines.GetLineFromPosition(referenceSpan.Start).LineNumber; var firstLineNumber = Math.Max(0, lineNumber - AdditionalLineCountPerSide); var lastLineNumber = Math.Min(sourceText.Lines.Count - 1, lineNumber + AdditionalLineCountPerSide); return Span.FromBounds( sourceText.Lines[firstLineNumber].Start, sourceText.Lines[lastLineNumber].End); } public bool CanNavigateTo() { if (_excerptResult.Document is SourceGeneratedDocument) { var workspace = _excerptResult.Document.Project.Solution.Workspace; var documentNavigationService = workspace.Services.GetService<IDocumentNavigationService>(); return documentNavigationService != null; } return false; } public Task NavigateToAsync(bool isPreview, CancellationToken cancellationToken) { Contract.ThrowIfFalse(CanNavigateTo()); // If the document is a source generated document, we need to do the navigation ourselves; // this is because the file path given to the table control isn't a real file path to a file // on disk. var solution = _excerptResult.Document.Project.Solution; var workspace = solution.Workspace; var documentNavigationService = workspace.Services.GetRequiredService<IDocumentNavigationService>(); return documentNavigationService.TryNavigateToSpanAsync( workspace, _excerptResult.Document.Id, _excerptResult.Span, solution.Options.WithChangedOption(NavigationOptions.PreferProvisionalTab, isPreview), cancellationToken); } } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/VisualBasic/Test/Emit/Microsoft.CodeAnalysis.VisualBasic.Emit.UnitTests.vbproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <TargetFrameworks>net5.0;net472</TargetFrameworks> <RootNamespace></RootNamespace> <!-- Disabling on assumption --> <SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests> <EmbeddedResourceUseDependentUponConvention>false</EmbeddedResourceUseDependentUponConvention> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> <ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" /> <ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.DiaSymReader" Version="$(MicrosoftDiaSymReaderVersion)" /> <PackageReference Include="Microsoft.VisualBasic" Version="$(MicrosoftVisualBasicVersion)" Condition="'$(TargetFramework)' == 'net472'" /> </ItemGroup> <ItemGroup> <Content Include="CodeGen\ConversionsILGenTestBaseline.txt" /> <Content Include="CodeGen\ConversionsILGenTestBaseline1.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndOrXor.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedIsIsNot.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedIsIsNotNothing.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedIsTrueIsFalse.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedNarrowingUDC.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedNothingConversions.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedTypeParameters.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedUdoUnaryPlusMinusNot.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedUserTypeConversions.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedWideningUDC.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedWithDate.txt" /> <Content Include="ExpressionTrees\Results\CheckedArithmeticBinaryOperators.txt" /> <Content Include="ExpressionTrees\Results\CheckedArrayInitializers.txt" /> <Content Include="ExpressionTrees\Results\CheckedCoalesceWithNullableBoolean.txt" /> <Content Include="ExpressionTrees\Results\CheckedCoalesceWithUserDefinedConversions.txt" /> <Content Include="ExpressionTrees\Results\CheckedCollectionInitializers.txt" /> <Content Include="ExpressionTrees\Results\CheckedComparisonOperators.txt" /> <Content Include="ExpressionTrees\Results\CheckedConcatenate.txt" /> <Content Include="ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsEven.txt" /> <Content Include="ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsOdd.txt" /> <Content Include="ExpressionTrees\Results\CheckedDirectTrySpecificConversions.txt" /> <Content Include="ExpressionTrees\Results\CheckedLike.txt" /> <Content Include="ExpressionTrees\Results\CheckedMiscellaneousA.txt" /> <Content Include="ExpressionTrees\Results\CheckedObjectInitializers.txt" /> <Content Include="ExpressionTrees\Results\CheckedShortCircuit.txt" /> <Content Include="ExpressionTrees\Results\CheckedUnaryPlusMinusNot.txt" /> <Content Include="ExpressionTrees\Results\CheckedUserDefinedBinaryOperators.txt" /> <Content Include="ExpressionTrees\Results\ExprTree_LegacyTests02_v40_Result.txt" /> <Content Include="ExpressionTrees\Results\ExprTree_LegacyTests02_v45_Result.txt" /> <Content Include="ExpressionTrees\Results\ExprTree_LegacyTests07_Result.txt" /> <Content Include="ExpressionTrees\Results\ExprTree_LegacyTests08_Result.txt" /> <Content Include="ExpressionTrees\Results\ExprTree_LegacyTests09_Result.txt" /> <Content Include="ExpressionTrees\Results\ExprTree_LegacyTests10_Result.txt" /> <Content Include="ExpressionTrees\Results\UncheckedAndOrXor.txt" /> <Content Include="ExpressionTrees\Results\UncheckedArithmeticBinaryOperators.txt" /> <Content Include="ExpressionTrees\Results\UncheckedComparisonOperators.txt" /> <Content Include="ExpressionTrees\Results\UncheckedConcatenate.txt" /> <Content Include="ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsEven.txt" /> <Content Include="ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsOdd.txt" /> <Content Include="ExpressionTrees\Results\UncheckedDirectTrySpecificConversions.txt" /> <Content Include="ExpressionTrees\Results\UncheckedLike.txt" /> <Content Include="ExpressionTrees\Results\UncheckedShortCircuit.txt" /> <Content Include="ExpressionTrees\Results\UncheckedUnaryPlusMinusNot.txt" /> <Content Include="ExpressionTrees\Results\UncheckedUserDefinedBinaryOperators.txt" /> <Content Include="ExpressionTrees\Results\XmlLiteralsInExprLambda01_Result.txt" /> <Content Include="ExpressionTrees\Results\XmlLiteralsInExprLambda02_Result.txt" /> <Content Include="ExpressionTrees\Results\XmlLiteralsInExprLambda03_Result.txt" /> </ItemGroup> <ItemGroup> <Content Include="CodeGen\ConversionsILGenTestSource.vb" /> <Content Include="CodeGen\ConversionsILGenTestSource1.vb" /> <Content Include="CodeGen\ConversionsILGenTestSource2.vb" /> <Content Include="ExpressionTrees\Sources\UserDefinedBinaryOperators.vb" /> <Content Include="ExpressionTrees\Tests\TestConversion_Narrowing_UDC.vb" /> <Content Include="ExpressionTrees\Tests\TestConversion_TypeMatrix_UserTypes.vb" /> <Content Include="ExpressionTrees\Tests\TestConversion_Widening_UDC.vb" /> <Content Include="ExpressionTrees\Tests\TestUnary_UDO_IsTrueIsFalse.vb" /> <Content Include="ExpressionTrees\Tests\TestUnary_UDO_PlusMinusNot.vb" /> <Compile Remove="CodeGen\ConversionsILGenTestSource.vb" /> <Compile Remove="CodeGen\ConversionsILGenTestSource1.vb" /> <Compile Remove="CodeGen\ConversionsILGenTestSource2.vb" /> <Compile Remove="ExpressionTrees\Sources\UserDefinedBinaryOperators.vb" /> <Compile Remove="ExpressionTrees\Tests\TestConversion_Narrowing_UDC.vb" /> <Compile Remove="ExpressionTrees\Tests\TestConversion_TypeMatrix_UserTypes.vb" /> <Compile Remove="ExpressionTrees\Tests\TestConversion_Widening_UDC.vb" /> <Compile Remove="ExpressionTrees\Tests\TestUnary_UDO_IsTrueIsFalse.vb" /> <Compile Remove="ExpressionTrees\Tests\TestUnary_UDO_PlusMinusNot.vb" /> </ItemGroup> <ItemGroup> <Import Include="IdentifierComparison = Microsoft.CodeAnalysis.CaseInsensitiveComparison" /> <Import Include="Roslyn.Utilities" /> <Import Include="System.Xml.Linq" /> <Import Include="Xunit" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="CodeGen\ConversionsILGenTestBaseline.txt" /> <EmbeddedResource Include="CodeGen\ConversionsILGenTestBaseline1.txt" /> <EmbeddedResource Include="CodeGen\ConversionsILGenTestSource.vb" /> <EmbeddedResource Include="CodeGen\ConversionsILGenTestSource1.vb" /> <EmbeddedResource Include="CodeGen\ConversionsILGenTestSource2.vb" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedArithmeticBinaryOperators.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedArithmeticBinaryOperators.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndOrXor.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedAndOrXor.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedShortCircuit.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedShortCircuit.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedComparisonOperators.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedComparisonOperators.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedIsIsNotNothing.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedIsIsNot.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedConcatenate.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedConcatenate.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedLike.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedLike.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedWithDate.txt" /> <EmbeddedResource Include="ExpressionTrees\Sources\ExprLambdaUtils.vb" /> <EmbeddedResource Include="ExpressionTrees\Sources\UserDefinedBinaryOperators.vb" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedUserDefinedBinaryOperators.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedUserDefinedBinaryOperators.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedNothingConversions.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedTypeParameters.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedDirectTrySpecificConversions.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedDirectTrySpecificConversions.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsEven.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsEven.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsOdd.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsOdd.txt" /> <EmbeddedResource Include="ExpressionTrees\Tests\TestConversion_TypeMatrix_UserTypes.vb" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedUserTypeConversions.txt" /> <EmbeddedResource Include="ExpressionTrees\Tests\TestConversion_Narrowing_UDC.vb" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedNarrowingUDC.txt" /> <EmbeddedResource Include="ExpressionTrees\Tests\TestConversion_Widening_UDC.vb" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedWideningUDC.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedUnaryPlusMinusNot.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedUnaryPlusMinusNot.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedIsTrueIsFalse.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedUdoUnaryPlusMinusNot.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedCoalesceWithNullableBoolean.txt" /> <EmbeddedResource Include="ExpressionTrees\Tests\TestUnary_UDO_PlusMinusNot.vb" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedCoalesceWithUserDefinedConversions.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedObjectInitializers.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedArrayInitializers.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedCollectionInitializers.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedMiscellaneousA.txt" /> <EmbeddedResource Include="ExpressionTrees\Tests\TestUnary_UDO_IsTrueIsFalse.vb" /> <EmbeddedResource Include="ExpressionTrees\Sources\QueryHelper.vb" /> <EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests07_Result.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests08_Result.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests09_Result.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\XmlLiteralsInExprLambda01_Result.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\XmlLiteralsInExprLambda02_Result.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\XmlLiteralsInExprLambda03_Result.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests10_Result.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests02_v40_Result.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests02_v45_Result.txt" /> </ItemGroup> <ItemGroup> <Folder Include="My Project\" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> <Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <TargetFrameworks>net5.0;net472</TargetFrameworks> <RootNamespace></RootNamespace> <!-- Disabling on assumption --> <SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests> <EmbeddedResourceUseDependentUponConvention>false</EmbeddedResourceUseDependentUponConvention> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> <ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" /> <ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="Microsoft.DiaSymReader" Version="$(MicrosoftDiaSymReaderVersion)" /> <PackageReference Include="Microsoft.VisualBasic" Version="$(MicrosoftVisualBasicVersion)" Condition="'$(TargetFramework)' == 'net472'" /> </ItemGroup> <ItemGroup> <Content Include="CodeGen\ConversionsILGenTestBaseline.txt" /> <Content Include="CodeGen\ConversionsILGenTestBaseline1.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndOrXor.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedIsIsNot.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedIsIsNotNothing.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedIsTrueIsFalse.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedNarrowingUDC.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedNothingConversions.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedTypeParameters.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedUdoUnaryPlusMinusNot.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedUserTypeConversions.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedWideningUDC.txt" /> <Content Include="ExpressionTrees\Results\CheckedAndUncheckedWithDate.txt" /> <Content Include="ExpressionTrees\Results\CheckedArithmeticBinaryOperators.txt" /> <Content Include="ExpressionTrees\Results\CheckedArrayInitializers.txt" /> <Content Include="ExpressionTrees\Results\CheckedCoalesceWithNullableBoolean.txt" /> <Content Include="ExpressionTrees\Results\CheckedCoalesceWithUserDefinedConversions.txt" /> <Content Include="ExpressionTrees\Results\CheckedCollectionInitializers.txt" /> <Content Include="ExpressionTrees\Results\CheckedComparisonOperators.txt" /> <Content Include="ExpressionTrees\Results\CheckedConcatenate.txt" /> <Content Include="ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsEven.txt" /> <Content Include="ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsOdd.txt" /> <Content Include="ExpressionTrees\Results\CheckedDirectTrySpecificConversions.txt" /> <Content Include="ExpressionTrees\Results\CheckedLike.txt" /> <Content Include="ExpressionTrees\Results\CheckedMiscellaneousA.txt" /> <Content Include="ExpressionTrees\Results\CheckedObjectInitializers.txt" /> <Content Include="ExpressionTrees\Results\CheckedShortCircuit.txt" /> <Content Include="ExpressionTrees\Results\CheckedUnaryPlusMinusNot.txt" /> <Content Include="ExpressionTrees\Results\CheckedUserDefinedBinaryOperators.txt" /> <Content Include="ExpressionTrees\Results\ExprTree_LegacyTests02_v40_Result.txt" /> <Content Include="ExpressionTrees\Results\ExprTree_LegacyTests02_v45_Result.txt" /> <Content Include="ExpressionTrees\Results\ExprTree_LegacyTests07_Result.txt" /> <Content Include="ExpressionTrees\Results\ExprTree_LegacyTests08_Result.txt" /> <Content Include="ExpressionTrees\Results\ExprTree_LegacyTests09_Result.txt" /> <Content Include="ExpressionTrees\Results\ExprTree_LegacyTests10_Result.txt" /> <Content Include="ExpressionTrees\Results\UncheckedAndOrXor.txt" /> <Content Include="ExpressionTrees\Results\UncheckedArithmeticBinaryOperators.txt" /> <Content Include="ExpressionTrees\Results\UncheckedComparisonOperators.txt" /> <Content Include="ExpressionTrees\Results\UncheckedConcatenate.txt" /> <Content Include="ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsEven.txt" /> <Content Include="ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsOdd.txt" /> <Content Include="ExpressionTrees\Results\UncheckedDirectTrySpecificConversions.txt" /> <Content Include="ExpressionTrees\Results\UncheckedLike.txt" /> <Content Include="ExpressionTrees\Results\UncheckedShortCircuit.txt" /> <Content Include="ExpressionTrees\Results\UncheckedUnaryPlusMinusNot.txt" /> <Content Include="ExpressionTrees\Results\UncheckedUserDefinedBinaryOperators.txt" /> <Content Include="ExpressionTrees\Results\XmlLiteralsInExprLambda01_Result.txt" /> <Content Include="ExpressionTrees\Results\XmlLiteralsInExprLambda02_Result.txt" /> <Content Include="ExpressionTrees\Results\XmlLiteralsInExprLambda03_Result.txt" /> </ItemGroup> <ItemGroup> <Content Include="CodeGen\ConversionsILGenTestSource.vb" /> <Content Include="CodeGen\ConversionsILGenTestSource1.vb" /> <Content Include="CodeGen\ConversionsILGenTestSource2.vb" /> <Content Include="ExpressionTrees\Sources\UserDefinedBinaryOperators.vb" /> <Content Include="ExpressionTrees\Tests\TestConversion_Narrowing_UDC.vb" /> <Content Include="ExpressionTrees\Tests\TestConversion_TypeMatrix_UserTypes.vb" /> <Content Include="ExpressionTrees\Tests\TestConversion_Widening_UDC.vb" /> <Content Include="ExpressionTrees\Tests\TestUnary_UDO_IsTrueIsFalse.vb" /> <Content Include="ExpressionTrees\Tests\TestUnary_UDO_PlusMinusNot.vb" /> <Compile Remove="CodeGen\ConversionsILGenTestSource.vb" /> <Compile Remove="CodeGen\ConversionsILGenTestSource1.vb" /> <Compile Remove="CodeGen\ConversionsILGenTestSource2.vb" /> <Compile Remove="ExpressionTrees\Sources\UserDefinedBinaryOperators.vb" /> <Compile Remove="ExpressionTrees\Tests\TestConversion_Narrowing_UDC.vb" /> <Compile Remove="ExpressionTrees\Tests\TestConversion_TypeMatrix_UserTypes.vb" /> <Compile Remove="ExpressionTrees\Tests\TestConversion_Widening_UDC.vb" /> <Compile Remove="ExpressionTrees\Tests\TestUnary_UDO_IsTrueIsFalse.vb" /> <Compile Remove="ExpressionTrees\Tests\TestUnary_UDO_PlusMinusNot.vb" /> </ItemGroup> <ItemGroup> <Import Include="IdentifierComparison = Microsoft.CodeAnalysis.CaseInsensitiveComparison" /> <Import Include="Roslyn.Utilities" /> <Import Include="System.Xml.Linq" /> <Import Include="Xunit" /> </ItemGroup> <ItemGroup> <EmbeddedResource Include="CodeGen\ConversionsILGenTestBaseline.txt" /> <EmbeddedResource Include="CodeGen\ConversionsILGenTestBaseline1.txt" /> <EmbeddedResource Include="CodeGen\ConversionsILGenTestSource.vb" /> <EmbeddedResource Include="CodeGen\ConversionsILGenTestSource1.vb" /> <EmbeddedResource Include="CodeGen\ConversionsILGenTestSource2.vb" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedArithmeticBinaryOperators.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedArithmeticBinaryOperators.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndOrXor.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedAndOrXor.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedShortCircuit.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedShortCircuit.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedComparisonOperators.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedComparisonOperators.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedIsIsNotNothing.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedIsIsNot.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedConcatenate.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedConcatenate.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedLike.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedLike.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedWithDate.txt" /> <EmbeddedResource Include="ExpressionTrees\Sources\ExprLambdaUtils.vb" /> <EmbeddedResource Include="ExpressionTrees\Sources\UserDefinedBinaryOperators.vb" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedUserDefinedBinaryOperators.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedUserDefinedBinaryOperators.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedNothingConversions.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedTypeParameters.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedDirectTrySpecificConversions.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedDirectTrySpecificConversions.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsEven.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsEven.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedCTypeAndImplicitConversionsOdd.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedCTypeAndImplicitConversionsOdd.txt" /> <EmbeddedResource Include="ExpressionTrees\Tests\TestConversion_TypeMatrix_UserTypes.vb" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedUserTypeConversions.txt" /> <EmbeddedResource Include="ExpressionTrees\Tests\TestConversion_Narrowing_UDC.vb" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedNarrowingUDC.txt" /> <EmbeddedResource Include="ExpressionTrees\Tests\TestConversion_Widening_UDC.vb" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedWideningUDC.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedUnaryPlusMinusNot.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\UncheckedUnaryPlusMinusNot.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedIsTrueIsFalse.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedAndUncheckedUdoUnaryPlusMinusNot.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedCoalesceWithNullableBoolean.txt" /> <EmbeddedResource Include="ExpressionTrees\Tests\TestUnary_UDO_PlusMinusNot.vb" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedCoalesceWithUserDefinedConversions.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedObjectInitializers.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedArrayInitializers.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedCollectionInitializers.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\CheckedMiscellaneousA.txt" /> <EmbeddedResource Include="ExpressionTrees\Tests\TestUnary_UDO_IsTrueIsFalse.vb" /> <EmbeddedResource Include="ExpressionTrees\Sources\QueryHelper.vb" /> <EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests07_Result.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests08_Result.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests09_Result.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\XmlLiteralsInExprLambda01_Result.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\XmlLiteralsInExprLambda02_Result.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\XmlLiteralsInExprLambda03_Result.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests10_Result.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests02_v40_Result.txt" /> <EmbeddedResource Include="ExpressionTrees\Results\ExprTree_LegacyTests02_v45_Result.txt" /> </ItemGroup> <ItemGroup> <Folder Include="My Project\" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> <Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" /> </Project>
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Compilers/Core/MSBuildTask/xlf/ErrorString.zh-Hans.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="zh-Hans" original="../ErrorString.resx"> <body> <trans-unit id="Compiler_UnexpectedException"> <source>MSB3883: Unexpected exception: </source> <target state="translated">MSB3883: 意外的异常: </target> <note>{StrBegin="MSB3883: "}</note> </trans-unit> <trans-unit id="Csc_AssemblyAliasContainsIllegalCharacters"> <source>MSB3053: The assembly alias "{1}" on reference "{0}" contains illegal characters.</source> <target state="translated">MSB3053: 引用“{0}”上的程序集别名“{1}”包含非法字符。</target> <note>{StrBegin="MSB3053: "}</note> </trans-unit> <trans-unit id="Csc_InvalidParameter"> <source>MSB3051: The parameter to the compiler is invalid. {0}</source> <target state="translated">MSB3051: 编译器的参数无效。 {0}</target> <note>{StrBegin="MSB3051: "}</note> </trans-unit> <trans-unit id="Csc_InvalidParameterWarning"> <source>MSB3052: The parameter to the compiler is invalid, '{0}{1}' will be ignored.</source> <target state="translated">MSB3052: 编译器的参数无效,“{0}{1}”将被忽略。</target> <note>{StrBegin="MSB3052: "}</note> </trans-unit> <trans-unit id="General_CannotConvertStringToBool"> <source>The string "{0}" cannot be converted to a boolean (true/false) value.</source> <target state="translated">无法将字符串“{0}”转换为布尔值(true/false)。</target> <note /> </trans-unit> <trans-unit id="General_CouldNotSetHostObjectParameter"> <source>MSB3081: A problem occurred while trying to set the "{0}" parameter for the IDE's in-process compiler. {1}</source> <target state="translated">MSB3081: 尝试设置 IDE 的进程内编译器的“{0}”参数时出现问题。{1}</target> <note>{StrBegin="MSB3081: "}</note> </trans-unit> <trans-unit id="General_DuplicateItemsNotSupported"> <source>MSB3105: The item "{0}" was specified more than once in the "{1}" parameter. Duplicate items are not supported by the "{1}" parameter.</source> <target state="translated">MSB3105: 在“{1}”参数中指定了项“{0}”多次。“{1}”参数不支持重复项。</target> <note>{StrBegin="MSB3105: "}</note> </trans-unit> <trans-unit id="General_DuplicateItemsNotSupportedWithMetadata"> <source>MSB3083: The item "{0}" was specified more than once in the "{1}" parameter and both items had the same value "{2}" for the "{3}" metadata. Duplicate items are not supported by the "{1}" parameter unless they have different values for the "{3}" metadata.</source> <target state="translated">MSB3083: 在参数“{1}”中指定了项“{0}”多次,并且这两个项对于元数据“{3}”具有相同的值“{2}”。参数“{1}”不支持重复项,除非这些项具有不同的“{3}”元数据值。</target> <note>{StrBegin="MSB3083: "}</note> </trans-unit> <trans-unit id="General_ExpectedFileMissing"> <source>Expected file "{0}" does not exist.</source> <target state="translated">所需文件“{0}”不存在。</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_SkippingCopy1"> <source>Reference assembly "{0}" already has latest information. Leaving it untouched.</source> <target state="translated">引用程序集“{0}”已具有最新信息。请不要改动。</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_SourceNotRef1"> <source>Could not extract the MVID from "{0}". Are you sure it is a reference assembly?</source> <target state="translated">无法从“{0}”提取 MVID。是否确定它是引用程序集?</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_BadSource3"> <source>Failed to check the content hash of the source ref assembly '{0}': {1} {2}</source> <target state="translated">未能查看源引用程序集“{0}”的内容哈希: {1} {2}</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_BadDestination1"> <source>Failed to check the content hash of the destination ref assembly '{0}'. It will be overwritten.</source> <target state="translated">未能检查目标引用程序集“{0}”的内容哈希。将对其进行覆盖。</target> <note /> </trans-unit> <trans-unit id="General_ToolFileNotFound"> <source>MSB3082: Task failed because "{0}" was not found.</source> <target state="translated">MSB3082: 由于找不到“{0}”,任务失败。</target> <note>{StrBegin="MSB3082: "}</note> </trans-unit> <trans-unit id="General_IncorrectHostObject"> <source>MSB3087: An incompatible host object was passed into the "{0}" task. The host object for this task must implement the "{1}" interface.</source> <target state="translated">MSB3087: 向任务“{0}”传入了不兼容的宿主对象。此任务的宿主对象必须实现“{1}”接口。</target> <note>{StrBegin="MSB3087: "}</note> </trans-unit> <trans-unit id="General_InvalidAttributeMetadata"> <source>Item "{0}" has attribute "{1}" with value "{2}" that could not be converted to "{3}".</source> <target state="translated">项“{0}”具有值为“{2}”的特性“{1}”,该值未能转换为“{3}”。</target> <note /> </trans-unit> <trans-unit id="General_ParameterUnsupportedOnHostCompiler"> <source>The IDE's in-process compiler does not support the specified values for the "{0}" parameter. Therefore, this task will fallback to using the command-line compiler.</source> <target state="translated">IDE 的进程内编译器不支持为“{0}”参数指定的值。因此,此任务将退而使用命令行编译器。</target> <note /> </trans-unit> <trans-unit id="General_ReferenceDoesNotExist"> <source>MSB3104: The referenced assembly "{0}" was not found. If this assembly is produced by another one of your projects, please make sure to build that project before building this one.</source> <target state="translated">MSB3104: 未找到引用的程序集“{0}”。如果此程序集是由你的另一个项目生成的,请确保在生成该项目之后再生成此程序集。</target> <note>{StrBegin="MSB3104: "}</note> </trans-unit> <trans-unit id="General_UnableToReadFile"> <source>File "{0}" could not be read: {1}</source> <target state="translated">无法读取文件 "{0}": {1}</target> <note /> </trans-unit> <trans-unit id="ImplicitlySkipAnalyzersMessage"> <source>Skipping analyzers to speed up the build. You can execute 'Build' or 'Rebuild' command to run analyzers.</source> <target state="translated">跳过分析器以加快生成速度。可以执行“生成”或“重新生成”命令来运行分析器。</target> <note /> </trans-unit> <trans-unit id="SharedCompilationFallback"> <source>Shared compilation failed; falling back to tool: {0}</source> <target state="translated">共享编译失败; 回到工具: {0}</target> <note /> </trans-unit> <trans-unit id="UsingSharedCompilation"> <source>Using shared compilation with compiler from directory: {0}</source> <target state="translated">对来自后列目录的编译器使用共享编译: {0}</target> <note /> </trans-unit> <trans-unit id="Vbc_EnumParameterHasInvalidValue"> <source>MSB3401: "{1}" is an invalid value for the "{0}" parameter. The valid values are: {2}</source> <target state="translated">MSB3401: “{1}”是无效的“{0}”参数值。有效值为: {2}</target> <note>{StrBegin="MSB3401: "}</note> </trans-unit> <trans-unit id="Vbc_ParameterHasInvalidValue"> <source>"{1}" is an invalid value for the "{0}" parameter.</source> <target state="translated">“{1}”是无效的“{0}”参数值。</target> <note /> </trans-unit> <trans-unit id="Vbc_RenamePDB"> <source>MSB3402: There was an error creating the pdb file "{0}". {1}</source> <target state="translated">MSB3402: 创建 pdb 文件“{0}”时出现错误。{1}</target> <note>{StrBegin="MSB3402: "}</note> </trans-unit> <trans-unit id="MapSourceRoots.ContainsDuplicate"> <source>{0} contains duplicate items '{1}' with conflicting metadata '{2}': '{3}' and '{4}'</source> <target state="translated">{0} 包含重复项“{1}”和冲突元数据“{2}”:“{3}”和“{4}”</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.PathMustEndWithSlashOrBackslash"> <source>{0} paths are required to end with a slash or backslash: '{1}'</source> <target state="translated">要求“{0}”路径以斜杠或反斜杠结尾:“{1}”</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.NoTopLevelSourceRoot"> <source>{0} items must include at least one top-level (not nested) item when {1} is true</source> <target state="translated">当 {1} 为 true,{0} 项必须包括至少一个顶级(未嵌套)项</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.NoSuchTopLevelSourceRoot"> <source>The value of {0} not found in {1} items, or the corresponding item is not a top-level source root: '{2}'</source> <target state="translated">未在 {1} 项中找到值 {0},或者对应项不是顶级源根目录:“{2}”</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="zh-Hans" original="../ErrorString.resx"> <body> <trans-unit id="Compiler_UnexpectedException"> <source>MSB3883: Unexpected exception: </source> <target state="translated">MSB3883: 意外的异常: </target> <note>{StrBegin="MSB3883: "}</note> </trans-unit> <trans-unit id="Csc_AssemblyAliasContainsIllegalCharacters"> <source>MSB3053: The assembly alias "{1}" on reference "{0}" contains illegal characters.</source> <target state="translated">MSB3053: 引用“{0}”上的程序集别名“{1}”包含非法字符。</target> <note>{StrBegin="MSB3053: "}</note> </trans-unit> <trans-unit id="Csc_InvalidParameter"> <source>MSB3051: The parameter to the compiler is invalid. {0}</source> <target state="translated">MSB3051: 编译器的参数无效。 {0}</target> <note>{StrBegin="MSB3051: "}</note> </trans-unit> <trans-unit id="Csc_InvalidParameterWarning"> <source>MSB3052: The parameter to the compiler is invalid, '{0}{1}' will be ignored.</source> <target state="translated">MSB3052: 编译器的参数无效,“{0}{1}”将被忽略。</target> <note>{StrBegin="MSB3052: "}</note> </trans-unit> <trans-unit id="General_CannotConvertStringToBool"> <source>The string "{0}" cannot be converted to a boolean (true/false) value.</source> <target state="translated">无法将字符串“{0}”转换为布尔值(true/false)。</target> <note /> </trans-unit> <trans-unit id="General_CouldNotSetHostObjectParameter"> <source>MSB3081: A problem occurred while trying to set the "{0}" parameter for the IDE's in-process compiler. {1}</source> <target state="translated">MSB3081: 尝试设置 IDE 的进程内编译器的“{0}”参数时出现问题。{1}</target> <note>{StrBegin="MSB3081: "}</note> </trans-unit> <trans-unit id="General_DuplicateItemsNotSupported"> <source>MSB3105: The item "{0}" was specified more than once in the "{1}" parameter. Duplicate items are not supported by the "{1}" parameter.</source> <target state="translated">MSB3105: 在“{1}”参数中指定了项“{0}”多次。“{1}”参数不支持重复项。</target> <note>{StrBegin="MSB3105: "}</note> </trans-unit> <trans-unit id="General_DuplicateItemsNotSupportedWithMetadata"> <source>MSB3083: The item "{0}" was specified more than once in the "{1}" parameter and both items had the same value "{2}" for the "{3}" metadata. Duplicate items are not supported by the "{1}" parameter unless they have different values for the "{3}" metadata.</source> <target state="translated">MSB3083: 在参数“{1}”中指定了项“{0}”多次,并且这两个项对于元数据“{3}”具有相同的值“{2}”。参数“{1}”不支持重复项,除非这些项具有不同的“{3}”元数据值。</target> <note>{StrBegin="MSB3083: "}</note> </trans-unit> <trans-unit id="General_ExpectedFileMissing"> <source>Expected file "{0}" does not exist.</source> <target state="translated">所需文件“{0}”不存在。</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_SkippingCopy1"> <source>Reference assembly "{0}" already has latest information. Leaving it untouched.</source> <target state="translated">引用程序集“{0}”已具有最新信息。请不要改动。</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_SourceNotRef1"> <source>Could not extract the MVID from "{0}". Are you sure it is a reference assembly?</source> <target state="translated">无法从“{0}”提取 MVID。是否确定它是引用程序集?</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_BadSource3"> <source>Failed to check the content hash of the source ref assembly '{0}': {1} {2}</source> <target state="translated">未能查看源引用程序集“{0}”的内容哈希: {1} {2}</target> <note /> </trans-unit> <trans-unit id="CopyRefAssembly_BadDestination1"> <source>Failed to check the content hash of the destination ref assembly '{0}'. It will be overwritten.</source> <target state="translated">未能检查目标引用程序集“{0}”的内容哈希。将对其进行覆盖。</target> <note /> </trans-unit> <trans-unit id="General_ToolFileNotFound"> <source>MSB3082: Task failed because "{0}" was not found.</source> <target state="translated">MSB3082: 由于找不到“{0}”,任务失败。</target> <note>{StrBegin="MSB3082: "}</note> </trans-unit> <trans-unit id="General_IncorrectHostObject"> <source>MSB3087: An incompatible host object was passed into the "{0}" task. The host object for this task must implement the "{1}" interface.</source> <target state="translated">MSB3087: 向任务“{0}”传入了不兼容的宿主对象。此任务的宿主对象必须实现“{1}”接口。</target> <note>{StrBegin="MSB3087: "}</note> </trans-unit> <trans-unit id="General_InvalidAttributeMetadata"> <source>Item "{0}" has attribute "{1}" with value "{2}" that could not be converted to "{3}".</source> <target state="translated">项“{0}”具有值为“{2}”的特性“{1}”,该值未能转换为“{3}”。</target> <note /> </trans-unit> <trans-unit id="General_ParameterUnsupportedOnHostCompiler"> <source>The IDE's in-process compiler does not support the specified values for the "{0}" parameter. Therefore, this task will fallback to using the command-line compiler.</source> <target state="translated">IDE 的进程内编译器不支持为“{0}”参数指定的值。因此,此任务将退而使用命令行编译器。</target> <note /> </trans-unit> <trans-unit id="General_ReferenceDoesNotExist"> <source>MSB3104: The referenced assembly "{0}" was not found. If this assembly is produced by another one of your projects, please make sure to build that project before building this one.</source> <target state="translated">MSB3104: 未找到引用的程序集“{0}”。如果此程序集是由你的另一个项目生成的,请确保在生成该项目之后再生成此程序集。</target> <note>{StrBegin="MSB3104: "}</note> </trans-unit> <trans-unit id="General_UnableToReadFile"> <source>File "{0}" could not be read: {1}</source> <target state="translated">无法读取文件 "{0}": {1}</target> <note /> </trans-unit> <trans-unit id="ImplicitlySkipAnalyzersMessage"> <source>Skipping analyzers to speed up the build. You can execute 'Build' or 'Rebuild' command to run analyzers.</source> <target state="translated">跳过分析器以加快生成速度。可以执行“生成”或“重新生成”命令来运行分析器。</target> <note /> </trans-unit> <trans-unit id="SharedCompilationFallback"> <source>Shared compilation failed; falling back to tool: {0}</source> <target state="translated">共享编译失败; 回到工具: {0}</target> <note /> </trans-unit> <trans-unit id="UsingSharedCompilation"> <source>Using shared compilation with compiler from directory: {0}</source> <target state="translated">对来自后列目录的编译器使用共享编译: {0}</target> <note /> </trans-unit> <trans-unit id="Vbc_EnumParameterHasInvalidValue"> <source>MSB3401: "{1}" is an invalid value for the "{0}" parameter. The valid values are: {2}</source> <target state="translated">MSB3401: “{1}”是无效的“{0}”参数值。有效值为: {2}</target> <note>{StrBegin="MSB3401: "}</note> </trans-unit> <trans-unit id="Vbc_ParameterHasInvalidValue"> <source>"{1}" is an invalid value for the "{0}" parameter.</source> <target state="translated">“{1}”是无效的“{0}”参数值。</target> <note /> </trans-unit> <trans-unit id="Vbc_RenamePDB"> <source>MSB3402: There was an error creating the pdb file "{0}". {1}</source> <target state="translated">MSB3402: 创建 pdb 文件“{0}”时出现错误。{1}</target> <note>{StrBegin="MSB3402: "}</note> </trans-unit> <trans-unit id="MapSourceRoots.ContainsDuplicate"> <source>{0} contains duplicate items '{1}' with conflicting metadata '{2}': '{3}' and '{4}'</source> <target state="translated">{0} 包含重复项“{1}”和冲突元数据“{2}”:“{3}”和“{4}”</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.PathMustEndWithSlashOrBackslash"> <source>{0} paths are required to end with a slash or backslash: '{1}'</source> <target state="translated">要求“{0}”路径以斜杠或反斜杠结尾:“{1}”</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.NoTopLevelSourceRoot"> <source>{0} items must include at least one top-level (not nested) item when {1} is true</source> <target state="translated">当 {1} 为 true,{0} 项必须包括至少一个顶级(未嵌套)项</target> <note /> </trans-unit> <trans-unit id="MapSourceRoots.NoSuchTopLevelSourceRoot"> <source>The value of {0} not found in {1} items, or the corresponding item is not a top-level source root: '{2}'</source> <target state="translated">未在 {1} 项中找到值 {0},或者对应项不是顶级源根目录:“{2}”</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/EditorFeatures/Test2/IntelliSense/IntellisenseQuickInfoBuilderTests_Lists.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.Classification Imports Microsoft.CodeAnalysis.Test.Utilities.QuickInfo Imports Microsoft.VisualStudio.Core.Imaging Imports Microsoft.VisualStudio.Imaging Imports Microsoft.VisualStudio.Text.Adornments Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Public Class IntellisenseQuickInfoBuilderTests_Lists Inherits AbstractIntellisenseQuickInfoBuilderTests <WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)> <InlineData(New Object() {New String() {"item", "description"}})> <InlineData(New Object() {New String() {"item"}})> Public Async Function QuickInfoForBulletedList(itemTags As String()) As Task Dim openItemTag = String.Join("", itemTags.Select(Function(tag) $"<{tag}>")) Dim closeItemTag = String.Join("", itemTags.Reverse().Select(Function(tag) $"</{tag}>")) Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Threading; class MyClass { /// &lt;summary&gt; /// &lt;list type="bullet"&gt; /// <%= openItemTag %>Item 1<%= closeItemTag %> /// <%= openItemTag %>Item 2<%= closeItemTag %> /// &lt;/list&gt; /// &lt;/summary&gt; void MyMethod() { MyM$$ethod(); } } </Document> </Project> </Workspace> Dim intellisenseQuickInfo = Await GetQuickInfoItemAsync(workspace, LanguageNames.CSharp) Dim expected = New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ContainerElement( ContainerElementStyle.Stacked, New ContainerElement( ContainerElementStyle.Wrapped, New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPrivate)), New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.ClassName, "MyClass", navigationAction:=Sub() Return, "MyClass"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."), New ClassifiedTextRun(ClassificationTypeNames.MethodName, "MyMethod", navigationAction:=Sub() Return, "void MyClass.MyMethod()"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "• ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 1"))))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "• ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 2"))))) ToolTipAssert.EqualContent(expected, intellisenseQuickInfo.Item) End Function <WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)> <InlineData(New Object() {New String() {"item", "description"}})> <InlineData(New Object() {New String() {"item"}})> Public Async Function QuickInfoForNumberedList(itemTags As String()) As Task Dim openItemTag = String.Join("", itemTags.Select(Function(tag) $"<{tag}>")) Dim closeItemTag = String.Join("", itemTags.Reverse().Select(Function(tag) $"</{tag}>")) Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Threading; class MyClass { /// &lt;summary&gt; /// &lt;list type="number"&gt; /// <%= openItemTag %>Item 1<%= closeItemTag %> /// <%= openItemTag %>Item 2<%= closeItemTag %> /// &lt;/list&gt; /// &lt;/summary&gt; void MyMethod() { MyM$$ethod(); } } </Document> </Project> </Workspace> Dim intellisenseQuickInfo = Await GetQuickInfoItemAsync(workspace, LanguageNames.CSharp) Dim expected = New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ContainerElement( ContainerElementStyle.Stacked, New ContainerElement( ContainerElementStyle.Wrapped, New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPrivate)), New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.ClassName, "MyClass", navigationAction:=Sub() Return, "MyClass"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."), New ClassifiedTextRun(ClassificationTypeNames.MethodName, "MyMethod", navigationAction:=Sub() Return, "void MyClass.MyMethod()"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "1. ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 1"))))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "2. ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 2"))))) ToolTipAssert.EqualContent(expected, intellisenseQuickInfo.Item) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)> Public Async Function QuickInfoForBulletedTermList() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Threading; class MyClass { /// &lt;summary&gt; /// &lt;list type="bullet"&gt; /// &lt;item&gt;&lt;term&gt;word1&lt;/term&gt;&lt;description&gt;Item 1&lt;/description&gt;&lt;/item&gt; /// &lt;item&gt;&lt;term&gt;word2&lt;/term&gt;&lt;description&gt;Item 2&lt;/description&gt;&lt;/item&gt; /// &lt;/list&gt; /// &lt;/summary&gt; void MyMethod() { MyM$$ethod(); } } </Document> </Project> </Workspace> Dim intellisenseQuickInfo = Await GetQuickInfoItemAsync(workspace, LanguageNames.CSharp) Dim expected = New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ContainerElement( ContainerElementStyle.Stacked, New ContainerElement( ContainerElementStyle.Wrapped, New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPrivate)), New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.ClassName, "MyClass", navigationAction:=Sub() Return, "MyClass"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."), New ClassifiedTextRun(ClassificationTypeNames.MethodName, "MyMethod", navigationAction:=Sub() Return, "void MyClass.MyMethod()"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "• ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "word1", ClassifiedTextRunStyle.Bold), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.Text, "–"), New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 1"))))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "• ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "word2", ClassifiedTextRunStyle.Bold), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.Text, "–"), New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 2"))))) ToolTipAssert.EqualContent(expected, intellisenseQuickInfo.Item) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)> Public Async Function QuickInfoForNumberedTermList() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Threading; class MyClass { /// &lt;summary&gt; /// &lt;list type="number"&gt; /// &lt;item&gt;&lt;term&gt;word1&lt;/term&gt;&lt;description&gt;Item 1&lt;/description&gt;&lt;/item&gt; /// &lt;item&gt;&lt;term&gt;word2&lt;/term&gt;&lt;description&gt;Item 2&lt;/description&gt;&lt;/item&gt; /// &lt;/list&gt; /// &lt;/summary&gt; void MyMethod() { MyM$$ethod(); } } </Document> </Project> </Workspace> Dim intellisenseQuickInfo = Await GetQuickInfoItemAsync(workspace, LanguageNames.CSharp) Dim expected = New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ContainerElement( ContainerElementStyle.Stacked, New ContainerElement( ContainerElementStyle.Wrapped, New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPrivate)), New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.ClassName, "MyClass", navigationAction:=Sub() Return, "MyClass"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."), New ClassifiedTextRun(ClassificationTypeNames.MethodName, "MyMethod", navigationAction:=Sub() Return, "void MyClass.MyMethod()"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "1. ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "word1", ClassifiedTextRunStyle.Bold), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.Text, "–"), New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 1"))))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "2. ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "word2", ClassifiedTextRunStyle.Bold), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.Text, "–"), New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 2"))))) ToolTipAssert.EqualContent(expected, intellisenseQuickInfo.Item) End Function <WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)> <InlineData(New Object() {New String() {"item", "description"}})> <InlineData(New Object() {New String() {"item"}})> Public Async Function QuickInfoForNestedLists(itemTags As String()) As Task Dim openItemTag = String.Join("", itemTags.Select(Function(tag) $"<{tag}>")) Dim closeItemTag = String.Join("", itemTags.Reverse().Select(Function(tag) $"</{tag}>")) Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Threading; class MyClass { /// &lt;summary&gt; /// &lt;list type="number"&gt; /// <%= openItemTag %> /// &lt;list type="bullet"&gt; /// <%= openItemTag %>&lt;para&gt;Line1&lt;/para&gt;&lt;para&gt;Line2&lt;/para&gt;<%= closeItemTag %> /// <%= openItemTag %>Item 1.2<%= closeItemTag %> /// &lt;/list&gt; /// <%= closeItemTag %> /// <%= openItemTag %> /// &lt;list type="number"&gt; /// <%= openItemTag %>Item 2.1<%= closeItemTag %> /// <%= openItemTag %>&lt;para&gt;Line1&lt;/para&gt;&lt;para&gt;Line2&lt;/para&gt;<%= closeItemTag %> /// &lt;/list&gt; /// <%= closeItemTag %> /// &lt;/list&gt; /// &lt;/summary&gt; void MyMethod() { MyM$$ethod(); } } </Document> </Project> </Workspace> Dim intellisenseQuickInfo = Await GetQuickInfoItemAsync(workspace, LanguageNames.CSharp) Dim expected = New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ContainerElement( ContainerElementStyle.Stacked, New ContainerElement( ContainerElementStyle.Wrapped, New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPrivate)), New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.ClassName, "MyClass", navigationAction:=Sub() Return, "MyClass"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."), New ClassifiedTextRun(ClassificationTypeNames.MethodName, "MyMethod", navigationAction:=Sub() Return, "void MyClass.MyMethod()"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "1. ")), New ContainerElement( ContainerElementStyle.Stacked, New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "• ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Line1")), New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Line2"))))), New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "• ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 1.2")))))))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "2. ")), New ContainerElement( ContainerElementStyle.Stacked, New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "1. ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 2.1")))), New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "2. ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Line1")), New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Line2"))))))))) ToolTipAssert.EqualContent(expected, intellisenseQuickInfo.Item) 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.Classification Imports Microsoft.CodeAnalysis.Test.Utilities.QuickInfo Imports Microsoft.VisualStudio.Core.Imaging Imports Microsoft.VisualStudio.Imaging Imports Microsoft.VisualStudio.Text.Adornments Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense Public Class IntellisenseQuickInfoBuilderTests_Lists Inherits AbstractIntellisenseQuickInfoBuilderTests <WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)> <InlineData(New Object() {New String() {"item", "description"}})> <InlineData(New Object() {New String() {"item"}})> Public Async Function QuickInfoForBulletedList(itemTags As String()) As Task Dim openItemTag = String.Join("", itemTags.Select(Function(tag) $"<{tag}>")) Dim closeItemTag = String.Join("", itemTags.Reverse().Select(Function(tag) $"</{tag}>")) Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Threading; class MyClass { /// &lt;summary&gt; /// &lt;list type="bullet"&gt; /// <%= openItemTag %>Item 1<%= closeItemTag %> /// <%= openItemTag %>Item 2<%= closeItemTag %> /// &lt;/list&gt; /// &lt;/summary&gt; void MyMethod() { MyM$$ethod(); } } </Document> </Project> </Workspace> Dim intellisenseQuickInfo = Await GetQuickInfoItemAsync(workspace, LanguageNames.CSharp) Dim expected = New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ContainerElement( ContainerElementStyle.Stacked, New ContainerElement( ContainerElementStyle.Wrapped, New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPrivate)), New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.ClassName, "MyClass", navigationAction:=Sub() Return, "MyClass"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."), New ClassifiedTextRun(ClassificationTypeNames.MethodName, "MyMethod", navigationAction:=Sub() Return, "void MyClass.MyMethod()"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "• ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 1"))))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "• ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 2"))))) ToolTipAssert.EqualContent(expected, intellisenseQuickInfo.Item) End Function <WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)> <InlineData(New Object() {New String() {"item", "description"}})> <InlineData(New Object() {New String() {"item"}})> Public Async Function QuickInfoForNumberedList(itemTags As String()) As Task Dim openItemTag = String.Join("", itemTags.Select(Function(tag) $"<{tag}>")) Dim closeItemTag = String.Join("", itemTags.Reverse().Select(Function(tag) $"</{tag}>")) Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Threading; class MyClass { /// &lt;summary&gt; /// &lt;list type="number"&gt; /// <%= openItemTag %>Item 1<%= closeItemTag %> /// <%= openItemTag %>Item 2<%= closeItemTag %> /// &lt;/list&gt; /// &lt;/summary&gt; void MyMethod() { MyM$$ethod(); } } </Document> </Project> </Workspace> Dim intellisenseQuickInfo = Await GetQuickInfoItemAsync(workspace, LanguageNames.CSharp) Dim expected = New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ContainerElement( ContainerElementStyle.Stacked, New ContainerElement( ContainerElementStyle.Wrapped, New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPrivate)), New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.ClassName, "MyClass", navigationAction:=Sub() Return, "MyClass"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."), New ClassifiedTextRun(ClassificationTypeNames.MethodName, "MyMethod", navigationAction:=Sub() Return, "void MyClass.MyMethod()"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "1. ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 1"))))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "2. ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 2"))))) ToolTipAssert.EqualContent(expected, intellisenseQuickInfo.Item) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)> Public Async Function QuickInfoForBulletedTermList() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Threading; class MyClass { /// &lt;summary&gt; /// &lt;list type="bullet"&gt; /// &lt;item&gt;&lt;term&gt;word1&lt;/term&gt;&lt;description&gt;Item 1&lt;/description&gt;&lt;/item&gt; /// &lt;item&gt;&lt;term&gt;word2&lt;/term&gt;&lt;description&gt;Item 2&lt;/description&gt;&lt;/item&gt; /// &lt;/list&gt; /// &lt;/summary&gt; void MyMethod() { MyM$$ethod(); } } </Document> </Project> </Workspace> Dim intellisenseQuickInfo = Await GetQuickInfoItemAsync(workspace, LanguageNames.CSharp) Dim expected = New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ContainerElement( ContainerElementStyle.Stacked, New ContainerElement( ContainerElementStyle.Wrapped, New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPrivate)), New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.ClassName, "MyClass", navigationAction:=Sub() Return, "MyClass"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."), New ClassifiedTextRun(ClassificationTypeNames.MethodName, "MyMethod", navigationAction:=Sub() Return, "void MyClass.MyMethod()"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "• ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "word1", ClassifiedTextRunStyle.Bold), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.Text, "–"), New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 1"))))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "• ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "word2", ClassifiedTextRunStyle.Bold), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.Text, "–"), New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 2"))))) ToolTipAssert.EqualContent(expected, intellisenseQuickInfo.Item) End Function <WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)> Public Async Function QuickInfoForNumberedTermList() As Task Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Threading; class MyClass { /// &lt;summary&gt; /// &lt;list type="number"&gt; /// &lt;item&gt;&lt;term&gt;word1&lt;/term&gt;&lt;description&gt;Item 1&lt;/description&gt;&lt;/item&gt; /// &lt;item&gt;&lt;term&gt;word2&lt;/term&gt;&lt;description&gt;Item 2&lt;/description&gt;&lt;/item&gt; /// &lt;/list&gt; /// &lt;/summary&gt; void MyMethod() { MyM$$ethod(); } } </Document> </Project> </Workspace> Dim intellisenseQuickInfo = Await GetQuickInfoItemAsync(workspace, LanguageNames.CSharp) Dim expected = New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ContainerElement( ContainerElementStyle.Stacked, New ContainerElement( ContainerElementStyle.Wrapped, New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPrivate)), New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.ClassName, "MyClass", navigationAction:=Sub() Return, "MyClass"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."), New ClassifiedTextRun(ClassificationTypeNames.MethodName, "MyMethod", navigationAction:=Sub() Return, "void MyClass.MyMethod()"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "1. ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "word1", ClassifiedTextRunStyle.Bold), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.Text, "–"), New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 1"))))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "2. ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "word2", ClassifiedTextRunStyle.Bold), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.Text, "–"), New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 2"))))) ToolTipAssert.EqualContent(expected, intellisenseQuickInfo.Item) End Function <WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)> <InlineData(New Object() {New String() {"item", "description"}})> <InlineData(New Object() {New String() {"item"}})> Public Async Function QuickInfoForNestedLists(itemTags As String()) As Task Dim openItemTag = String.Join("", itemTags.Select(Function(tag) $"<{tag}>")) Dim closeItemTag = String.Join("", itemTags.Reverse().Select(Function(tag) $"</{tag}>")) Dim workspace = <Workspace> <Project Language="C#" CommonReferences="true"> <Document> using System.Threading; class MyClass { /// &lt;summary&gt; /// &lt;list type="number"&gt; /// <%= openItemTag %> /// &lt;list type="bullet"&gt; /// <%= openItemTag %>&lt;para&gt;Line1&lt;/para&gt;&lt;para&gt;Line2&lt;/para&gt;<%= closeItemTag %> /// <%= openItemTag %>Item 1.2<%= closeItemTag %> /// &lt;/list&gt; /// <%= closeItemTag %> /// <%= openItemTag %> /// &lt;list type="number"&gt; /// <%= openItemTag %>Item 2.1<%= closeItemTag %> /// <%= openItemTag %>&lt;para&gt;Line1&lt;/para&gt;&lt;para&gt;Line2&lt;/para&gt;<%= closeItemTag %> /// &lt;/list&gt; /// <%= closeItemTag %> /// &lt;/list&gt; /// &lt;/summary&gt; void MyMethod() { MyM$$ethod(); } } </Document> </Project> </Workspace> Dim intellisenseQuickInfo = Await GetQuickInfoItemAsync(workspace, LanguageNames.CSharp) Dim expected = New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ContainerElement( ContainerElementStyle.Stacked, New ContainerElement( ContainerElementStyle.Wrapped, New ImageElement(New ImageId(KnownImageIds.ImageCatalogGuid, KnownImageIds.MethodPrivate)), New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Keyword, "void"), New ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "), New ClassifiedTextRun(ClassificationTypeNames.ClassName, "MyClass", navigationAction:=Sub() Return, "MyClass"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "."), New ClassifiedTextRun(ClassificationTypeNames.MethodName, "MyMethod", navigationAction:=Sub() Return, "void MyClass.MyMethod()"), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, "("), New ClassifiedTextRun(ClassificationTypeNames.Punctuation, ")"))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "1. ")), New ContainerElement( ContainerElementStyle.Stacked, New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "• ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Line1")), New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Line2"))))), New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "• ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 1.2")))))))), New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "2. ")), New ContainerElement( ContainerElementStyle.Stacked, New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "1. ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Item 2.1")))), New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ContainerElement( ContainerElementStyle.Wrapped, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "2. ")), New ContainerElement( ContainerElementStyle.Stacked, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Line1")), New ContainerElement( ContainerElementStyle.Stacked Or ContainerElementStyle.VerticalPadding, New ClassifiedTextElement( New ClassifiedTextRun(ClassificationTypeNames.Text, "Line2"))))))))) ToolTipAssert.EqualContent(expected, intellisenseQuickInfo.Item) End Function End Class End Namespace
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceVariableService.State_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. #nullable disable using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; namespace Microsoft.CodeAnalysis.IntroduceVariable { internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax, TNameSyntax> { private partial class State { private bool IsInParameterContext( CancellationToken cancellationToken) { if (!_service.IsInParameterInitializer(Expression)) { return false; } // The default value for a parameter is a constant. So we always allow it unless it // happens to capture one of the method's type parameters. var bindingMap = GetSemanticMap(cancellationToken); if (bindingMap.AllReferencedSymbols.OfType<ITypeParameterSymbol>() .Where(tp => tp.TypeParameterKind == TypeParameterKind.Method) .Any()) { return false; } return 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.Linq; using System.Threading; using Microsoft.CodeAnalysis; namespace Microsoft.CodeAnalysis.IntroduceVariable { internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax, TNameSyntax> { private partial class State { private bool IsInParameterContext( CancellationToken cancellationToken) { if (!_service.IsInParameterInitializer(Expression)) { return false; } // The default value for a parameter is a constant. So we always allow it unless it // happens to capture one of the method's type parameters. var bindingMap = GetSemanticMap(cancellationToken); if (bindingMap.AllReferencedSymbols.OfType<ITypeParameterSymbol>() .Where(tp => tp.TypeParameterKind == TypeParameterKind.Method) .Any()) { return false; } return true; } } } }
-1
dotnet/roslyn
56,416
Do not include function type conversions in user-defined conversions
Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
cston
"2021-09-15T18:16:38Z"
"2021-09-24T23:24:46Z"
bb99d0bc89bde01650d2a694d720d600dd952dcb
3913f352cf066fa485869d866e4753fa721cbe93
Do not include function type conversions in user-defined conversions. Removes "function type conversions" from the set of "standard conversions" so that function type conversions (from the inferred type of a lambda expression or method group to `Delegate`, `Expression` or a base type) are not considered for user-defined conversions. Fixes #56407 Relates to test plan #52192
./src/Features/Core/Portable/ExternalAccess/VSTypeScript/Api/IVSTypeScriptDiagnosticAnalyzerImplementation.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 IVSTypeScriptDiagnosticAnalyzerImplementation { Task<ImmutableArray<Diagnostic>> AnalyzeProjectAsync(Project project, CancellationToken cancellationToken); Task<ImmutableArray<Diagnostic>> AnalyzeDocumentSyntaxAsync(Document document, CancellationToken cancellationToken); Task<ImmutableArray<Diagnostic>> AnalyzeDocumentSemanticsAsync(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 IVSTypeScriptDiagnosticAnalyzerImplementation { Task<ImmutableArray<Diagnostic>> AnalyzeProjectAsync(Project project, CancellationToken cancellationToken); Task<ImmutableArray<Diagnostic>> AnalyzeDocumentSyntaxAsync(Document document, CancellationToken cancellationToken); Task<ImmutableArray<Diagnostic>> AnalyzeDocumentSemanticsAsync(Document document, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/Declarations/DeclarationTreeBuilder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using CoreInternalSyntax = Microsoft.CodeAnalysis.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class DeclarationTreeBuilder : CSharpSyntaxVisitor<SingleNamespaceOrTypeDeclaration> { private readonly SyntaxTree _syntaxTree; private readonly string _scriptClassName; private readonly bool _isSubmission; private DeclarationTreeBuilder(SyntaxTree syntaxTree, string scriptClassName, bool isSubmission) { _syntaxTree = syntaxTree; _scriptClassName = scriptClassName; _isSubmission = isSubmission; } public static RootSingleNamespaceDeclaration ForTree( SyntaxTree syntaxTree, string scriptClassName, bool isSubmission) { var builder = new DeclarationTreeBuilder(syntaxTree, scriptClassName, isSubmission); return (RootSingleNamespaceDeclaration)builder.Visit(syntaxTree.GetRoot()); } private ImmutableArray<SingleNamespaceOrTypeDeclaration> VisitNamespaceChildren( CSharpSyntaxNode node, SyntaxList<MemberDeclarationSyntax> members, CoreInternalSyntax.SyntaxList<Syntax.InternalSyntax.MemberDeclarationSyntax> internalMembers) { Debug.Assert( node.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration || (node.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind == SourceCodeKind.Regular)); if (members.Count == 0) { return ImmutableArray<SingleNamespaceOrTypeDeclaration>.Empty; } // We look for members that are not allowed in a namespace. // If there are any we create an implicit class to wrap them. bool hasGlobalMembers = false; bool acceptSimpleProgram = node.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind == SourceCodeKind.Regular; bool hasAwaitExpressions = false; bool isIterator = false; bool hasReturnWithExpression = false; GlobalStatementSyntax firstGlobalStatement = null; bool hasNonEmptyGlobalStatement = false; var childrenBuilder = ArrayBuilder<SingleNamespaceOrTypeDeclaration>.GetInstance(); foreach (var member in members) { SingleNamespaceOrTypeDeclaration namespaceOrType = Visit(member); if (namespaceOrType != null) { childrenBuilder.Add(namespaceOrType); } else if (acceptSimpleProgram && member.IsKind(SyntaxKind.GlobalStatement)) { var global = (GlobalStatementSyntax)member; firstGlobalStatement ??= global; var topLevelStatement = global.Statement; if (!topLevelStatement.IsKind(SyntaxKind.EmptyStatement)) { hasNonEmptyGlobalStatement = true; } if (!hasAwaitExpressions) { hasAwaitExpressions = SyntaxFacts.HasAwaitOperations(topLevelStatement); } if (!isIterator) { isIterator = SyntaxFacts.HasYieldOperations(topLevelStatement); } if (!hasReturnWithExpression) { hasReturnWithExpression = SyntaxFacts.HasReturnWithExpression(topLevelStatement); } } else if (!hasGlobalMembers && member.Kind() != SyntaxKind.IncompleteMember) { hasGlobalMembers = true; } } // wrap all global statements in a compilation unit into a simple program type: if (firstGlobalStatement is object) { var diagnostics = ImmutableArray<Diagnostic>.Empty; if (!hasNonEmptyGlobalStatement) { var bag = DiagnosticBag.GetInstance(); bag.Add(ErrorCode.ERR_SimpleProgramIsEmpty, ((EmptyStatementSyntax)firstGlobalStatement.Statement).SemicolonToken.GetLocation()); diagnostics = bag.ToReadOnlyAndFree(); } childrenBuilder.Add(CreateSimpleProgram(firstGlobalStatement, hasAwaitExpressions, isIterator, hasReturnWithExpression, diagnostics)); } // wrap all members that are defined in a namespace or compilation unit into an implicit type: if (hasGlobalMembers) { //The implicit class is not static and has no extensions SingleTypeDeclaration.TypeDeclarationFlags declFlags = SingleTypeDeclaration.TypeDeclarationFlags.None; var memberNames = GetNonTypeMemberNames(internalMembers, ref declFlags, skipGlobalStatements: acceptSimpleProgram); var container = _syntaxTree.GetReference(node); childrenBuilder.Add(CreateImplicitClass(memberNames, container, declFlags)); } return childrenBuilder.ToImmutableAndFree(); } private static SingleNamespaceOrTypeDeclaration CreateImplicitClass(ImmutableSegmentedDictionary<string, VoidResult> memberNames, SyntaxReference container, SingleTypeDeclaration.TypeDeclarationFlags declFlags) { return new SingleTypeDeclaration( kind: DeclarationKind.ImplicitClass, name: TypeSymbol.ImplicitTypeName, arity: 0, modifiers: DeclarationModifiers.Internal | DeclarationModifiers.Partial | DeclarationModifiers.Sealed, declFlags: declFlags, syntaxReference: container, nameLocation: new SourceLocation(container), memberNames: memberNames, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: ImmutableArray<Diagnostic>.Empty); } private static SingleNamespaceOrTypeDeclaration CreateSimpleProgram(GlobalStatementSyntax firstGlobalStatement, bool hasAwaitExpressions, bool isIterator, bool hasReturnWithExpression, ImmutableArray<Diagnostic> diagnostics) { return new SingleTypeDeclaration( kind: DeclarationKind.Class, name: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, arity: 0, modifiers: DeclarationModifiers.Partial, declFlags: (hasAwaitExpressions ? SingleTypeDeclaration.TypeDeclarationFlags.HasAwaitExpressions : SingleTypeDeclaration.TypeDeclarationFlags.None) | (isIterator ? SingleTypeDeclaration.TypeDeclarationFlags.IsIterator : SingleTypeDeclaration.TypeDeclarationFlags.None) | (hasReturnWithExpression ? SingleTypeDeclaration.TypeDeclarationFlags.HasReturnWithExpression : SingleTypeDeclaration.TypeDeclarationFlags.None) | SingleTypeDeclaration.TypeDeclarationFlags.IsSimpleProgram, syntaxReference: firstGlobalStatement.SyntaxTree.GetReference(firstGlobalStatement.Parent), nameLocation: new SourceLocation(firstGlobalStatement.GetFirstToken()), memberNames: ImmutableSegmentedDictionary<string, VoidResult>.Empty, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics); } /// <summary> /// Creates a root declaration that contains a Script class declaration (possibly in a namespace) and namespace declarations. /// Top-level declarations in script code are nested in Script class. /// </summary> private RootSingleNamespaceDeclaration CreateScriptRootDeclaration(CompilationUnitSyntax compilationUnit) { Debug.Assert(_syntaxTree.Options.Kind != SourceCodeKind.Regular); var members = compilationUnit.Members; var rootChildren = ArrayBuilder<SingleNamespaceOrTypeDeclaration>.GetInstance(); var scriptChildren = ArrayBuilder<SingleTypeDeclaration>.GetInstance(); foreach (var member in members) { var decl = Visit(member); if (decl != null) { // Although namespaces are not allowed in script code process them // here as if they were to improve error reporting. if (decl.Kind == DeclarationKind.Namespace) { rootChildren.Add(decl); } else { scriptChildren.Add((SingleTypeDeclaration)decl); } } } //Script class is not static and contains no extensions. SingleTypeDeclaration.TypeDeclarationFlags declFlags = SingleTypeDeclaration.TypeDeclarationFlags.None; var membernames = GetNonTypeMemberNames(((Syntax.InternalSyntax.CompilationUnitSyntax)(compilationUnit.Green)).Members, ref declFlags); rootChildren.Add( CreateScriptClass( compilationUnit, scriptChildren.ToImmutableAndFree(), membernames, declFlags)); return CreateRootSingleNamespaceDeclaration(compilationUnit, rootChildren.ToImmutableAndFree(), isForScript: true); } private static ImmutableArray<ReferenceDirective> GetReferenceDirectives(CompilationUnitSyntax compilationUnit) { IList<ReferenceDirectiveTriviaSyntax> directiveNodes = compilationUnit.GetReferenceDirectives( d => !d.File.ContainsDiagnostics && !string.IsNullOrEmpty(d.File.ValueText)); if (directiveNodes.Count == 0) { return ImmutableArray<ReferenceDirective>.Empty; } var directives = ArrayBuilder<ReferenceDirective>.GetInstance(directiveNodes.Count); foreach (var directiveNode in directiveNodes) { directives.Add(new ReferenceDirective(directiveNode.File.ValueText, new SourceLocation(directiveNode))); } return directives.ToImmutableAndFree(); } private SingleNamespaceOrTypeDeclaration CreateScriptClass( CompilationUnitSyntax parent, ImmutableArray<SingleTypeDeclaration> children, ImmutableSegmentedDictionary<string, VoidResult> memberNames, SingleTypeDeclaration.TypeDeclarationFlags declFlags) { Debug.Assert(parent.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind != SourceCodeKind.Regular); // script type is represented by the parent node: var parentReference = _syntaxTree.GetReference(parent); var fullName = _scriptClassName.Split('.'); // Note: The symbol representing the merged declarations uses parentReference to enumerate non-type members. SingleNamespaceOrTypeDeclaration decl = new SingleTypeDeclaration( kind: _isSubmission ? DeclarationKind.Submission : DeclarationKind.Script, name: fullName.Last(), arity: 0, modifiers: DeclarationModifiers.Internal | DeclarationModifiers.Partial | DeclarationModifiers.Sealed, declFlags: declFlags, syntaxReference: parentReference, nameLocation: new SourceLocation(parentReference), memberNames: memberNames, children: children, diagnostics: ImmutableArray<Diagnostic>.Empty); for (int i = fullName.Length - 2; i >= 0; i--) { decl = SingleNamespaceDeclaration.Create( name: fullName[i], hasUsings: false, hasExternAliases: false, syntaxReference: parentReference, nameLocation: new SourceLocation(parentReference), children: ImmutableArray.Create(decl), diagnostics: ImmutableArray<Diagnostic>.Empty); } return decl; } public override SingleNamespaceOrTypeDeclaration VisitCompilationUnit(CompilationUnitSyntax compilationUnit) { if (_syntaxTree.Options.Kind != SourceCodeKind.Regular) { return CreateScriptRootDeclaration(compilationUnit); } var children = VisitNamespaceChildren(compilationUnit, compilationUnit.Members, ((Syntax.InternalSyntax.CompilationUnitSyntax)(compilationUnit.Green)).Members); return CreateRootSingleNamespaceDeclaration(compilationUnit, children, isForScript: false); } private RootSingleNamespaceDeclaration CreateRootSingleNamespaceDeclaration(CompilationUnitSyntax compilationUnit, ImmutableArray<SingleNamespaceOrTypeDeclaration> children, bool isForScript) { bool hasUsings = false; bool hasGlobalUsings = false; bool reportedGlobalUsingOutOfOrder = false; var diagnostics = DiagnosticBag.GetInstance(); foreach (var directive in compilationUnit.Usings) { if (directive.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) { hasGlobalUsings = true; if (hasUsings && !reportedGlobalUsingOutOfOrder) { reportedGlobalUsingOutOfOrder = true; diagnostics.Add(ErrorCode.ERR_GlobalUsingOutOfOrder, directive.GlobalKeyword.GetLocation()); } } else { hasUsings = true; } } return new RootSingleNamespaceDeclaration( hasGlobalUsings: hasGlobalUsings, hasUsings: hasUsings, hasExternAliases: compilationUnit.Externs.Any(), treeNode: _syntaxTree.GetReference(compilationUnit), children: children, referenceDirectives: isForScript ? GetReferenceDirectives(compilationUnit) : ImmutableArray<ReferenceDirective>.Empty, hasAssemblyAttributes: compilationUnit.AttributeLists.Any(), diagnostics: diagnostics.ToReadOnlyAndFree()); } public override SingleNamespaceOrTypeDeclaration VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) => this.VisitBaseNamespaceDeclaration(node); public override SingleNamespaceOrTypeDeclaration VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) => this.VisitBaseNamespaceDeclaration(node); private SingleNamespaceDeclaration VisitBaseNamespaceDeclaration(BaseNamespaceDeclarationSyntax node) { var children = VisitNamespaceChildren(node, node.Members, ((Syntax.InternalSyntax.BaseNamespaceDeclarationSyntax)node.Green).Members); bool hasUsings = node.Usings.Any(); bool hasExterns = node.Externs.Any(); NameSyntax name = node.Name; CSharpSyntaxNode currentNode = node; QualifiedNameSyntax dotted; while ((dotted = name as QualifiedNameSyntax) != null) { var ns = SingleNamespaceDeclaration.Create( name: dotted.Right.Identifier.ValueText, hasUsings: hasUsings, hasExternAliases: hasExterns, syntaxReference: _syntaxTree.GetReference(currentNode), nameLocation: new SourceLocation(dotted.Right), children: children, diagnostics: ImmutableArray<Diagnostic>.Empty); var nsDeclaration = new[] { ns }; children = nsDeclaration.AsImmutableOrNull<SingleNamespaceOrTypeDeclaration>(); currentNode = name = dotted.Left; hasUsings = false; hasExterns = false; } var diagnostics = DiagnosticBag.GetInstance(); if (node is FileScopedNamespaceDeclarationSyntax) { if (node.Parent is FileScopedNamespaceDeclarationSyntax) { // Happens when user writes: // namespace A.B; // namespace X.Y; diagnostics.Add(ErrorCode.ERR_MultipleFileScopedNamespace, node.Name.GetLocation()); } else if (node.Parent is NamespaceDeclarationSyntax) { // Happens with: // // namespace A.B // { // namespace X.Y; diagnostics.Add(ErrorCode.ERR_FileScopedAndNormalNamespace, node.Name.GetLocation()); } else { // Happens with cases like: // // namespace A.B { } // namespace X.Y; // // or even // // class C { } // namespace X.Y; Debug.Assert(node.Parent is CompilationUnitSyntax); var compilationUnit = (CompilationUnitSyntax)node.Parent; if (node != compilationUnit.Members[0]) { diagnostics.Add(ErrorCode.ERR_FileScopedNamespaceNotBeforeAllMembers, node.Name.GetLocation()); } } } else { Debug.Assert(node is NamespaceDeclarationSyntax); // namespace X.Y; // namespace A.B { } if (node.Parent is FileScopedNamespaceDeclarationSyntax) { diagnostics.Add(ErrorCode.ERR_FileScopedAndNormalNamespace, node.Name.GetLocation()); } } if (ContainsGeneric(node.Name)) { // We're not allowed to have generics. diagnostics.Add(ErrorCode.ERR_UnexpectedGenericName, node.Name.GetLocation()); } if (ContainsAlias(node.Name)) { diagnostics.Add(ErrorCode.ERR_UnexpectedAliasedName, node.Name.GetLocation()); } if (node.AttributeLists.Count > 0) { diagnostics.Add(ErrorCode.ERR_BadModifiersOnNamespace, node.AttributeLists[0].GetLocation()); } if (node.Modifiers.Count > 0) { diagnostics.Add(ErrorCode.ERR_BadModifiersOnNamespace, node.Modifiers[0].GetLocation()); } foreach (var directive in node.Usings) { if (directive.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) { diagnostics.Add(ErrorCode.ERR_GlobalUsingInNamespace, directive.GlobalKeyword.GetLocation()); break; } } // NOTE: *Something* has to happen for alias-qualified names. It turns out that we // just grab the part after the colons (via GetUnqualifiedName, below). This logic // must be kept in sync with NamespaceSymbol.GetNestedNamespace. return SingleNamespaceDeclaration.Create( name: name.GetUnqualifiedName().Identifier.ValueText, hasUsings: hasUsings, hasExternAliases: hasExterns, syntaxReference: _syntaxTree.GetReference(currentNode), nameLocation: new SourceLocation(name), children: children, diagnostics: diagnostics.ToReadOnlyAndFree()); } private static bool ContainsAlias(NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: return false; case SyntaxKind.AliasQualifiedName: return true; case SyntaxKind.QualifiedName: var qualifiedName = (QualifiedNameSyntax)name; return ContainsAlias(qualifiedName.Left); } return false; } private static bool ContainsGeneric(NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: return true; case SyntaxKind.AliasQualifiedName: return ContainsGeneric(((AliasQualifiedNameSyntax)name).Name); case SyntaxKind.QualifiedName: var qualifiedName = (QualifiedNameSyntax)name; return ContainsGeneric(qualifiedName.Left) || ContainsGeneric(qualifiedName.Right); } return false; } public override SingleNamespaceOrTypeDeclaration VisitClassDeclaration(ClassDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Class); } public override SingleNamespaceOrTypeDeclaration VisitStructDeclaration(StructDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Struct); } public override SingleNamespaceOrTypeDeclaration VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Interface); } public override SingleNamespaceOrTypeDeclaration VisitRecordDeclaration(RecordDeclarationSyntax node) { var declarationKind = node.Kind() switch { SyntaxKind.RecordDeclaration => DeclarationKind.Record, SyntaxKind.RecordStructDeclaration => DeclarationKind.RecordStruct, _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()) }; return VisitTypeDeclaration(node, declarationKind); } private SingleNamespaceOrTypeDeclaration VisitTypeDeclaration(TypeDeclarationSyntax node, DeclarationKind kind) { SingleTypeDeclaration.TypeDeclarationFlags declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; if (node.BaseList != null) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations; } var diagnostics = DiagnosticBag.GetInstance(); if (node.Arity == 0) { Symbol.ReportErrorIfHasConstraints(node.ConstraintClauses, diagnostics); } var memberNames = GetNonTypeMemberNames(((Syntax.InternalSyntax.TypeDeclarationSyntax)(node.Green)).Members, ref declFlags); // A record with parameters at least has a primary constructor if (((declFlags & SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers) == 0) && node is RecordDeclarationSyntax { ParameterList: { } }) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); return new SingleTypeDeclaration( kind: kind, name: node.Identifier.ValueText, modifiers: modifiers, arity: node.Arity, declFlags: declFlags, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: memberNames, children: VisitTypeChildren(node), diagnostics: diagnostics.ToReadOnlyAndFree()); } private ImmutableArray<SingleTypeDeclaration> VisitTypeChildren(TypeDeclarationSyntax node) { if (node.Members.Count == 0) { return ImmutableArray<SingleTypeDeclaration>.Empty; } var children = ArrayBuilder<SingleTypeDeclaration>.GetInstance(); foreach (var member in node.Members) { var typeDecl = Visit(member) as SingleTypeDeclaration; if (typeDecl != null) { children.Add(typeDecl); } } return children.ToImmutableAndFree(); } public override SingleNamespaceOrTypeDeclaration VisitDelegateDeclaration(DelegateDeclarationSyntax node) { var declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; var diagnostics = DiagnosticBag.GetInstance(); if (node.Arity == 0) { Symbol.ReportErrorIfHasConstraints(node.ConstraintClauses, diagnostics); } declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); return new SingleTypeDeclaration( kind: DeclarationKind.Delegate, name: node.Identifier.ValueText, modifiers: modifiers, declFlags: declFlags, arity: node.Arity, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: ImmutableSegmentedDictionary<string, VoidResult>.Empty, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics.ToReadOnlyAndFree()); } public override SingleNamespaceOrTypeDeclaration VisitEnumDeclaration(EnumDeclarationSyntax node) { var members = node.Members; SingleTypeDeclaration.TypeDeclarationFlags declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; if (node.BaseList != null) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations; } ImmutableSegmentedDictionary<string, VoidResult> memberNames = GetEnumMemberNames(members, ref declFlags); var diagnostics = DiagnosticBag.GetInstance(); var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); return new SingleTypeDeclaration( kind: DeclarationKind.Enum, name: node.Identifier.ValueText, arity: 0, modifiers: modifiers, declFlags: declFlags, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: memberNames, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics.ToReadOnlyAndFree()); } private static readonly ObjectPool<ImmutableSegmentedDictionary<string, VoidResult>.Builder> s_memberNameBuilderPool = new ObjectPool<ImmutableSegmentedDictionary<string, VoidResult>.Builder>(() => ImmutableSegmentedDictionary.CreateBuilder<string, VoidResult>()); private static ImmutableSegmentedDictionary<string, VoidResult> ToImmutableAndFree(ImmutableSegmentedDictionary<string, VoidResult>.Builder builder) { var result = builder.ToImmutable(); builder.Clear(); s_memberNameBuilderPool.Free(builder); return result; } private static ImmutableSegmentedDictionary<string, VoidResult> GetEnumMemberNames(SeparatedSyntaxList<EnumMemberDeclarationSyntax> members, ref SingleTypeDeclaration.TypeDeclarationFlags declFlags) { var cnt = members.Count; var memberNamesBuilder = s_memberNameBuilderPool.Allocate(); if (cnt != 0) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } bool anyMemberHasAttributes = false; foreach (var member in members) { memberNamesBuilder.TryAdd(member.Identifier.ValueText); if (!anyMemberHasAttributes && member.AttributeLists.Any()) { anyMemberHasAttributes = true; } } if (anyMemberHasAttributes) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes; } return ToImmutableAndFree(memberNamesBuilder); } private static ImmutableSegmentedDictionary<string, VoidResult> GetNonTypeMemberNames( CoreInternalSyntax.SyntaxList<Syntax.InternalSyntax.MemberDeclarationSyntax> members, ref SingleTypeDeclaration.TypeDeclarationFlags declFlags, bool skipGlobalStatements = false) { bool anyMethodHadExtensionSyntax = false; bool anyMemberHasAttributes = false; bool anyNonTypeMembers = false; var memberNameBuilder = s_memberNameBuilderPool.Allocate(); foreach (var member in members) { AddNonTypeMemberNames(member, memberNameBuilder, ref anyNonTypeMembers, skipGlobalStatements); // Check to see if any method contains a 'this' modifier on its first parameter. // This data is used to determine if a type needs to have its members materialized // as part of extension method lookup. if (!anyMethodHadExtensionSyntax && CheckMethodMemberForExtensionSyntax(member)) { anyMethodHadExtensionSyntax = true; } if (!anyMemberHasAttributes && CheckMemberForAttributes(member)) { anyMemberHasAttributes = true; } } if (anyMethodHadExtensionSyntax) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasExtensionMethodSyntax; } if (anyMemberHasAttributes) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes; } if (anyNonTypeMembers) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } return ToImmutableAndFree(memberNameBuilder); } private static bool CheckMethodMemberForExtensionSyntax(Syntax.InternalSyntax.CSharpSyntaxNode member) { if (member.Kind == SyntaxKind.MethodDeclaration) { var methodDecl = (Syntax.InternalSyntax.MethodDeclarationSyntax)member; var paramList = methodDecl.parameterList; if (paramList != null) { var parameters = paramList.Parameters; if (parameters.Count != 0) { var firstParameter = parameters[0]; foreach (var modifier in firstParameter.Modifiers) { if (modifier.Kind == SyntaxKind.ThisKeyword) { return true; } } } } } return false; } private static bool CheckMemberForAttributes(Syntax.InternalSyntax.CSharpSyntaxNode member) { switch (member.Kind) { case SyntaxKind.CompilationUnit: return (((Syntax.InternalSyntax.CompilationUnitSyntax)member).AttributeLists).Any(); case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return (((Syntax.InternalSyntax.BaseTypeDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.DelegateDeclaration: return (((Syntax.InternalSyntax.DelegateDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: return (((Syntax.InternalSyntax.BaseFieldDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return (((Syntax.InternalSyntax.BaseMethodDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.PropertyDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: var baseProp = (Syntax.InternalSyntax.BasePropertyDeclarationSyntax)member; bool hasAttributes = baseProp.AttributeLists.Any(); if (!hasAttributes && baseProp.AccessorList != null) { foreach (var accessor in baseProp.AccessorList.Accessors) { hasAttributes |= accessor.AttributeLists.Any(); } } return hasAttributes; } return false; } private static void AddNonTypeMemberNames( Syntax.InternalSyntax.CSharpSyntaxNode member, ImmutableSegmentedDictionary<string, VoidResult>.Builder set, ref bool anyNonTypeMembers, bool skipGlobalStatements) { switch (member.Kind) { case SyntaxKind.FieldDeclaration: anyNonTypeMembers = true; CodeAnalysis.Syntax.InternalSyntax.SeparatedSyntaxList<Syntax.InternalSyntax.VariableDeclaratorSyntax> fieldDeclarators = ((Syntax.InternalSyntax.FieldDeclarationSyntax)member).Declaration.Variables; int numFieldDeclarators = fieldDeclarators.Count; for (int i = 0; i < numFieldDeclarators; i++) { set.TryAdd(fieldDeclarators[i].Identifier.ValueText); } break; case SyntaxKind.EventFieldDeclaration: anyNonTypeMembers = true; CoreInternalSyntax.SeparatedSyntaxList<Syntax.InternalSyntax.VariableDeclaratorSyntax> eventDeclarators = ((Syntax.InternalSyntax.EventFieldDeclarationSyntax)member).Declaration.Variables; int numEventDeclarators = eventDeclarators.Count; for (int i = 0; i < numEventDeclarators; i++) { set.TryAdd(eventDeclarators[i].Identifier.ValueText); } break; case SyntaxKind.MethodDeclaration: anyNonTypeMembers = true; // Member names are exposed via NamedTypeSymbol.MemberNames and are used primarily // as an acid test to determine whether a more in-depth search of a type is worthwhile. // We decided that it was reasonable to exclude explicit interface implementations // from the list of member names. var methodDecl = (Syntax.InternalSyntax.MethodDeclarationSyntax)member; if (methodDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(methodDecl.Identifier.ValueText); } break; case SyntaxKind.PropertyDeclaration: anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var propertyDecl = (Syntax.InternalSyntax.PropertyDeclarationSyntax)member; if (propertyDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(propertyDecl.Identifier.ValueText); } break; case SyntaxKind.EventDeclaration: anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var eventDecl = (Syntax.InternalSyntax.EventDeclarationSyntax)member; if (eventDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(eventDecl.Identifier.ValueText); } break; case SyntaxKind.ConstructorDeclaration: anyNonTypeMembers = true; set.TryAdd(((Syntax.InternalSyntax.ConstructorDeclarationSyntax)member).Modifiers.Any((int)SyntaxKind.StaticKeyword) ? WellKnownMemberNames.StaticConstructorName : WellKnownMemberNames.InstanceConstructorName); break; case SyntaxKind.DestructorDeclaration: anyNonTypeMembers = true; set.TryAdd(WellKnownMemberNames.DestructorName); break; case SyntaxKind.IndexerDeclaration: anyNonTypeMembers = true; set.TryAdd(WellKnownMemberNames.Indexer); break; case SyntaxKind.OperatorDeclaration: { anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var opDecl = (Syntax.InternalSyntax.OperatorDeclarationSyntax)member; if (opDecl.ExplicitInterfaceSpecifier == null) { var name = OperatorFacts.OperatorNameFromDeclaration(opDecl); set.TryAdd(name); } } break; case SyntaxKind.ConversionOperatorDeclaration: { anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var opDecl = (Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)member; if (opDecl.ExplicitInterfaceSpecifier == null) { var name = OperatorFacts.OperatorNameFromDeclaration(opDecl); set.TryAdd(name); } } break; case SyntaxKind.GlobalStatement: if (!skipGlobalStatements) { anyNonTypeMembers = true; } break; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; using CoreInternalSyntax = Microsoft.CodeAnalysis.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class DeclarationTreeBuilder : CSharpSyntaxVisitor<SingleNamespaceOrTypeDeclaration> { private readonly SyntaxTree _syntaxTree; private readonly string _scriptClassName; private readonly bool _isSubmission; /// <summary> /// Any special attributes we may be referencing through a using alias in the file. /// For example <c>using X = System.Runtime.CompilerServices.TypeForwardedToAttribute</c>. /// </summary> private QuickAttributes _nonGlobalAliasedQuickAttributes; private DeclarationTreeBuilder(SyntaxTree syntaxTree, string scriptClassName, bool isSubmission) { _syntaxTree = syntaxTree; _scriptClassName = scriptClassName; _isSubmission = isSubmission; } public static RootSingleNamespaceDeclaration ForTree( SyntaxTree syntaxTree, string scriptClassName, bool isSubmission) { var builder = new DeclarationTreeBuilder(syntaxTree, scriptClassName, isSubmission); return (RootSingleNamespaceDeclaration)builder.Visit(syntaxTree.GetRoot()); } private ImmutableArray<SingleNamespaceOrTypeDeclaration> VisitNamespaceChildren( CSharpSyntaxNode node, SyntaxList<MemberDeclarationSyntax> members, CoreInternalSyntax.SyntaxList<Syntax.InternalSyntax.MemberDeclarationSyntax> internalMembers) { Debug.Assert( node.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration || (node.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind == SourceCodeKind.Regular)); if (members.Count == 0) { return ImmutableArray<SingleNamespaceOrTypeDeclaration>.Empty; } // We look for members that are not allowed in a namespace. // If there are any we create an implicit class to wrap them. bool hasGlobalMembers = false; bool acceptSimpleProgram = node.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind == SourceCodeKind.Regular; bool hasAwaitExpressions = false; bool isIterator = false; bool hasReturnWithExpression = false; GlobalStatementSyntax firstGlobalStatement = null; bool hasNonEmptyGlobalStatement = false; var childrenBuilder = ArrayBuilder<SingleNamespaceOrTypeDeclaration>.GetInstance(); foreach (var member in members) { SingleNamespaceOrTypeDeclaration namespaceOrType = Visit(member); if (namespaceOrType != null) { childrenBuilder.Add(namespaceOrType); } else if (acceptSimpleProgram && member.IsKind(SyntaxKind.GlobalStatement)) { var global = (GlobalStatementSyntax)member; firstGlobalStatement ??= global; var topLevelStatement = global.Statement; if (!topLevelStatement.IsKind(SyntaxKind.EmptyStatement)) { hasNonEmptyGlobalStatement = true; } if (!hasAwaitExpressions) { hasAwaitExpressions = SyntaxFacts.HasAwaitOperations(topLevelStatement); } if (!isIterator) { isIterator = SyntaxFacts.HasYieldOperations(topLevelStatement); } if (!hasReturnWithExpression) { hasReturnWithExpression = SyntaxFacts.HasReturnWithExpression(topLevelStatement); } } else if (!hasGlobalMembers && member.Kind() != SyntaxKind.IncompleteMember) { hasGlobalMembers = true; } } // wrap all global statements in a compilation unit into a simple program type: if (firstGlobalStatement is object) { var diagnostics = ImmutableArray<Diagnostic>.Empty; if (!hasNonEmptyGlobalStatement) { var bag = DiagnosticBag.GetInstance(); bag.Add(ErrorCode.ERR_SimpleProgramIsEmpty, ((EmptyStatementSyntax)firstGlobalStatement.Statement).SemicolonToken.GetLocation()); diagnostics = bag.ToReadOnlyAndFree(); } childrenBuilder.Add(CreateSimpleProgram(firstGlobalStatement, hasAwaitExpressions, isIterator, hasReturnWithExpression, diagnostics)); } // wrap all members that are defined in a namespace or compilation unit into an implicit type: if (hasGlobalMembers) { //The implicit class is not static and has no extensions SingleTypeDeclaration.TypeDeclarationFlags declFlags = SingleTypeDeclaration.TypeDeclarationFlags.None; var memberNames = GetNonTypeMemberNames(internalMembers, ref declFlags, skipGlobalStatements: acceptSimpleProgram); var container = _syntaxTree.GetReference(node); childrenBuilder.Add(CreateImplicitClass(memberNames, container, declFlags)); } return childrenBuilder.ToImmutableAndFree(); } private static SingleNamespaceOrTypeDeclaration CreateImplicitClass(ImmutableSegmentedDictionary<string, VoidResult> memberNames, SyntaxReference container, SingleTypeDeclaration.TypeDeclarationFlags declFlags) { return new SingleTypeDeclaration( kind: DeclarationKind.ImplicitClass, name: TypeSymbol.ImplicitTypeName, arity: 0, modifiers: DeclarationModifiers.Internal | DeclarationModifiers.Partial | DeclarationModifiers.Sealed, declFlags: declFlags, syntaxReference: container, nameLocation: new SourceLocation(container), memberNames: memberNames, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: ImmutableArray<Diagnostic>.Empty, quickAttributes: QuickAttributes.None); } private static SingleNamespaceOrTypeDeclaration CreateSimpleProgram(GlobalStatementSyntax firstGlobalStatement, bool hasAwaitExpressions, bool isIterator, bool hasReturnWithExpression, ImmutableArray<Diagnostic> diagnostics) { return new SingleTypeDeclaration( kind: DeclarationKind.Class, name: WellKnownMemberNames.TopLevelStatementsEntryPointTypeName, arity: 0, modifiers: DeclarationModifiers.Partial, declFlags: (hasAwaitExpressions ? SingleTypeDeclaration.TypeDeclarationFlags.HasAwaitExpressions : SingleTypeDeclaration.TypeDeclarationFlags.None) | (isIterator ? SingleTypeDeclaration.TypeDeclarationFlags.IsIterator : SingleTypeDeclaration.TypeDeclarationFlags.None) | (hasReturnWithExpression ? SingleTypeDeclaration.TypeDeclarationFlags.HasReturnWithExpression : SingleTypeDeclaration.TypeDeclarationFlags.None) | SingleTypeDeclaration.TypeDeclarationFlags.IsSimpleProgram, syntaxReference: firstGlobalStatement.SyntaxTree.GetReference(firstGlobalStatement.Parent), nameLocation: new SourceLocation(firstGlobalStatement.GetFirstToken()), memberNames: ImmutableSegmentedDictionary<string, VoidResult>.Empty, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics, quickAttributes: QuickAttributes.None); } /// <summary> /// Creates a root declaration that contains a Script class declaration (possibly in a namespace) and namespace declarations. /// Top-level declarations in script code are nested in Script class. /// </summary> private RootSingleNamespaceDeclaration CreateScriptRootDeclaration(CompilationUnitSyntax compilationUnit) { Debug.Assert(_syntaxTree.Options.Kind != SourceCodeKind.Regular); var members = compilationUnit.Members; var rootChildren = ArrayBuilder<SingleNamespaceOrTypeDeclaration>.GetInstance(); var scriptChildren = ArrayBuilder<SingleTypeDeclaration>.GetInstance(); foreach (var member in members) { var decl = Visit(member); if (decl != null) { // Although namespaces are not allowed in script code process them // here as if they were to improve error reporting. if (decl.Kind == DeclarationKind.Namespace) { rootChildren.Add(decl); } else { scriptChildren.Add((SingleTypeDeclaration)decl); } } } //Script class is not static and contains no extensions. SingleTypeDeclaration.TypeDeclarationFlags declFlags = SingleTypeDeclaration.TypeDeclarationFlags.None; var membernames = GetNonTypeMemberNames(((Syntax.InternalSyntax.CompilationUnitSyntax)(compilationUnit.Green)).Members, ref declFlags); rootChildren.Add( CreateScriptClass( compilationUnit, scriptChildren.ToImmutableAndFree(), membernames, declFlags)); return CreateRootSingleNamespaceDeclaration(compilationUnit, rootChildren.ToImmutableAndFree(), isForScript: true); } private static ImmutableArray<ReferenceDirective> GetReferenceDirectives(CompilationUnitSyntax compilationUnit) { IList<ReferenceDirectiveTriviaSyntax> directiveNodes = compilationUnit.GetReferenceDirectives( d => !d.File.ContainsDiagnostics && !string.IsNullOrEmpty(d.File.ValueText)); if (directiveNodes.Count == 0) { return ImmutableArray<ReferenceDirective>.Empty; } var directives = ArrayBuilder<ReferenceDirective>.GetInstance(directiveNodes.Count); foreach (var directiveNode in directiveNodes) { directives.Add(new ReferenceDirective(directiveNode.File.ValueText, new SourceLocation(directiveNode))); } return directives.ToImmutableAndFree(); } private SingleNamespaceOrTypeDeclaration CreateScriptClass( CompilationUnitSyntax parent, ImmutableArray<SingleTypeDeclaration> children, ImmutableSegmentedDictionary<string, VoidResult> memberNames, SingleTypeDeclaration.TypeDeclarationFlags declFlags) { Debug.Assert(parent.Kind() == SyntaxKind.CompilationUnit && _syntaxTree.Options.Kind != SourceCodeKind.Regular); // script type is represented by the parent node: var parentReference = _syntaxTree.GetReference(parent); var fullName = _scriptClassName.Split('.'); // Note: The symbol representing the merged declarations uses parentReference to enumerate non-type members. SingleNamespaceOrTypeDeclaration decl = new SingleTypeDeclaration( kind: _isSubmission ? DeclarationKind.Submission : DeclarationKind.Script, name: fullName.Last(), arity: 0, modifiers: DeclarationModifiers.Internal | DeclarationModifiers.Partial | DeclarationModifiers.Sealed, declFlags: declFlags, syntaxReference: parentReference, nameLocation: new SourceLocation(parentReference), memberNames: memberNames, children: children, diagnostics: ImmutableArray<Diagnostic>.Empty, quickAttributes: QuickAttributes.None); for (int i = fullName.Length - 2; i >= 0; i--) { decl = SingleNamespaceDeclaration.Create( name: fullName[i], hasUsings: false, hasExternAliases: false, syntaxReference: parentReference, nameLocation: new SourceLocation(parentReference), children: ImmutableArray.Create(decl), diagnostics: ImmutableArray<Diagnostic>.Empty); } return decl; } private static QuickAttributes GetQuickAttributes( SyntaxList<UsingDirectiveSyntax> usings, bool global) { var result = QuickAttributes.None; foreach (var directive in usings) { if (directive.Alias == null) { continue; } var isGlobal = directive.GlobalKeyword.Kind() != SyntaxKind.None; if (isGlobal != global) { continue; } result |= QuickAttributeHelpers.GetQuickAttributes(directive.Name.GetUnqualifiedName().Identifier.ValueText, inAttribute: false); } return result; } public override SingleNamespaceOrTypeDeclaration VisitCompilationUnit(CompilationUnitSyntax compilationUnit) { if (_syntaxTree.Options.Kind != SourceCodeKind.Regular) { return CreateScriptRootDeclaration(compilationUnit); } _nonGlobalAliasedQuickAttributes = GetNonGlobalAliasedQuickAttributes(compilationUnit); var children = VisitNamespaceChildren(compilationUnit, compilationUnit.Members, ((Syntax.InternalSyntax.CompilationUnitSyntax)(compilationUnit.Green)).Members); return CreateRootSingleNamespaceDeclaration(compilationUnit, children, isForScript: false); } private static QuickAttributes GetNonGlobalAliasedQuickAttributes(CompilationUnitSyntax compilationUnit) { var result = GetQuickAttributes(compilationUnit.Usings, global: false); foreach (var member in compilationUnit.Members) { if (member is BaseNamespaceDeclarationSyntax @namespace) { result |= GetNonGlobalAliasedQuickAttributes(@namespace); } } return result; } private static QuickAttributes GetNonGlobalAliasedQuickAttributes(BaseNamespaceDeclarationSyntax @namespace) { var result = GetQuickAttributes(@namespace.Usings, global: false); foreach (var member in @namespace.Members) { if (member is BaseNamespaceDeclarationSyntax child) { result |= GetNonGlobalAliasedQuickAttributes(child); } } return result; } private RootSingleNamespaceDeclaration CreateRootSingleNamespaceDeclaration(CompilationUnitSyntax compilationUnit, ImmutableArray<SingleNamespaceOrTypeDeclaration> children, bool isForScript) { bool hasUsings = false; bool hasGlobalUsings = false; bool reportedGlobalUsingOutOfOrder = false; var diagnostics = DiagnosticBag.GetInstance(); foreach (var directive in compilationUnit.Usings) { if (directive.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) { hasGlobalUsings = true; if (hasUsings && !reportedGlobalUsingOutOfOrder) { reportedGlobalUsingOutOfOrder = true; diagnostics.Add(ErrorCode.ERR_GlobalUsingOutOfOrder, directive.GlobalKeyword.GetLocation()); } } else { hasUsings = true; } } var globalAliasedQuickAttributes = GetQuickAttributes(compilationUnit.Usings, global: true); return new RootSingleNamespaceDeclaration( hasGlobalUsings: hasGlobalUsings, hasUsings: hasUsings, hasExternAliases: compilationUnit.Externs.Any(), treeNode: _syntaxTree.GetReference(compilationUnit), children: children, referenceDirectives: isForScript ? GetReferenceDirectives(compilationUnit) : ImmutableArray<ReferenceDirective>.Empty, hasAssemblyAttributes: compilationUnit.AttributeLists.Any(), diagnostics: diagnostics.ToReadOnlyAndFree(), globalAliasedQuickAttributes); } public override SingleNamespaceOrTypeDeclaration VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node) => this.VisitBaseNamespaceDeclaration(node); public override SingleNamespaceOrTypeDeclaration VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) => this.VisitBaseNamespaceDeclaration(node); private SingleNamespaceDeclaration VisitBaseNamespaceDeclaration(BaseNamespaceDeclarationSyntax node) { var children = VisitNamespaceChildren(node, node.Members, ((Syntax.InternalSyntax.BaseNamespaceDeclarationSyntax)node.Green).Members); bool hasUsings = node.Usings.Any(); bool hasExterns = node.Externs.Any(); NameSyntax name = node.Name; CSharpSyntaxNode currentNode = node; QualifiedNameSyntax dotted; while ((dotted = name as QualifiedNameSyntax) != null) { var ns = SingleNamespaceDeclaration.Create( name: dotted.Right.Identifier.ValueText, hasUsings: hasUsings, hasExternAliases: hasExterns, syntaxReference: _syntaxTree.GetReference(currentNode), nameLocation: new SourceLocation(dotted.Right), children: children, diagnostics: ImmutableArray<Diagnostic>.Empty); var nsDeclaration = new[] { ns }; children = nsDeclaration.AsImmutableOrNull<SingleNamespaceOrTypeDeclaration>(); currentNode = name = dotted.Left; hasUsings = false; hasExterns = false; } var diagnostics = DiagnosticBag.GetInstance(); if (node is FileScopedNamespaceDeclarationSyntax) { if (node.Parent is FileScopedNamespaceDeclarationSyntax) { // Happens when user writes: // namespace A.B; // namespace X.Y; diagnostics.Add(ErrorCode.ERR_MultipleFileScopedNamespace, node.Name.GetLocation()); } else if (node.Parent is NamespaceDeclarationSyntax) { // Happens with: // // namespace A.B // { // namespace X.Y; diagnostics.Add(ErrorCode.ERR_FileScopedAndNormalNamespace, node.Name.GetLocation()); } else { // Happens with cases like: // // namespace A.B { } // namespace X.Y; // // or even // // class C { } // namespace X.Y; Debug.Assert(node.Parent is CompilationUnitSyntax); var compilationUnit = (CompilationUnitSyntax)node.Parent; if (node != compilationUnit.Members[0]) { diagnostics.Add(ErrorCode.ERR_FileScopedNamespaceNotBeforeAllMembers, node.Name.GetLocation()); } } } else { Debug.Assert(node is NamespaceDeclarationSyntax); // namespace X.Y; // namespace A.B { } if (node.Parent is FileScopedNamespaceDeclarationSyntax) { diagnostics.Add(ErrorCode.ERR_FileScopedAndNormalNamespace, node.Name.GetLocation()); } } if (ContainsGeneric(node.Name)) { // We're not allowed to have generics. diagnostics.Add(ErrorCode.ERR_UnexpectedGenericName, node.Name.GetLocation()); } if (ContainsAlias(node.Name)) { diagnostics.Add(ErrorCode.ERR_UnexpectedAliasedName, node.Name.GetLocation()); } if (node.AttributeLists.Count > 0) { diagnostics.Add(ErrorCode.ERR_BadModifiersOnNamespace, node.AttributeLists[0].GetLocation()); } if (node.Modifiers.Count > 0) { diagnostics.Add(ErrorCode.ERR_BadModifiersOnNamespace, node.Modifiers[0].GetLocation()); } foreach (var directive in node.Usings) { if (directive.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword)) { diagnostics.Add(ErrorCode.ERR_GlobalUsingInNamespace, directive.GlobalKeyword.GetLocation()); break; } } // NOTE: *Something* has to happen for alias-qualified names. It turns out that we // just grab the part after the colons (via GetUnqualifiedName, below). This logic // must be kept in sync with NamespaceSymbol.GetNestedNamespace. return SingleNamespaceDeclaration.Create( name: name.GetUnqualifiedName().Identifier.ValueText, hasUsings: hasUsings, hasExternAliases: hasExterns, syntaxReference: _syntaxTree.GetReference(currentNode), nameLocation: new SourceLocation(name), children: children, diagnostics: diagnostics.ToReadOnlyAndFree()); } private static bool ContainsAlias(NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: return false; case SyntaxKind.AliasQualifiedName: return true; case SyntaxKind.QualifiedName: var qualifiedName = (QualifiedNameSyntax)name; return ContainsAlias(qualifiedName.Left); } return false; } private static bool ContainsGeneric(NameSyntax name) { switch (name.Kind()) { case SyntaxKind.GenericName: return true; case SyntaxKind.AliasQualifiedName: return ContainsGeneric(((AliasQualifiedNameSyntax)name).Name); case SyntaxKind.QualifiedName: var qualifiedName = (QualifiedNameSyntax)name; return ContainsGeneric(qualifiedName.Left) || ContainsGeneric(qualifiedName.Right); } return false; } public override SingleNamespaceOrTypeDeclaration VisitClassDeclaration(ClassDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Class); } public override SingleNamespaceOrTypeDeclaration VisitStructDeclaration(StructDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Struct); } public override SingleNamespaceOrTypeDeclaration VisitInterfaceDeclaration(InterfaceDeclarationSyntax node) { return VisitTypeDeclaration(node, DeclarationKind.Interface); } public override SingleNamespaceOrTypeDeclaration VisitRecordDeclaration(RecordDeclarationSyntax node) { var declarationKind = node.Kind() switch { SyntaxKind.RecordDeclaration => DeclarationKind.Record, SyntaxKind.RecordStructDeclaration => DeclarationKind.RecordStruct, _ => throw ExceptionUtilities.UnexpectedValue(node.Kind()) }; return VisitTypeDeclaration(node, declarationKind); } private SingleNamespaceOrTypeDeclaration VisitTypeDeclaration(TypeDeclarationSyntax node, DeclarationKind kind) { SingleTypeDeclaration.TypeDeclarationFlags declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; if (node.BaseList != null) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations; } var diagnostics = DiagnosticBag.GetInstance(); if (node.Arity == 0) { Symbol.ReportErrorIfHasConstraints(node.ConstraintClauses, diagnostics); } var memberNames = GetNonTypeMemberNames(((Syntax.InternalSyntax.TypeDeclarationSyntax)(node.Green)).Members, ref declFlags); // A record with parameters at least has a primary constructor if (((declFlags & SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers) == 0) && node is RecordDeclarationSyntax { ParameterList: { } }) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); var quickAttributes = DeclarationTreeBuilder.GetQuickAttributes(node.AttributeLists); return new SingleTypeDeclaration( kind: kind, name: node.Identifier.ValueText, arity: node.Arity, modifiers: modifiers, declFlags: declFlags, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: memberNames, children: VisitTypeChildren(node), diagnostics: diagnostics.ToReadOnlyAndFree(), _nonGlobalAliasedQuickAttributes | quickAttributes); } private ImmutableArray<SingleTypeDeclaration> VisitTypeChildren(TypeDeclarationSyntax node) { if (node.Members.Count == 0) { return ImmutableArray<SingleTypeDeclaration>.Empty; } var children = ArrayBuilder<SingleTypeDeclaration>.GetInstance(); foreach (var member in node.Members) { var typeDecl = Visit(member) as SingleTypeDeclaration; children.AddIfNotNull(typeDecl); } return children.ToImmutableAndFree(); } public override SingleNamespaceOrTypeDeclaration VisitDelegateDeclaration(DelegateDeclarationSyntax node) { var declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; var diagnostics = DiagnosticBag.GetInstance(); if (node.Arity == 0) { Symbol.ReportErrorIfHasConstraints(node.ConstraintClauses, diagnostics); } declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); var quickAttributes = DeclarationTreeBuilder.GetQuickAttributes(node.AttributeLists); return new SingleTypeDeclaration( kind: DeclarationKind.Delegate, name: node.Identifier.ValueText, arity: node.Arity, modifiers: modifiers, declFlags: declFlags, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: ImmutableSegmentedDictionary<string, VoidResult>.Empty, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics.ToReadOnlyAndFree(), _nonGlobalAliasedQuickAttributes | quickAttributes); } public override SingleNamespaceOrTypeDeclaration VisitEnumDeclaration(EnumDeclarationSyntax node) { var members = node.Members; SingleTypeDeclaration.TypeDeclarationFlags declFlags = node.AttributeLists.Any() ? SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes : SingleTypeDeclaration.TypeDeclarationFlags.None; if (node.BaseList != null) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations; } ImmutableSegmentedDictionary<string, VoidResult> memberNames = GetEnumMemberNames(members, ref declFlags); var diagnostics = DiagnosticBag.GetInstance(); var modifiers = node.Modifiers.ToDeclarationModifiers(diagnostics: diagnostics); var quickAttributes = DeclarationTreeBuilder.GetQuickAttributes(node.AttributeLists); return new SingleTypeDeclaration( kind: DeclarationKind.Enum, name: node.Identifier.ValueText, arity: 0, modifiers: modifiers, declFlags: declFlags, syntaxReference: _syntaxTree.GetReference(node), nameLocation: new SourceLocation(node.Identifier), memberNames: memberNames, children: ImmutableArray<SingleTypeDeclaration>.Empty, diagnostics: diagnostics.ToReadOnlyAndFree(), _nonGlobalAliasedQuickAttributes | quickAttributes); } private static QuickAttributes GetQuickAttributes(SyntaxList<AttributeListSyntax> attributeLists) { var result = QuickAttributes.None; foreach (var attributeList in attributeLists) { foreach (var attribute in attributeList.Attributes) { result |= QuickAttributeHelpers.GetQuickAttributes(attribute.Name.GetUnqualifiedName().Identifier.ValueText, inAttribute: true); } } return result; } private static readonly ObjectPool<ImmutableSegmentedDictionary<string, VoidResult>.Builder> s_memberNameBuilderPool = new ObjectPool<ImmutableSegmentedDictionary<string, VoidResult>.Builder>(() => ImmutableSegmentedDictionary.CreateBuilder<string, VoidResult>()); private static ImmutableSegmentedDictionary<string, VoidResult> ToImmutableAndFree(ImmutableSegmentedDictionary<string, VoidResult>.Builder builder) { var result = builder.ToImmutable(); builder.Clear(); s_memberNameBuilderPool.Free(builder); return result; } private static ImmutableSegmentedDictionary<string, VoidResult> GetEnumMemberNames(SeparatedSyntaxList<EnumMemberDeclarationSyntax> members, ref SingleTypeDeclaration.TypeDeclarationFlags declFlags) { var cnt = members.Count; var memberNamesBuilder = s_memberNameBuilderPool.Allocate(); if (cnt != 0) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } bool anyMemberHasAttributes = false; foreach (var member in members) { memberNamesBuilder.TryAdd(member.Identifier.ValueText); if (!anyMemberHasAttributes && member.AttributeLists.Any()) { anyMemberHasAttributes = true; } } if (anyMemberHasAttributes) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes; } return ToImmutableAndFree(memberNamesBuilder); } private static ImmutableSegmentedDictionary<string, VoidResult> GetNonTypeMemberNames( CoreInternalSyntax.SyntaxList<Syntax.InternalSyntax.MemberDeclarationSyntax> members, ref SingleTypeDeclaration.TypeDeclarationFlags declFlags, bool skipGlobalStatements = false) { bool anyMethodHadExtensionSyntax = false; bool anyMemberHasAttributes = false; bool anyNonTypeMembers = false; var memberNameBuilder = s_memberNameBuilderPool.Allocate(); foreach (var member in members) { AddNonTypeMemberNames(member, memberNameBuilder, ref anyNonTypeMembers, skipGlobalStatements); // Check to see if any method contains a 'this' modifier on its first parameter. // This data is used to determine if a type needs to have its members materialized // as part of extension method lookup. if (!anyMethodHadExtensionSyntax && CheckMethodMemberForExtensionSyntax(member)) { anyMethodHadExtensionSyntax = true; } if (!anyMemberHasAttributes && CheckMemberForAttributes(member)) { anyMemberHasAttributes = true; } } if (anyMethodHadExtensionSyntax) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasExtensionMethodSyntax; } if (anyMemberHasAttributes) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes; } if (anyNonTypeMembers) { declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers; } return ToImmutableAndFree(memberNameBuilder); } private static bool CheckMethodMemberForExtensionSyntax(Syntax.InternalSyntax.CSharpSyntaxNode member) { if (member.Kind == SyntaxKind.MethodDeclaration) { var methodDecl = (Syntax.InternalSyntax.MethodDeclarationSyntax)member; var paramList = methodDecl.parameterList; if (paramList != null) { var parameters = paramList.Parameters; if (parameters.Count != 0) { var firstParameter = parameters[0]; foreach (var modifier in firstParameter.Modifiers) { if (modifier.Kind == SyntaxKind.ThisKeyword) { return true; } } } } } return false; } private static bool CheckMemberForAttributes(Syntax.InternalSyntax.CSharpSyntaxNode member) { switch (member.Kind) { case SyntaxKind.CompilationUnit: return (((Syntax.InternalSyntax.CompilationUnitSyntax)member).AttributeLists).Any(); case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return (((Syntax.InternalSyntax.BaseTypeDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.DelegateDeclaration: return (((Syntax.InternalSyntax.DelegateDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: return (((Syntax.InternalSyntax.BaseFieldDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.MethodDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: return (((Syntax.InternalSyntax.BaseMethodDeclarationSyntax)member).AttributeLists).Any(); case SyntaxKind.PropertyDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: var baseProp = (Syntax.InternalSyntax.BasePropertyDeclarationSyntax)member; bool hasAttributes = baseProp.AttributeLists.Any(); if (!hasAttributes && baseProp.AccessorList != null) { foreach (var accessor in baseProp.AccessorList.Accessors) { hasAttributes |= accessor.AttributeLists.Any(); } } return hasAttributes; } return false; } private static void AddNonTypeMemberNames( Syntax.InternalSyntax.CSharpSyntaxNode member, ImmutableSegmentedDictionary<string, VoidResult>.Builder set, ref bool anyNonTypeMembers, bool skipGlobalStatements) { switch (member.Kind) { case SyntaxKind.FieldDeclaration: anyNonTypeMembers = true; CodeAnalysis.Syntax.InternalSyntax.SeparatedSyntaxList<Syntax.InternalSyntax.VariableDeclaratorSyntax> fieldDeclarators = ((Syntax.InternalSyntax.FieldDeclarationSyntax)member).Declaration.Variables; int numFieldDeclarators = fieldDeclarators.Count; for (int i = 0; i < numFieldDeclarators; i++) { set.TryAdd(fieldDeclarators[i].Identifier.ValueText); } break; case SyntaxKind.EventFieldDeclaration: anyNonTypeMembers = true; CoreInternalSyntax.SeparatedSyntaxList<Syntax.InternalSyntax.VariableDeclaratorSyntax> eventDeclarators = ((Syntax.InternalSyntax.EventFieldDeclarationSyntax)member).Declaration.Variables; int numEventDeclarators = eventDeclarators.Count; for (int i = 0; i < numEventDeclarators; i++) { set.TryAdd(eventDeclarators[i].Identifier.ValueText); } break; case SyntaxKind.MethodDeclaration: anyNonTypeMembers = true; // Member names are exposed via NamedTypeSymbol.MemberNames and are used primarily // as an acid test to determine whether a more in-depth search of a type is worthwhile. // We decided that it was reasonable to exclude explicit interface implementations // from the list of member names. var methodDecl = (Syntax.InternalSyntax.MethodDeclarationSyntax)member; if (methodDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(methodDecl.Identifier.ValueText); } break; case SyntaxKind.PropertyDeclaration: anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var propertyDecl = (Syntax.InternalSyntax.PropertyDeclarationSyntax)member; if (propertyDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(propertyDecl.Identifier.ValueText); } break; case SyntaxKind.EventDeclaration: anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var eventDecl = (Syntax.InternalSyntax.EventDeclarationSyntax)member; if (eventDecl.ExplicitInterfaceSpecifier == null) { set.TryAdd(eventDecl.Identifier.ValueText); } break; case SyntaxKind.ConstructorDeclaration: anyNonTypeMembers = true; set.TryAdd(((Syntax.InternalSyntax.ConstructorDeclarationSyntax)member).Modifiers.Any((int)SyntaxKind.StaticKeyword) ? WellKnownMemberNames.StaticConstructorName : WellKnownMemberNames.InstanceConstructorName); break; case SyntaxKind.DestructorDeclaration: anyNonTypeMembers = true; set.TryAdd(WellKnownMemberNames.DestructorName); break; case SyntaxKind.IndexerDeclaration: anyNonTypeMembers = true; set.TryAdd(WellKnownMemberNames.Indexer); break; case SyntaxKind.OperatorDeclaration: { anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var opDecl = (Syntax.InternalSyntax.OperatorDeclarationSyntax)member; if (opDecl.ExplicitInterfaceSpecifier == null) { var name = OperatorFacts.OperatorNameFromDeclaration(opDecl); set.TryAdd(name); } } break; case SyntaxKind.ConversionOperatorDeclaration: { anyNonTypeMembers = true; // Handle in the same way as explicit method implementations var opDecl = (Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)member; if (opDecl.ExplicitInterfaceSpecifier == null) { var name = OperatorFacts.OperatorNameFromDeclaration(opDecl); set.TryAdd(name); } } break; case SyntaxKind.GlobalStatement: if (!skipGlobalStatements) { anyNonTypeMembers = true; } break; } } } }
1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/Declarations/MergedTypeDeclaration.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { // An invariant of a merged type declaration is that all of its children are also merged // declarations. [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed class MergedTypeDeclaration : MergedNamespaceOrTypeDeclaration { private readonly ImmutableArray<SingleTypeDeclaration> _declarations; private ImmutableArray<MergedTypeDeclaration> _lazyChildren; private ICollection<string> _lazyMemberNames; internal MergedTypeDeclaration(ImmutableArray<SingleTypeDeclaration> declarations) : base(declarations[0].Name) { _declarations = declarations; } public ImmutableArray<SingleTypeDeclaration> Declarations { get { return _declarations; } } public ImmutableArray<SyntaxReference> SyntaxReferences { get { return _declarations.SelectAsArray(r => r.SyntaxReference); } } public ImmutableArray<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { var attributeSyntaxListBuilder = ArrayBuilder<SyntaxList<AttributeListSyntax>>.GetInstance(); foreach (var decl in _declarations) { if (!decl.HasAnyAttributes) { continue; } var syntaxRef = decl.SyntaxReference; var typeDecl = syntaxRef.GetSyntax(); SyntaxList<AttributeListSyntax> attributesSyntaxList; switch (typeDecl.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: attributesSyntaxList = ((TypeDeclarationSyntax)typeDecl).AttributeLists; break; case SyntaxKind.DelegateDeclaration: attributesSyntaxList = ((DelegateDeclarationSyntax)typeDecl).AttributeLists; break; case SyntaxKind.EnumDeclaration: attributesSyntaxList = ((EnumDeclarationSyntax)typeDecl).AttributeLists; break; default: throw ExceptionUtilities.UnexpectedValue(typeDecl.Kind()); } attributeSyntaxListBuilder.Add(attributesSyntaxList); } return attributeSyntaxListBuilder.ToImmutableAndFree(); } public override DeclarationKind Kind { get { return this.Declarations[0].Kind; } } public int Arity { get { return this.Declarations[0].Arity; } } public bool ContainsExtensionMethods { get { foreach (var decl in this.Declarations) { if (decl.AnyMemberHasExtensionMethodSyntax) return true; } return false; } } public bool AnyMemberHasAttributes { get { foreach (var decl in this.Declarations) { if (decl.AnyMemberHasAttributes) return true; } return false; } } public LexicalSortKey GetLexicalSortKey(CSharpCompilation compilation) { LexicalSortKey sortKey = new LexicalSortKey(Declarations[0].NameLocation, compilation); for (var i = 1; i < Declarations.Length; i++) { sortKey = LexicalSortKey.First(sortKey, new LexicalSortKey(Declarations[i].NameLocation, compilation)); } return sortKey; } public ImmutableArray<SourceLocation> NameLocations { get { if (Declarations.Length == 1) { return ImmutableArray.Create(Declarations[0].NameLocation); } else { var builder = ArrayBuilder<SourceLocation>.GetInstance(); foreach (var decl in Declarations) { SourceLocation loc = decl.NameLocation; if (loc != null) builder.Add(loc); } return builder.ToImmutableAndFree(); } } } private ImmutableArray<MergedTypeDeclaration> MakeChildren() { ArrayBuilder<SingleTypeDeclaration> nestedTypes = null; foreach (var decl in this.Declarations) { foreach (var child in decl.Children) { var asType = child as SingleTypeDeclaration; if (asType != null) { if (nestedTypes == null) { nestedTypes = ArrayBuilder<SingleTypeDeclaration>.GetInstance(); } nestedTypes.Add(asType); } } } var children = ArrayBuilder<MergedTypeDeclaration>.GetInstance(); if (nestedTypes != null) { var typesGrouped = nestedTypes.ToDictionary(t => t.Identity); nestedTypes.Free(); foreach (var typeGroup in typesGrouped.Values) { children.Add(new MergedTypeDeclaration(typeGroup)); } } return children.ToImmutableAndFree(); } public new ImmutableArray<MergedTypeDeclaration> Children { get { if (_lazyChildren.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyChildren, MakeChildren()); } return _lazyChildren; } } protected override ImmutableArray<Declaration> GetDeclarationChildren() { return StaticCast<Declaration>.From(this.Children); } public ICollection<string> MemberNames { get { if (_lazyMemberNames == null) { var names = UnionCollection<string>.Create(this.Declarations, d => d.MemberNames.Keys); Interlocked.CompareExchange(ref _lazyMemberNames, names, null); } return _lazyMemberNames; } } internal string GetDebuggerDisplay() { return $"{nameof(MergedTypeDeclaration)} {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.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { // An invariant of a merged type declaration is that all of its children are also merged // declarations. [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal sealed class MergedTypeDeclaration : MergedNamespaceOrTypeDeclaration { private readonly ImmutableArray<SingleTypeDeclaration> _declarations; private ImmutableArray<MergedTypeDeclaration> _lazyChildren; private ICollection<string> _lazyMemberNames; internal MergedTypeDeclaration(ImmutableArray<SingleTypeDeclaration> declarations) : base(declarations[0].Name) { _declarations = declarations; } public ImmutableArray<SingleTypeDeclaration> Declarations { get { return _declarations; } } public ImmutableArray<SyntaxReference> SyntaxReferences { get { return _declarations.SelectAsArray(r => r.SyntaxReference); } } /// <summary> /// Returns the original syntax nodes for this type declaration across all its parts. If /// <paramref name="quickAttributes"/> is provided, attributes will not be returned if it /// is certain there are none that could match the request. This prevents going back to /// source unnecessarily. /// </summary> public ImmutableArray<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations(QuickAttributes? quickAttributes) { var attributeSyntaxListBuilder = ArrayBuilder<SyntaxList<AttributeListSyntax>>.GetInstance(); foreach (var decl in _declarations) { if (!decl.HasAnyAttributes) { continue; } if (quickAttributes != null && (decl.QuickAttributes & quickAttributes.Value) == 0) { continue; } var syntaxRef = decl.SyntaxReference; var typeDecl = syntaxRef.GetSyntax(); SyntaxList<AttributeListSyntax> attributesSyntaxList; switch (typeDecl.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: attributesSyntaxList = ((TypeDeclarationSyntax)typeDecl).AttributeLists; break; case SyntaxKind.DelegateDeclaration: attributesSyntaxList = ((DelegateDeclarationSyntax)typeDecl).AttributeLists; break; case SyntaxKind.EnumDeclaration: attributesSyntaxList = ((EnumDeclarationSyntax)typeDecl).AttributeLists; break; default: throw ExceptionUtilities.UnexpectedValue(typeDecl.Kind()); } attributeSyntaxListBuilder.Add(attributesSyntaxList); } return attributeSyntaxListBuilder.ToImmutableAndFree(); } public override DeclarationKind Kind { get { return this.Declarations[0].Kind; } } public int Arity { get { return this.Declarations[0].Arity; } } public bool ContainsExtensionMethods { get { foreach (var decl in this.Declarations) { if (decl.AnyMemberHasExtensionMethodSyntax) return true; } return false; } } public bool AnyMemberHasAttributes { get { foreach (var decl in this.Declarations) { if (decl.AnyMemberHasAttributes) return true; } return false; } } public LexicalSortKey GetLexicalSortKey(CSharpCompilation compilation) { LexicalSortKey sortKey = new LexicalSortKey(Declarations[0].NameLocation, compilation); for (var i = 1; i < Declarations.Length; i++) { sortKey = LexicalSortKey.First(sortKey, new LexicalSortKey(Declarations[i].NameLocation, compilation)); } return sortKey; } public ImmutableArray<SourceLocation> NameLocations { get { if (Declarations.Length == 1) { return ImmutableArray.Create(Declarations[0].NameLocation); } else { var builder = ArrayBuilder<SourceLocation>.GetInstance(); foreach (var decl in Declarations) { SourceLocation loc = decl.NameLocation; if (loc != null) builder.Add(loc); } return builder.ToImmutableAndFree(); } } } private ImmutableArray<MergedTypeDeclaration> MakeChildren() { ArrayBuilder<SingleTypeDeclaration> nestedTypes = null; foreach (var decl in this.Declarations) { foreach (var child in decl.Children) { var asType = child as SingleTypeDeclaration; if (asType != null) { if (nestedTypes == null) { nestedTypes = ArrayBuilder<SingleTypeDeclaration>.GetInstance(); } nestedTypes.Add(asType); } } } var children = ArrayBuilder<MergedTypeDeclaration>.GetInstance(); if (nestedTypes != null) { var typesGrouped = nestedTypes.ToDictionary(t => t.Identity); nestedTypes.Free(); foreach (var typeGroup in typesGrouped.Values) { children.Add(new MergedTypeDeclaration(typeGroup)); } } return children.ToImmutableAndFree(); } public new ImmutableArray<MergedTypeDeclaration> Children { get { if (_lazyChildren.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyChildren, MakeChildren()); } return _lazyChildren; } } protected override ImmutableArray<Declaration> GetDeclarationChildren() { return StaticCast<Declaration>.From(this.Children); } public ICollection<string> MemberNames { get { if (_lazyMemberNames == null) { var names = UnionCollection<string>.Create(this.Declarations, d => d.MemberNames.Keys); Interlocked.CompareExchange(ref _lazyMemberNames, names, null); } return _lazyMemberNames; } } internal string GetDebuggerDisplay() { return $"{nameof(MergedTypeDeclaration)} {Name}"; } } }
1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/Declarations/RootSingleNamespaceDeclaration.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class RootSingleNamespaceDeclaration : SingleNamespaceDeclaration { private readonly ImmutableArray<ReferenceDirective> _referenceDirectives; private readonly bool _hasAssemblyAttributes; private readonly bool _hasGlobalUsings; private readonly bool _hasUsings; private readonly bool _hasExternAliases; public RootSingleNamespaceDeclaration( bool hasGlobalUsings, bool hasUsings, bool hasExternAliases, SyntaxReference treeNode, ImmutableArray<SingleNamespaceOrTypeDeclaration> children, ImmutableArray<ReferenceDirective> referenceDirectives, bool hasAssemblyAttributes, ImmutableArray<Diagnostic> diagnostics) : base(string.Empty, treeNode, nameLocation: new SourceLocation(treeNode), children: children, diagnostics: diagnostics) { Debug.Assert(!referenceDirectives.IsDefault); _referenceDirectives = referenceDirectives; _hasAssemblyAttributes = hasAssemblyAttributes; _hasGlobalUsings = hasGlobalUsings; _hasUsings = hasUsings; _hasExternAliases = hasExternAliases; } public ImmutableArray<ReferenceDirective> ReferenceDirectives { get { return _referenceDirectives; } } public bool HasAssemblyAttributes { get { return _hasAssemblyAttributes; } } public override bool HasGlobalUsings { get { return _hasGlobalUsings; } } public override bool HasUsings { get { return _hasUsings; } } public override bool HasExternAliases { get { return _hasExternAliases; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Symbols; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class RootSingleNamespaceDeclaration : SingleNamespaceDeclaration { private readonly ImmutableArray<ReferenceDirective> _referenceDirectives; private readonly bool _hasAssemblyAttributes; private readonly bool _hasGlobalUsings; private readonly bool _hasUsings; private readonly bool _hasExternAliases; /// <summary> /// Any special attributes we may be referencing directly through a global using alias in the file. /// <c>global using X = System.Runtime.CompilerServices.TypeForwardedToAttribute</c>. /// </summary> public QuickAttributes GlobalAliasedQuickAttributes { get; } public RootSingleNamespaceDeclaration( bool hasGlobalUsings, bool hasUsings, bool hasExternAliases, SyntaxReference treeNode, ImmutableArray<SingleNamespaceOrTypeDeclaration> children, ImmutableArray<ReferenceDirective> referenceDirectives, bool hasAssemblyAttributes, ImmutableArray<Diagnostic> diagnostics, QuickAttributes globalAliasedQuickAttributes) : base(string.Empty, treeNode, nameLocation: new SourceLocation(treeNode), children: children, diagnostics: diagnostics) { Debug.Assert(!referenceDirectives.IsDefault); _referenceDirectives = referenceDirectives; _hasAssemblyAttributes = hasAssemblyAttributes; _hasGlobalUsings = hasGlobalUsings; _hasUsings = hasUsings; _hasExternAliases = hasExternAliases; GlobalAliasedQuickAttributes = globalAliasedQuickAttributes; } public ImmutableArray<ReferenceDirective> ReferenceDirectives { get { return _referenceDirectives; } } public bool HasAssemblyAttributes { get { return _hasAssemblyAttributes; } } public override bool HasGlobalUsings { get { return _hasGlobalUsings; } } public override bool HasUsings { get { return _hasUsings; } } public override bool HasExternAliases { get { return _hasExternAliases; } } } }
1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/Declarations/SingleTypeDeclaration.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics; using Microsoft.CodeAnalysis.Collections; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class SingleTypeDeclaration : SingleNamespaceOrTypeDeclaration { private readonly DeclarationKind _kind; private readonly TypeDeclarationFlags _flags; private readonly ushort _arity; private readonly DeclarationModifiers _modifiers; private readonly ImmutableArray<SingleTypeDeclaration> _children; [Flags] internal enum TypeDeclarationFlags : ushort { None = 0, AnyMemberHasExtensionMethodSyntax = 1 << 1, HasAnyAttributes = 1 << 2, HasBaseDeclarations = 1 << 3, AnyMemberHasAttributes = 1 << 4, HasAnyNontypeMembers = 1 << 5, /// <summary> /// Simple program uses await expressions. Set only in conjunction with <see cref="TypeDeclarationFlags.IsSimpleProgram"/> /// </summary> HasAwaitExpressions = 1 << 6, /// <summary> /// Set only in conjunction with <see cref="TypeDeclarationFlags.IsSimpleProgram"/> /// </summary> IsIterator = 1 << 7, /// <summary> /// Set only in conjunction with <see cref="TypeDeclarationFlags.IsSimpleProgram"/> /// </summary> HasReturnWithExpression = 1 << 8, IsSimpleProgram = 1 << 9, } internal SingleTypeDeclaration( DeclarationKind kind, string name, int arity, DeclarationModifiers modifiers, TypeDeclarationFlags declFlags, SyntaxReference syntaxReference, SourceLocation nameLocation, ImmutableSegmentedDictionary<string, VoidResult> memberNames, ImmutableArray<SingleTypeDeclaration> children, ImmutableArray<Diagnostic> diagnostics) : base(name, syntaxReference, nameLocation, diagnostics) { Debug.Assert(kind != DeclarationKind.Namespace); _kind = kind; _arity = (ushort)arity; _modifiers = modifiers; MemberNames = memberNames; _children = children; _flags = declFlags; } public override DeclarationKind Kind { get { return _kind; } } public new ImmutableArray<SingleTypeDeclaration> Children { get { return _children; } } public int Arity { get { return _arity; } } public DeclarationModifiers Modifiers { get { return _modifiers; } } public ImmutableSegmentedDictionary<string, VoidResult> MemberNames { get; } public bool AnyMemberHasExtensionMethodSyntax { get { return (_flags & TypeDeclarationFlags.AnyMemberHasExtensionMethodSyntax) != 0; } } public bool HasAnyAttributes { get { return (_flags & TypeDeclarationFlags.HasAnyAttributes) != 0; } } public bool HasBaseDeclarations { get { return (_flags & TypeDeclarationFlags.HasBaseDeclarations) != 0; } } public bool AnyMemberHasAttributes { get { return (_flags & TypeDeclarationFlags.AnyMemberHasAttributes) != 0; } } public bool HasAnyNontypeMembers { get { return (_flags & TypeDeclarationFlags.HasAnyNontypeMembers) != 0; } } public bool HasAwaitExpressions { get { return (_flags & TypeDeclarationFlags.HasAwaitExpressions) != 0; } } public bool HasReturnWithExpression { get { return (_flags & TypeDeclarationFlags.HasReturnWithExpression) != 0; } } public bool IsIterator { get { return (_flags & TypeDeclarationFlags.IsIterator) != 0; } } public bool IsSimpleProgram { get { return (_flags & TypeDeclarationFlags.IsSimpleProgram) != 0; } } protected override ImmutableArray<SingleNamespaceOrTypeDeclaration> GetNamespaceOrTypeDeclarationChildren() { return StaticCast<SingleNamespaceOrTypeDeclaration>.From(_children); } internal TypeDeclarationIdentity Identity { get { return new TypeDeclarationIdentity(this); } } // identity that is used when collecting all declarations // of same type across multiple containers internal struct TypeDeclarationIdentity : IEquatable<TypeDeclarationIdentity> { private readonly SingleTypeDeclaration _decl; internal TypeDeclarationIdentity(SingleTypeDeclaration decl) { _decl = decl; } public override bool Equals(object obj) { return obj is TypeDeclarationIdentity && Equals((TypeDeclarationIdentity)obj); } public bool Equals(TypeDeclarationIdentity other) { var thisDecl = _decl; var otherDecl = other._decl; // same as itself if ((object)thisDecl == otherDecl) { return true; } // arity, kind, name must match if ((thisDecl._arity != otherDecl._arity) || (thisDecl._kind != otherDecl._kind) || (thisDecl.name != otherDecl.name)) { return false; } if (thisDecl._kind == DeclarationKind.Enum || thisDecl._kind == DeclarationKind.Delegate) { // oh, so close, but enums and delegates cannot be partial return false; } return true; } public override int GetHashCode() { var thisDecl = _decl; return Hash.Combine(thisDecl.Name.GetHashCode(), Hash.Combine(thisDecl.Arity.GetHashCode(), (int)thisDecl.Kind)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class SingleTypeDeclaration : SingleNamespaceOrTypeDeclaration { private readonly DeclarationKind _kind; private readonly TypeDeclarationFlags _flags; private readonly ushort _arity; private readonly DeclarationModifiers _modifiers; private readonly ImmutableArray<SingleTypeDeclaration> _children; /// <summary> /// Any special attributes we may be referencing directly as an attribute on this type or /// through a using alias in the file. For example /// <c>using X = System.Runtime.CompilerServices.TypeForwardedToAttribute</c> or /// <c>[TypeForwardedToAttribute]</c>. Can be used to avoid having to go back to source /// to retrieve attributes whtn there is no chance they would bind to attribute of interest. /// </summary> public QuickAttributes QuickAttributes { get; } [Flags] internal enum TypeDeclarationFlags : ushort { None = 0, AnyMemberHasExtensionMethodSyntax = 1 << 1, HasAnyAttributes = 1 << 2, HasBaseDeclarations = 1 << 3, AnyMemberHasAttributes = 1 << 4, HasAnyNontypeMembers = 1 << 5, /// <summary> /// Simple program uses await expressions. Set only in conjunction with <see cref="TypeDeclarationFlags.IsSimpleProgram"/> /// </summary> HasAwaitExpressions = 1 << 6, /// <summary> /// Set only in conjunction with <see cref="TypeDeclarationFlags.IsSimpleProgram"/> /// </summary> IsIterator = 1 << 7, /// <summary> /// Set only in conjunction with <see cref="TypeDeclarationFlags.IsSimpleProgram"/> /// </summary> HasReturnWithExpression = 1 << 8, IsSimpleProgram = 1 << 9, } internal SingleTypeDeclaration( DeclarationKind kind, string name, int arity, DeclarationModifiers modifiers, TypeDeclarationFlags declFlags, SyntaxReference syntaxReference, SourceLocation nameLocation, ImmutableSegmentedDictionary<string, VoidResult> memberNames, ImmutableArray<SingleTypeDeclaration> children, ImmutableArray<Diagnostic> diagnostics, QuickAttributes quickAttributes) : base(name, syntaxReference, nameLocation, diagnostics) { Debug.Assert(kind != DeclarationKind.Namespace); _kind = kind; _arity = (ushort)arity; _modifiers = modifiers; MemberNames = memberNames; _children = children; _flags = declFlags; QuickAttributes = quickAttributes; } public override DeclarationKind Kind { get { return _kind; } } public new ImmutableArray<SingleTypeDeclaration> Children { get { return _children; } } public int Arity { get { return _arity; } } public DeclarationModifiers Modifiers { get { return _modifiers; } } public ImmutableSegmentedDictionary<string, VoidResult> MemberNames { get; } public bool AnyMemberHasExtensionMethodSyntax { get { return (_flags & TypeDeclarationFlags.AnyMemberHasExtensionMethodSyntax) != 0; } } public bool HasAnyAttributes { get { return (_flags & TypeDeclarationFlags.HasAnyAttributes) != 0; } } public bool HasBaseDeclarations { get { return (_flags & TypeDeclarationFlags.HasBaseDeclarations) != 0; } } public bool AnyMemberHasAttributes { get { return (_flags & TypeDeclarationFlags.AnyMemberHasAttributes) != 0; } } public bool HasAnyNontypeMembers { get { return (_flags & TypeDeclarationFlags.HasAnyNontypeMembers) != 0; } } public bool HasAwaitExpressions { get { return (_flags & TypeDeclarationFlags.HasAwaitExpressions) != 0; } } public bool HasReturnWithExpression { get { return (_flags & TypeDeclarationFlags.HasReturnWithExpression) != 0; } } public bool IsIterator { get { return (_flags & TypeDeclarationFlags.IsIterator) != 0; } } public bool IsSimpleProgram { get { return (_flags & TypeDeclarationFlags.IsSimpleProgram) != 0; } } protected override ImmutableArray<SingleNamespaceOrTypeDeclaration> GetNamespaceOrTypeDeclarationChildren() { return StaticCast<SingleNamespaceOrTypeDeclaration>.From(_children); } internal TypeDeclarationIdentity Identity { get { return new TypeDeclarationIdentity(this); } } // identity that is used when collecting all declarations // of same type across multiple containers internal struct TypeDeclarationIdentity : IEquatable<TypeDeclarationIdentity> { private readonly SingleTypeDeclaration _decl; internal TypeDeclarationIdentity(SingleTypeDeclaration decl) { _decl = decl; } public override bool Equals(object obj) { return obj is TypeDeclarationIdentity && Equals((TypeDeclarationIdentity)obj); } public bool Equals(TypeDeclarationIdentity other) { var thisDecl = _decl; var otherDecl = other._decl; // same as itself if ((object)thisDecl == otherDecl) { return true; } // arity, kind, name must match if ((thisDecl._arity != otherDecl._arity) || (thisDecl._kind != otherDecl._kind) || (thisDecl.name != otherDecl.name)) { return false; } if (thisDecl._kind == DeclarationKind.Enum || thisDecl._kind == DeclarationKind.Delegate) { // oh, so close, but enums and delegates cannot be partial return false; } return true; } public override int GetHashCode() { var thisDecl = _decl; return Hash.Combine(thisDecl.Name.GetHashCode(), Hash.Combine(thisDecl.Arity.GetHashCode(), (int)thisDecl.Kind)); } } } }
1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/Symbols/Source/QuickAttributeChecker.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// The QuickAttributeChecker applies a simple fast heuristic for determining probable /// attributes of certain kinds without binding attribute types, just by looking at the final syntax of an /// attribute usage. /// </summary> /// <remarks> /// It works by maintaining a dictionary of all possible simple names that might map to the given /// attribute. /// </remarks> internal sealed class QuickAttributeChecker { private readonly Dictionary<string, QuickAttributes> _nameToAttributeMap; private static QuickAttributeChecker _lazyPredefinedQuickAttributeChecker; #if DEBUG private bool _sealed; #endif internal static QuickAttributeChecker Predefined { get { if (_lazyPredefinedQuickAttributeChecker is null) { Interlocked.CompareExchange(ref _lazyPredefinedQuickAttributeChecker, CreatePredefinedQuickAttributeChecker(), null); } return _lazyPredefinedQuickAttributeChecker; } } private static QuickAttributeChecker CreatePredefinedQuickAttributeChecker() { var result = new QuickAttributeChecker(); result.AddName(AttributeDescription.TypeIdentifierAttribute.Name, QuickAttributes.TypeIdentifier); result.AddName(AttributeDescription.TypeForwardedToAttribute.Name, QuickAttributes.TypeForwardedTo); result.AddName(AttributeDescription.AssemblyKeyNameAttribute.Name, QuickAttributes.AssemblyKeyName); result.AddName(AttributeDescription.AssemblyKeyFileAttribute.Name, QuickAttributes.AssemblyKeyFile); result.AddName(AttributeDescription.AssemblySignatureKeyAttribute.Name, QuickAttributes.AssemblySignatureKey); #if DEBUG result._sealed = true; #endif return result; } private QuickAttributeChecker() { _nameToAttributeMap = new Dictionary<string, QuickAttributes>(StringComparer.Ordinal); // NOTE: caller must seal } private QuickAttributeChecker(QuickAttributeChecker previous) { _nameToAttributeMap = new Dictionary<string, QuickAttributes>(previous._nameToAttributeMap, StringComparer.Ordinal); // NOTE: caller must seal } private void AddName(string name, QuickAttributes newAttributes) { #if DEBUG Debug.Assert(!_sealed); #endif var currentValue = QuickAttributes.None; _nameToAttributeMap.TryGetValue(name, out currentValue); QuickAttributes newValue = newAttributes | currentValue; _nameToAttributeMap[name] = newValue; } internal QuickAttributeChecker AddAliasesIfAny(SyntaxList<UsingDirectiveSyntax> usingsSyntax, bool onlyGlobalAliases = false) { if (usingsSyntax.Count == 0) { return this; } QuickAttributeChecker newChecker = null; foreach (var usingDirective in usingsSyntax) { if (usingDirective.Alias != null && (!onlyGlobalAliases || usingDirective.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword))) { string name = usingDirective.Alias.Name.Identifier.ValueText; string target = usingDirective.Name.GetUnqualifiedName().Identifier.ValueText; if (_nameToAttributeMap.TryGetValue(target, out var foundAttributes)) { // copy the QuickAttributes from alias target to alias name (newChecker ?? (newChecker = new QuickAttributeChecker(this))).AddName(name, foundAttributes); } } } if (newChecker != null) { #if DEBUG newChecker._sealed = true; #endif return newChecker; } return this; } public bool IsPossibleMatch(AttributeSyntax attr, QuickAttributes pattern) { #if DEBUG Debug.Assert(_sealed); #endif string name = attr.Name.GetUnqualifiedName().Identifier.ValueText; QuickAttributes foundAttributes; // We allow "Name" to bind to "NameAttribute" if (_nameToAttributeMap.TryGetValue(name, out foundAttributes) || _nameToAttributeMap.TryGetValue(name + "Attribute", out foundAttributes)) { return (foundAttributes & pattern) != 0; } return false; } } [Flags] internal enum QuickAttributes : byte { None = 0, TypeIdentifier = 1 << 0, TypeForwardedTo = 1 << 1, AssemblyKeyName = 1 << 2, AssemblyKeyFile = 1 << 3, AssemblySignatureKey = 1 << 4, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// The QuickAttributeChecker applies a simple fast heuristic for determining probable /// attributes of certain kinds without binding attribute types, just by looking at the final syntax of an /// attribute usage. /// </summary> /// <remarks> /// It works by maintaining a dictionary of all possible simple names that might map to the given /// attribute. /// </remarks> internal sealed class QuickAttributeChecker { private readonly Dictionary<string, QuickAttributes> _nameToAttributeMap; private static QuickAttributeChecker _lazyPredefinedQuickAttributeChecker; #if DEBUG private bool _sealed; #endif internal static QuickAttributeChecker Predefined { get { if (_lazyPredefinedQuickAttributeChecker is null) { Interlocked.CompareExchange(ref _lazyPredefinedQuickAttributeChecker, CreatePredefinedQuickAttributeChecker(), null); } return _lazyPredefinedQuickAttributeChecker; } } private static QuickAttributeChecker CreatePredefinedQuickAttributeChecker() { var result = new QuickAttributeChecker(); result.AddName(AttributeDescription.TypeIdentifierAttribute.Name, QuickAttributes.TypeIdentifier); result.AddName(AttributeDescription.TypeForwardedToAttribute.Name, QuickAttributes.TypeForwardedTo); result.AddName(AttributeDescription.AssemblyKeyNameAttribute.Name, QuickAttributes.AssemblyKeyName); result.AddName(AttributeDescription.AssemblyKeyFileAttribute.Name, QuickAttributes.AssemblyKeyFile); result.AddName(AttributeDescription.AssemblySignatureKeyAttribute.Name, QuickAttributes.AssemblySignatureKey); #if DEBUG result._sealed = true; #endif return result; } private QuickAttributeChecker() { _nameToAttributeMap = new Dictionary<string, QuickAttributes>(StringComparer.Ordinal); // NOTE: caller must seal } private QuickAttributeChecker(QuickAttributeChecker previous) { _nameToAttributeMap = new Dictionary<string, QuickAttributes>(previous._nameToAttributeMap, StringComparer.Ordinal); // NOTE: caller must seal } private void AddName(string name, QuickAttributes newAttributes) { #if DEBUG Debug.Assert(!_sealed); #endif var currentValue = QuickAttributes.None; _nameToAttributeMap.TryGetValue(name, out currentValue); QuickAttributes newValue = newAttributes | currentValue; _nameToAttributeMap[name] = newValue; } internal QuickAttributeChecker AddAliasesIfAny(SyntaxList<UsingDirectiveSyntax> usingsSyntax, bool onlyGlobalAliases = false) { if (usingsSyntax.Count == 0) { return this; } QuickAttributeChecker newChecker = null; foreach (var usingDirective in usingsSyntax) { if (usingDirective.Alias != null && (!onlyGlobalAliases || usingDirective.GlobalKeyword.IsKind(SyntaxKind.GlobalKeyword))) { string name = usingDirective.Alias.Name.Identifier.ValueText; string target = usingDirective.Name.GetUnqualifiedName().Identifier.ValueText; if (_nameToAttributeMap.TryGetValue(target, out var foundAttributes)) { // copy the QuickAttributes from alias target to alias name (newChecker ?? (newChecker = new QuickAttributeChecker(this))).AddName(name, foundAttributes); } } } if (newChecker != null) { #if DEBUG newChecker._sealed = true; #endif return newChecker; } return this; } public bool IsPossibleMatch(AttributeSyntax attr, QuickAttributes pattern) { #if DEBUG Debug.Assert(_sealed); #endif string name = attr.Name.GetUnqualifiedName().Identifier.ValueText; QuickAttributes foundAttributes; // We allow "Name" to bind to "NameAttribute" if (_nameToAttributeMap.TryGetValue(name, out foundAttributes) || _nameToAttributeMap.TryGetValue(name + "Attribute", out foundAttributes)) { return (foundAttributes & pattern) != 0; } return false; } } [Flags] internal enum QuickAttributes : byte { None = 0, TypeIdentifier = 1 << 0, TypeForwardedTo = 1 << 1, AssemblyKeyName = 1 << 2, AssemblyKeyFile = 1 << 3, AssemblySignatureKey = 1 << 4, Last = AssemblySignatureKey, } internal static class QuickAttributeHelpers { /// <summary> /// Returns the <see cref="QuickAttributes"/> that corresponds to the particular type /// <paramref name="name"/> passed in. If <paramref name="inAttribute"/> is <see langword="true"/> /// then the name will be checked both as-is as well as with the 'Attribute' suffix. /// </summary> public static QuickAttributes GetQuickAttributes(string name, bool inAttribute) { // Update this code if we add new quick attributes. Debug.Assert(QuickAttributes.Last == QuickAttributes.AssemblySignatureKey); var result = QuickAttributes.None; if (matches(AttributeDescription.TypeIdentifierAttribute)) { result |= QuickAttributes.TypeIdentifier; } else if (matches(AttributeDescription.TypeForwardedToAttribute)) { result |= QuickAttributes.TypeForwardedTo; } else if (matches(AttributeDescription.AssemblyKeyNameAttribute)) { result |= QuickAttributes.AssemblyKeyName; } else if (matches(AttributeDescription.AssemblyKeyFileAttribute)) { result |= QuickAttributes.AssemblyKeyFile; } else if (matches(AttributeDescription.AssemblySignatureKeyAttribute)) { result |= QuickAttributes.AssemblySignatureKey; } return result; bool matches(AttributeDescription attributeDescription) { Debug.Assert(attributeDescription.Name.EndsWith(nameof(System.Attribute))); if (name == attributeDescription.Name) { return true; } // In an attribute context the name might be referenced as the full name (like 'TypeForwardedToAttribute') // or the short name (like 'TypeForwardedTo'). if (inAttribute && (name.Length + nameof(System.Attribute).Length) == attributeDescription.Name.Length && attributeDescription.Name.StartsWith(name)) { return true; } return false; } } } }
1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/Symbols/Source/SourceNamedTypeSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { // This is a type symbol associated with a type definition in source code. // That is, for a generic type C<T> this is the instance type C<T>. internal sealed partial class SourceNamedTypeSymbol : SourceMemberContainerTypeSymbol, IAttributeTargetSymbol { private ImmutableArray<TypeParameterSymbol> _lazyTypeParameters; /// <summary> /// A collection of type parameter constraint types, populated when /// constraint types for the first type parameter are requested. /// </summary> private ImmutableArray<ImmutableArray<TypeWithAnnotations>> _lazyTypeParameterConstraintTypes; /// <summary> /// A collection of type parameter constraint kinds, populated when /// constraint kinds for the first type parameter are requested. /// </summary> private ImmutableArray<TypeParameterConstraintKind> _lazyTypeParameterConstraintKinds; private CustomAttributesBag<CSharpAttributeData> _lazyCustomAttributesBag; private string _lazyDocComment; private string _lazyExpandedDocComment; private ThreeState _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.Unknown; protected override Location GetCorrespondingBaseListLocation(NamedTypeSymbol @base) { Location backupLocation = null; foreach (SyntaxReference part in SyntaxReferences) { TypeDeclarationSyntax typeBlock = (TypeDeclarationSyntax)part.GetSyntax(); BaseListSyntax bases = typeBlock.BaseList; if (bases == null) { continue; } SeparatedSyntaxList<BaseTypeSyntax> inheritedTypeDecls = bases.Types; var baseBinder = this.DeclaringCompilation.GetBinder(bases); baseBinder = baseBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); if ((object)backupLocation == null) { backupLocation = inheritedTypeDecls[0].Type.GetLocation(); } foreach (BaseTypeSyntax baseTypeSyntax in inheritedTypeDecls) { TypeSyntax t = baseTypeSyntax.Type; TypeSymbol bt = baseBinder.BindType(t, BindingDiagnosticBag.Discarded).Type; if (TypeSymbol.Equals(bt, @base, TypeCompareKind.ConsiderEverything2)) { return t.GetLocation(); } } } return backupLocation; } internal SourceNamedTypeSymbol(NamespaceOrTypeSymbol containingSymbol, MergedTypeDeclaration declaration, BindingDiagnosticBag diagnostics, TupleExtraData tupleData = null) : base(containingSymbol, declaration, diagnostics, tupleData) { switch (declaration.Kind) { case DeclarationKind.Struct: case DeclarationKind.Interface: case DeclarationKind.Enum: case DeclarationKind.Delegate: case DeclarationKind.Class: case DeclarationKind.Record: case DeclarationKind.RecordStruct: break; default: Debug.Assert(false, "bad declaration kind"); break; } if (containingSymbol.Kind == SymbolKind.NamedType) { // Nested types are never unified. _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.False; } } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) { return new SourceNamedTypeSymbol(ContainingType, declaration, BindingDiagnosticBag.Discarded, newData); } #region Syntax private static SyntaxToken GetName(CSharpSyntaxNode node) { switch (node.Kind()) { case SyntaxKind.EnumDeclaration: return ((EnumDeclarationSyntax)node).Identifier; case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)node).Identifier; case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return ((BaseTypeDeclarationSyntax)node).Identifier; default: return default(SyntaxToken); } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { ref var lazyDocComment = ref expandIncludes ? ref _lazyExpandedDocComment : ref _lazyDocComment; return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(this, expandIncludes, ref lazyDocComment); } #endregion #region Type Parameters private ImmutableArray<TypeParameterSymbol> MakeTypeParameters(BindingDiagnosticBag diagnostics) { if (declaration.Arity == 0) { return ImmutableArray<TypeParameterSymbol>.Empty; } var typeParameterMismatchReported = false; var typeParameterNames = new string[declaration.Arity]; var typeParameterVarianceKeywords = new string[declaration.Arity]; var parameterBuilders1 = new List<List<TypeParameterBuilder>>(); foreach (var syntaxRef in this.SyntaxReferences) { var typeDecl = (CSharpSyntaxNode)syntaxRef.GetSyntax(); var syntaxTree = syntaxRef.SyntaxTree; TypeParameterListSyntax tpl; SyntaxKind typeKind = typeDecl.Kind(); switch (typeKind) { case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: tpl = ((TypeDeclarationSyntax)typeDecl).TypeParameterList; break; case SyntaxKind.DelegateDeclaration: tpl = ((DelegateDeclarationSyntax)typeDecl).TypeParameterList; break; case SyntaxKind.EnumDeclaration: default: // there is no such thing as a generic enum, so code should never reach here. throw ExceptionUtilities.UnexpectedValue(typeDecl.Kind()); } bool isInterfaceOrDelegate = typeKind == SyntaxKind.InterfaceDeclaration || typeKind == SyntaxKind.DelegateDeclaration; var parameterBuilder = new List<TypeParameterBuilder>(); parameterBuilders1.Add(parameterBuilder); int i = 0; foreach (var tp in tpl.Parameters) { if (tp.VarianceKeyword.Kind() != SyntaxKind.None && !isInterfaceOrDelegate) { diagnostics.Add(ErrorCode.ERR_IllegalVarianceSyntax, tp.VarianceKeyword.GetLocation()); } var name = typeParameterNames[i]; var location = new SourceLocation(tp.Identifier); var varianceKind = typeParameterVarianceKeywords[i]; ReportTypeNamedRecord(tp.Identifier.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, location); if (name == null) { name = typeParameterNames[i] = tp.Identifier.ValueText; varianceKind = typeParameterVarianceKeywords[i] = tp.VarianceKeyword.ValueText; for (int j = 0; j < i; j++) { if (name == typeParameterNames[j]) { typeParameterMismatchReported = true; diagnostics.Add(ErrorCode.ERR_DuplicateTypeParameter, location, name); goto next; } } if (!ReferenceEquals(ContainingType, null)) { var tpEnclosing = ContainingType.FindEnclosingTypeParameter(name); if ((object)tpEnclosing != null) { // Type parameter '{0}' has the same name as the type parameter from outer type '{1}' diagnostics.Add(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, location, name, tpEnclosing.ContainingType); } } next:; } else if (!typeParameterMismatchReported) { // Note: the "this", below, refers to the name of the current class, which includes its type // parameter names. But the type parameter names have not been computed yet. Therefore, we // take advantage of the fact that "this" won't undergo "ToString()" until later, when the // diagnostic is printed, by which time the type parameters field will have been filled in. if (varianceKind != tp.VarianceKeyword.ValueText) { // Dev10 reports CS1067, even if names also don't match typeParameterMismatchReported = true; diagnostics.Add( ErrorCode.ERR_PartialWrongTypeParamsVariance, declaration.NameLocations.First(), this); // see comment above } else if (name != tp.Identifier.ValueText) { typeParameterMismatchReported = true; diagnostics.Add( ErrorCode.ERR_PartialWrongTypeParams, declaration.NameLocations.First(), this); // see comment above } } parameterBuilder.Add(new TypeParameterBuilder(syntaxTree.GetReference(tp), this, location)); i++; } } var parameterBuilders2 = parameterBuilders1.Transpose(); // type arguments are positional var parameters = parameterBuilders2.Select((builders, i) => builders[0].MakeSymbol(i, builders, diagnostics)); return parameters.AsImmutable(); } /// <summary> /// Returns the constraint types for the given type parameter. /// </summary> internal ImmutableArray<TypeWithAnnotations> GetTypeParameterConstraintTypes(int ordinal) { var constraintTypes = GetTypeParameterConstraintTypes(); return (constraintTypes.Length > 0) ? constraintTypes[ordinal] : ImmutableArray<TypeWithAnnotations>.Empty; } private ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() { var constraintTypes = _lazyTypeParameterConstraintTypes; if (constraintTypes.IsDefault) { GetTypeParameterConstraintKinds(); var diagnostics = BindingDiagnosticBag.GetInstance(); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintTypes, MakeTypeParameterConstraintTypes(diagnostics))) { this.AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); constraintTypes = _lazyTypeParameterConstraintTypes; } return constraintTypes; } /// <summary> /// Returns the constraint kind for the given type parameter. /// </summary> internal TypeParameterConstraintKind GetTypeParameterConstraintKind(int ordinal) { var constraintKinds = GetTypeParameterConstraintKinds(); return (constraintKinds.Length > 0) ? constraintKinds[ordinal] : TypeParameterConstraintKind.None; } private ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() { var constraintKinds = _lazyTypeParameterConstraintKinds; if (constraintKinds.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintKinds, MakeTypeParameterConstraintKinds()); constraintKinds = _lazyTypeParameterConstraintKinds; } return constraintKinds; } private ImmutableArray<ImmutableArray<TypeWithAnnotations>> MakeTypeParameterConstraintTypes(BindingDiagnosticBag diagnostics) { var typeParameters = this.TypeParameters; var results = ImmutableArray<TypeParameterConstraintClause>.Empty; int arity = typeParameters.Length; if (arity > 0) { bool skipPartialDeclarationsWithoutConstraintClauses = SkipPartialDeclarationsWithoutConstraintClauses(); ArrayBuilder<ImmutableArray<TypeParameterConstraintClause>> otherPartialClauses = null; foreach (var decl in declaration.Declarations) { var syntaxRef = decl.SyntaxReference; var constraintClauses = GetConstraintClauses((CSharpSyntaxNode)syntaxRef.GetSyntax(), out TypeParameterListSyntax typeParameterList); if (skipPartialDeclarationsWithoutConstraintClauses && constraintClauses.Count == 0) { continue; } var binderFactory = this.DeclaringCompilation.GetBinderFactory(syntaxRef.SyntaxTree); Binder binder; ImmutableArray<TypeParameterConstraintClause> constraints; if (constraintClauses.Count == 0) { binder = binderFactory.GetBinder(typeParameterList.Parameters[0]); constraints = binder.GetDefaultTypeParameterConstraintClauses(typeParameterList); } else { binder = binderFactory.GetBinder(constraintClauses[0]); // Wrap binder from factory in a generic constraints specific binder // to avoid checking constraints when binding type names. Debug.Assert(!binder.Flags.Includes(BinderFlags.GenericConstraintsClause)); binder = binder.WithContainingMemberOrLambda(this).WithAdditionalFlags(BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks); constraints = binder.BindTypeParameterConstraintClauses(this, typeParameters, typeParameterList, constraintClauses, diagnostics, performOnlyCycleSafeValidation: false); } Debug.Assert(constraints.Length == arity); if (results.Length == 0) { results = constraints; } else { (otherPartialClauses ??= ArrayBuilder<ImmutableArray<TypeParameterConstraintClause>>.GetInstance()).Add(constraints); } } results = MergeConstraintTypesForPartialDeclarations(results, otherPartialClauses, diagnostics); if (results.All(clause => clause.ConstraintTypes.IsEmpty)) { results = ImmutableArray<TypeParameterConstraintClause>.Empty; } otherPartialClauses?.Free(); } return results.SelectAsArray(clause => clause.ConstraintTypes); } private bool SkipPartialDeclarationsWithoutConstraintClauses() { foreach (var decl in declaration.Declarations) { if (GetConstraintClauses((CSharpSyntaxNode)decl.SyntaxReference.GetSyntax(), out _).Count != 0) { return true; } } return false; } private ImmutableArray<TypeParameterConstraintKind> MakeTypeParameterConstraintKinds() { var typeParameters = this.TypeParameters; var results = ImmutableArray<TypeParameterConstraintClause>.Empty; int arity = typeParameters.Length; if (arity > 0) { bool skipPartialDeclarationsWithoutConstraintClauses = SkipPartialDeclarationsWithoutConstraintClauses(); ArrayBuilder<ImmutableArray<TypeParameterConstraintClause>> otherPartialClauses = null; foreach (var decl in declaration.Declarations) { var syntaxRef = decl.SyntaxReference; var constraintClauses = GetConstraintClauses((CSharpSyntaxNode)syntaxRef.GetSyntax(), out TypeParameterListSyntax typeParameterList); if (skipPartialDeclarationsWithoutConstraintClauses && constraintClauses.Count == 0) { continue; } var binderFactory = this.DeclaringCompilation.GetBinderFactory(syntaxRef.SyntaxTree); Binder binder; ImmutableArray<TypeParameterConstraintClause> constraints; if (constraintClauses.Count == 0) { binder = binderFactory.GetBinder(typeParameterList.Parameters[0]); constraints = binder.GetDefaultTypeParameterConstraintClauses(typeParameterList); } else { binder = binderFactory.GetBinder(constraintClauses[0]); // Wrap binder from factory in a generic constraints specific binder // to avoid checking constraints when binding type names. // Also, suppress type argument binding in constraint types, this helps to avoid cycles while we figure out constraint kinds. Debug.Assert(!binder.Flags.Includes(BinderFlags.GenericConstraintsClause)); binder = binder.WithContainingMemberOrLambda(this).WithAdditionalFlags(BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks | BinderFlags.SuppressTypeArgumentBinding); // We will recompute this diagnostics more accurately later, when binding without BinderFlags.SuppressTypeArgumentBinding constraints = binder.BindTypeParameterConstraintClauses(this, typeParameters, typeParameterList, constraintClauses, BindingDiagnosticBag.Discarded, performOnlyCycleSafeValidation: true); } Debug.Assert(constraints.Length == arity); if (results.Length == 0) { results = constraints; } else { (otherPartialClauses ??= ArrayBuilder<ImmutableArray<TypeParameterConstraintClause>>.GetInstance()).Add(constraints); } } results = MergeConstraintKindsForPartialDeclarations(results, otherPartialClauses); results = ConstraintsHelper.AdjustConstraintKindsBasedOnConstraintTypes(this, typeParameters, results); if (results.All(clause => clause.Constraints == TypeParameterConstraintKind.None)) { results = ImmutableArray<TypeParameterConstraintClause>.Empty; } otherPartialClauses?.Free(); } return results.SelectAsArray(clause => clause.Constraints); } private static SyntaxList<TypeParameterConstraintClauseSyntax> GetConstraintClauses(CSharpSyntaxNode node, out TypeParameterListSyntax typeParameterList) { switch (node.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: var typeDeclaration = (TypeDeclarationSyntax)node; typeParameterList = typeDeclaration.TypeParameterList; return typeDeclaration.ConstraintClauses; case SyntaxKind.DelegateDeclaration: var delegateDeclaration = (DelegateDeclarationSyntax)node; typeParameterList = delegateDeclaration.TypeParameterList; return delegateDeclaration.ConstraintClauses; default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } /// <summary> /// Note, only nullability aspects are merged if possible, other mismatches are treated as failures. /// </summary> private ImmutableArray<TypeParameterConstraintClause> MergeConstraintTypesForPartialDeclarations(ImmutableArray<TypeParameterConstraintClause> constraintClauses, ArrayBuilder<ImmutableArray<TypeParameterConstraintClause>> otherPartialClauses, BindingDiagnosticBag diagnostics) { if (otherPartialClauses == null) { return constraintClauses; } ArrayBuilder<TypeParameterConstraintClause> builder = null; var typeParameters = TypeParameters; int arity = typeParameters.Length; Debug.Assert(constraintClauses.Length == arity); for (int i = 0; i < arity; i++) { var constraint = constraintClauses[i]; ImmutableArray<TypeWithAnnotations> originalConstraintTypes = constraint.ConstraintTypes; ArrayBuilder<TypeWithAnnotations> mergedConstraintTypes = null; SmallDictionary<TypeWithAnnotations, int> originalConstraintTypesMap = null; // Constraints defined on multiple partial declarations. // Report any mismatched constraints. bool report = (GetTypeParameterConstraintKind(i) & TypeParameterConstraintKind.PartialMismatch) != 0; foreach (ImmutableArray<TypeParameterConstraintClause> otherPartialConstraints in otherPartialClauses) { if (!mergeConstraints(originalConstraintTypes, ref originalConstraintTypesMap, ref mergedConstraintTypes, otherPartialConstraints[i])) { report = true; } } if (report) { // "Partial declarations of '{0}' have inconsistent constraints for type parameter '{1}'" diagnostics.Add(ErrorCode.ERR_PartialWrongConstraints, Locations[0], this, typeParameters[i]); } if (mergedConstraintTypes != null) { #if DEBUG Debug.Assert(originalConstraintTypes.Length == mergedConstraintTypes.Count); for (int j = 0; j < originalConstraintTypes.Length; j++) { Debug.Assert(originalConstraintTypes[j].Equals(mergedConstraintTypes[j], TypeCompareKind.ObliviousNullableModifierMatchesAny)); } #endif if (builder == null) { builder = ArrayBuilder<TypeParameterConstraintClause>.GetInstance(constraintClauses.Length); builder.AddRange(constraintClauses); } builder[i] = TypeParameterConstraintClause.Create(constraint.Constraints, mergedConstraintTypes?.ToImmutableAndFree() ?? originalConstraintTypes); } } if (builder != null) { constraintClauses = builder.ToImmutableAndFree(); } return constraintClauses; static bool mergeConstraints(ImmutableArray<TypeWithAnnotations> originalConstraintTypes, ref SmallDictionary<TypeWithAnnotations, int> originalConstraintTypesMap, ref ArrayBuilder<TypeWithAnnotations> mergedConstraintTypes, TypeParameterConstraintClause clause) { bool result = true; if (originalConstraintTypes.Length == 0) { if (clause.ConstraintTypes.Length == 0) { return result; } return false; } else if (clause.ConstraintTypes.Length == 0) { return false; } originalConstraintTypesMap ??= toDictionary(originalConstraintTypes, TypeWithAnnotations.EqualsComparer.IgnoreNullableModifiersForReferenceTypesComparer); SmallDictionary<TypeWithAnnotations, int> clauseConstraintTypesMap = toDictionary(clause.ConstraintTypes, originalConstraintTypesMap.Comparer); foreach (int index1 in originalConstraintTypesMap.Values) { TypeWithAnnotations constraintType1 = mergedConstraintTypes?[index1] ?? originalConstraintTypes[index1]; int index2; if (!clauseConstraintTypesMap.TryGetValue(constraintType1, out index2)) { // No matching type result = false; continue; } TypeWithAnnotations constraintType2 = clause.ConstraintTypes[index2]; if (!constraintType1.Equals(constraintType2, TypeCompareKind.ObliviousNullableModifierMatchesAny)) { // Nullability mismatch that doesn't involve oblivious result = false; continue; } if (!constraintType1.Equals(constraintType2, TypeCompareKind.ConsiderEverything)) { // Mismatch with oblivious, merge if (mergedConstraintTypes == null) { mergedConstraintTypes = ArrayBuilder<TypeWithAnnotations>.GetInstance(originalConstraintTypes.Length); mergedConstraintTypes.AddRange(originalConstraintTypes); } mergedConstraintTypes[index1] = constraintType1.MergeEquivalentTypes(constraintType2, VarianceKind.None); } } foreach (var constraintType in clauseConstraintTypesMap.Keys) { if (!originalConstraintTypesMap.ContainsKey(constraintType)) { result = false; break; } } return result; } static SmallDictionary<TypeWithAnnotations, int> toDictionary(ImmutableArray<TypeWithAnnotations> constraintTypes, IEqualityComparer<TypeWithAnnotations> comparer) { var result = new SmallDictionary<TypeWithAnnotations, int>(comparer); for (int i = constraintTypes.Length - 1; i >= 0; i--) { result[constraintTypes[i]] = i; // Use the first type among the duplicates as the source of the nullable information } return result; } } /// <summary> /// Note, only nullability aspects are merged if possible, other mismatches are treated as failures. /// </summary> private ImmutableArray<TypeParameterConstraintClause> MergeConstraintKindsForPartialDeclarations(ImmutableArray<TypeParameterConstraintClause> constraintClauses, ArrayBuilder<ImmutableArray<TypeParameterConstraintClause>> otherPartialClauses) { if (otherPartialClauses == null) { return constraintClauses; } ArrayBuilder<TypeParameterConstraintClause> builder = null; var typeParameters = TypeParameters; int arity = typeParameters.Length; Debug.Assert(constraintClauses.Length == arity); for (int i = 0; i < arity; i++) { var constraint = constraintClauses[i]; TypeParameterConstraintKind mergedKind = constraint.Constraints; ImmutableArray<TypeWithAnnotations> originalConstraintTypes = constraint.ConstraintTypes; foreach (ImmutableArray<TypeParameterConstraintClause> otherPartialConstraints in otherPartialClauses) { mergeConstraints(ref mergedKind, originalConstraintTypes, otherPartialConstraints[i]); } if (constraint.Constraints != mergedKind) { Debug.Assert((constraint.Constraints & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull)) == (mergedKind & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull))); Debug.Assert((mergedKind & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) == 0 || (constraint.Constraints & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0); Debug.Assert((constraint.Constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) == (mergedKind & TypeParameterConstraintKind.AllReferenceTypeKinds) || (constraint.Constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) == TypeParameterConstraintKind.ReferenceType); if (builder == null) { builder = ArrayBuilder<TypeParameterConstraintClause>.GetInstance(constraintClauses.Length); builder.AddRange(constraintClauses); } builder[i] = TypeParameterConstraintClause.Create(mergedKind, originalConstraintTypes); } } if (builder != null) { constraintClauses = builder.ToImmutableAndFree(); } return constraintClauses; static void mergeConstraints(ref TypeParameterConstraintKind mergedKind, ImmutableArray<TypeWithAnnotations> originalConstraintTypes, TypeParameterConstraintClause clause) { if ((mergedKind & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull)) != (clause.Constraints & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull))) { mergedKind |= TypeParameterConstraintKind.PartialMismatch; } if ((mergedKind & TypeParameterConstraintKind.ReferenceType) != 0 && (clause.Constraints & TypeParameterConstraintKind.ReferenceType) != 0) { // Try merging nullability of a 'class' constraint TypeParameterConstraintKind clause1Constraints = mergedKind & TypeParameterConstraintKind.AllReferenceTypeKinds; TypeParameterConstraintKind clause2Constraints = clause.Constraints & TypeParameterConstraintKind.AllReferenceTypeKinds; if (clause1Constraints != clause2Constraints) { if (clause1Constraints == TypeParameterConstraintKind.ReferenceType) // Oblivious { // Take nullability from clause2 mergedKind = (mergedKind & (~TypeParameterConstraintKind.AllReferenceTypeKinds)) | clause2Constraints; } else if (clause2Constraints != TypeParameterConstraintKind.ReferenceType) { // Neither nullability is oblivious and they do not match. Cannot merge. mergedKind |= TypeParameterConstraintKind.PartialMismatch; } } } if (originalConstraintTypes.Length == 0 && clause.ConstraintTypes.Length == 0) { // Try merging nullability of implied 'object' constraint if (((mergedKind | clause.Constraints) & ~(TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType | TypeParameterConstraintKind.Constructor)) == 0 && (mergedKind & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0 && // 'object~' (clause.Constraints & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) == 0) // 'object?' { // Merged value is 'object?' mergedKind &= ~TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType; } } } } internal sealed override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return GetTypeParametersAsTypeArguments(); } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { if (_lazyTypeParameters.IsDefault) { var diagnostics = BindingDiagnosticBag.GetInstance(); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameters, MakeTypeParameters(diagnostics))) { AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } return _lazyTypeParameters; } } #endregion #region Attributes internal ImmutableArray<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { return declaration.GetAttributeDeclarations(); } IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner { get { return this; } } AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation { get { return AttributeLocation.Type; } } AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations { get { switch (TypeKind) { case TypeKind.Delegate: return AttributeLocation.Type | AttributeLocation.Return; case TypeKind.Enum: case TypeKind.Interface: return AttributeLocation.Type; case TypeKind.Struct: case TypeKind.Class: return AttributeLocation.Type; default: return AttributeLocation.None; } } } /// <summary> /// Returns a bag of applied custom attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> private CustomAttributesBag<CSharpAttributeData> GetAttributesBag() { var bag = _lazyCustomAttributesBag; if (bag != null && bag.IsSealed) { return bag; } if (LoadAndValidateAttributes(OneOrMany.Create(this.GetAttributeDeclarations()), ref _lazyCustomAttributesBag)) { var completed = state.NotePartComplete(CompletionPart.Attributes); Debug.Assert(completed); } Debug.Assert(_lazyCustomAttributesBag.IsSealed); return _lazyCustomAttributesBag; } /// <summary> /// Gets the attributes applied on this symbol. /// Returns an empty array if there are no attributes. /// </summary> public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.GetAttributesBag().Attributes; } /// <summary> /// Returns data decoded from well-known attributes applied to the symbol or null if there are no applied attributes. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> private TypeWellKnownAttributeData GetDecodedWellKnownAttributeData() { var attributesBag = _lazyCustomAttributesBag; if (attributesBag == null || !attributesBag.IsDecodedWellKnownAttributeDataComputed) { attributesBag = this.GetAttributesBag(); } return (TypeWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; } #nullable enable /// <summary> /// Returns data decoded from special early bound well-known attributes applied to the symbol or null if there are no applied attributes. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> internal TypeEarlyWellKnownAttributeData? GetEarlyDecodedWellKnownAttributeData() { var attributesBag = _lazyCustomAttributesBag; if (attributesBag == null || !attributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) { attributesBag = this.GetAttributesBag(); } return (TypeEarlyWellKnownAttributeData)attributesBag.EarlyDecodedWellKnownAttributeData; } internal override (CSharpAttributeData?, BoundAttribute?) EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments<EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation> arguments) { bool hasAnyDiagnostics; CSharpAttributeData? attributeData; BoundAttribute? boundAttribute; if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ComImportAttribute)) { (attributeData, boundAttribute) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out hasAnyDiagnostics); if (!attributeData.HasErrors) { arguments.GetOrCreateData<TypeEarlyWellKnownAttributeData>().HasComImportAttribute = true; if (!hasAnyDiagnostics) { return (attributeData, boundAttribute); } } return (null, null); } if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CodeAnalysisEmbeddedAttribute)) { (attributeData, boundAttribute) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out hasAnyDiagnostics); if (!attributeData.HasErrors) { arguments.GetOrCreateData<TypeEarlyWellKnownAttributeData>().HasCodeAnalysisEmbeddedAttribute = true; if (!hasAnyDiagnostics) { return (attributeData, boundAttribute); } } return (null, null); } if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ConditionalAttribute)) { (attributeData, boundAttribute) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out hasAnyDiagnostics); if (!attributeData.HasErrors) { string? name = attributeData.GetConstructorArgument<string>(0, SpecialType.System_String); arguments.GetOrCreateData<TypeEarlyWellKnownAttributeData>().AddConditionalSymbol(name); if (!hasAnyDiagnostics) { return (attributeData, boundAttribute); } } return (null, null); } ObsoleteAttributeData? obsoleteData; if (EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(ref arguments, out attributeData, out boundAttribute, out obsoleteData)) { if (obsoleteData != null) { arguments.GetOrCreateData<TypeEarlyWellKnownAttributeData>().ObsoleteAttributeData = obsoleteData; } return (attributeData, boundAttribute); } if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.AttributeUsageAttribute)) { (attributeData, boundAttribute) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out hasAnyDiagnostics); if (!attributeData.HasErrors) { AttributeUsageInfo info = this.DecodeAttributeUsageAttribute(attributeData, arguments.AttributeSyntax, diagnose: false); if (!info.IsNull) { var typeData = arguments.GetOrCreateData<TypeEarlyWellKnownAttributeData>(); if (typeData.AttributeUsageInfo.IsNull) { typeData.AttributeUsageInfo = info; } if (!hasAnyDiagnostics) { return (attributeData, boundAttribute); } } } return (null, null); } // We want to decode this early because it can influence overload resolution, which could affect attribute binding itself. Consider an attribute with these // constructors: // // MyAttribute(string s) // MyAttribute(CustomBuilder c) // CustomBuilder has InterpolatedStringHandlerAttribute on the type // // If it's applied with [MyAttribute($"{1}")], overload resolution rules say that we should prefer the CustomBuilder overload over the string overload. This // is an error scenario regardless (non-constant interpolated string), but it's good to get right as it will affect public API results. if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.InterpolatedStringHandlerAttribute)) { (attributeData, boundAttribute) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out hasAnyDiagnostics); if (!attributeData.HasErrors) { arguments.GetOrCreateData<TypeEarlyWellKnownAttributeData>().HasInterpolatedStringHandlerAttribute = true; if (!hasAnyDiagnostics) { return (attributeData, boundAttribute); } } return (null, null); } return base.EarlyDecodeWellKnownAttribute(ref arguments); } #nullable disable internal override AttributeUsageInfo GetAttributeUsageInfo() { Debug.Assert(this.SpecialType == SpecialType.System_Object || this.DeclaringCompilation.IsAttributeType(this)); TypeEarlyWellKnownAttributeData data = this.GetEarlyDecodedWellKnownAttributeData(); if (data != null && !data.AttributeUsageInfo.IsNull) { return data.AttributeUsageInfo; } return ((object)this.BaseTypeNoUseSiteDiagnostics != null) ? this.BaseTypeNoUseSiteDiagnostics.GetAttributeUsageInfo() : AttributeUsageInfo.Default; } /// <summary> /// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute. /// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet. /// </summary> internal override ObsoleteAttributeData ObsoleteAttributeData { get { var lazyCustomAttributesBag = _lazyCustomAttributesBag; if (lazyCustomAttributesBag != null && lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) { var data = (TypeEarlyWellKnownAttributeData)lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData; return data != null ? data.ObsoleteAttributeData : null; } foreach (var decl in this.declaration.Declarations) { if (decl.HasAnyAttributes) { return ObsoleteAttributeData.Uninitialized; } } return null; } } internal sealed override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics; var attribute = arguments.Attribute; Debug.Assert(!attribute.HasErrors); Debug.Assert(arguments.SymbolPart == AttributeLocation.None); if (attribute.IsTargetAttribute(this, AttributeDescription.AttributeUsageAttribute)) { DecodeAttributeUsageAttribute(attribute, arguments.AttributeSyntaxOpt, diagnose: true, diagnosticsOpt: diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.DefaultMemberAttribute)) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().HasDefaultMemberAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.CoClassAttribute)) { DecodeCoClassAttribute(ref arguments); } else if (attribute.IsTargetAttribute(this, AttributeDescription.ConditionalAttribute)) { ValidateConditionalAttribute(attribute, arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.GuidAttribute)) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().GuidString = attribute.DecodeGuidAttribute(arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.SpecialNameAttribute)) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().HasSpecialNameAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.SerializableAttribute)) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().HasSerializableAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.ExcludeFromCodeCoverageAttribute)) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().HasExcludeFromCodeCoverageAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.StructLayoutAttribute)) { AttributeData.DecodeStructLayoutAttribute<TypeWellKnownAttributeData, AttributeSyntax, CSharpAttributeData, AttributeLocation>( ref arguments, this.DefaultMarshallingCharSet, defaultAutoLayoutSize: 0, messageProvider: MessageProvider.Instance); } else if (attribute.IsTargetAttribute(this, AttributeDescription.SuppressUnmanagedCodeSecurityAttribute)) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().HasSuppressUnmanagedCodeSecurityAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.ClassInterfaceAttribute)) { attribute.DecodeClassInterfaceAttribute(arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.InterfaceTypeAttribute)) { attribute.DecodeInterfaceTypeAttribute(arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.WindowsRuntimeImportAttribute)) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().HasWindowsRuntimeImportAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.RequiredAttributeAttribute)) { // CS1608: The Required attribute is not permitted on C# types diagnostics.Add(ErrorCode.ERR_CantUseRequiredAttribute, arguments.AttributeSyntaxOpt.Name.Location); } else if (ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.DynamicAttribute | ReservedAttributes.IsReadOnlyAttribute | ReservedAttributes.IsUnmanagedAttribute | ReservedAttributes.IsByRefLikeAttribute | ReservedAttributes.TupleElementNamesAttribute | ReservedAttributes.NullableAttribute | ReservedAttributes.NullableContextAttribute | ReservedAttributes.NativeIntegerAttribute | ReservedAttributes.CaseSensitiveExtensionAttribute)) { } else if (attribute.IsTargetAttribute(this, AttributeDescription.SecurityCriticalAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.SecuritySafeCriticalAttribute)) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().HasSecurityCriticalAttributes = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.SkipLocalsInitAttribute)) { CSharpAttributeData.DecodeSkipLocalsInitAttribute<TypeWellKnownAttributeData>(DeclaringCompilation, ref arguments); } else if (_lazyIsExplicitDefinitionOfNoPiaLocalType == ThreeState.Unknown && attribute.IsTargetAttribute(this, AttributeDescription.TypeIdentifierAttribute)) { _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.True; } else { var compilation = this.DeclaringCompilation; if (attribute.IsSecurityAttribute(compilation)) { attribute.DecodeSecurityAttribute<TypeWellKnownAttributeData>(this, compilation, ref arguments); } } } internal override bool IsExplicitDefinitionOfNoPiaLocalType { get { if (_lazyIsExplicitDefinitionOfNoPiaLocalType == ThreeState.Unknown) { CheckPresenceOfTypeIdentifierAttribute(); if (_lazyIsExplicitDefinitionOfNoPiaLocalType == ThreeState.Unknown) { _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.False; } } Debug.Assert(_lazyIsExplicitDefinitionOfNoPiaLocalType != ThreeState.Unknown); return _lazyIsExplicitDefinitionOfNoPiaLocalType == ThreeState.True; } } private void CheckPresenceOfTypeIdentifierAttribute() { // Have we already decoded well-known attributes? if (_lazyCustomAttributesBag?.IsDecodedWellKnownAttributeDataComputed == true) { return; } // We want this function to be as cheap as possible, it is called for every top level type // and we don't want to bind attributes attached to the declaration unless there is a chance // that one of them is TypeIdentifier attribute. ImmutableArray<SyntaxList<AttributeListSyntax>> attributeLists = GetAttributeDeclarations(); foreach (SyntaxList<AttributeListSyntax> list in attributeLists) { var syntaxTree = list.Node.SyntaxTree; QuickAttributeChecker checker = this.DeclaringCompilation.GetBinderFactory(list.Node.SyntaxTree).GetBinder(list.Node).QuickAttributeChecker; foreach (AttributeListSyntax attrList in list) { foreach (AttributeSyntax attr in attrList.Attributes) { if (checker.IsPossibleMatch(attr, QuickAttributes.TypeIdentifier)) { // This attribute syntax might be an application of TypeIdentifierAttribute. // Let's bind it. // For simplicity we bind all attributes. GetAttributes(); return; } } } } } // Process the specified AttributeUsage attribute on the given ownerSymbol private AttributeUsageInfo DecodeAttributeUsageAttribute(CSharpAttributeData attribute, AttributeSyntax node, bool diagnose, BindingDiagnosticBag diagnosticsOpt = null) { Debug.Assert(diagnose == (diagnosticsOpt != null)); Debug.Assert(!attribute.HasErrors); Debug.Assert(!this.IsErrorType()); // AttributeUsage can only be specified for attribute classes if (!this.DeclaringCompilation.IsAttributeType(this)) { if (diagnose) { diagnosticsOpt.Add(ErrorCode.ERR_AttributeUsageOnNonAttributeClass, node.Name.Location, node.GetErrorDisplayName()); } return AttributeUsageInfo.Null; } else { AttributeUsageInfo info = attribute.DecodeAttributeUsageAttribute(); // Validate first ctor argument for AttributeUsage specification is a valid AttributeTargets enum member if (!info.HasValidAttributeTargets) { if (diagnose) { // invalid attribute target CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(0, node); diagnosticsOpt.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, node.GetErrorDisplayName()); } return AttributeUsageInfo.Null; } return info; } } private void DecodeCoClassAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { var attribute = arguments.Attribute; Debug.Assert(!attribute.HasErrors); if (this.IsInterfaceType() && (!arguments.HasDecodedData || (object)((TypeWellKnownAttributeData)arguments.DecodedData).ComImportCoClass == null)) { TypedConstant argument = attribute.CommonConstructorArguments[0]; Debug.Assert(argument.Kind == TypedConstantKind.Type); var coClassType = argument.ValueInternal as NamedTypeSymbol; if ((object)coClassType != null && coClassType.TypeKind == TypeKind.Class) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().ComImportCoClass = coClassType; } } } internal override bool IsComImport { get { TypeEarlyWellKnownAttributeData data = this.GetEarlyDecodedWellKnownAttributeData(); return data != null && data.HasComImportAttribute; } } internal override NamedTypeSymbol ComImportCoClass { get { TypeWellKnownAttributeData data = this.GetDecodedWellKnownAttributeData(); return data != null ? data.ComImportCoClass : null; } } private void ValidateConditionalAttribute(CSharpAttributeData attribute, AttributeSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(this.IsConditional); Debug.Assert(!attribute.HasErrors); if (!this.DeclaringCompilation.IsAttributeType(this)) { // CS1689: Attribute '{0}' is only valid on methods or attribute classes diagnostics.Add(ErrorCode.ERR_ConditionalOnNonAttributeClass, node.Location, node.GetErrorDisplayName()); } else { string name = attribute.GetConstructorArgument<string>(0, SpecialType.System_String); if (name == null || !SyntaxFacts.IsValidIdentifier(name)) { // CS0633: The argument to the '{0}' attribute must be a valid identifier CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(0, node); diagnostics.Add(ErrorCode.ERR_BadArgumentToAttribute, attributeArgumentSyntax.Location, node.GetErrorDisplayName()); } } } internal override bool HasSpecialName { get { var data = GetDecodedWellKnownAttributeData(); return data != null && data.HasSpecialNameAttribute; } } internal override bool HasCodeAnalysisEmbeddedAttribute { get { var data = GetEarlyDecodedWellKnownAttributeData(); return data != null && data.HasCodeAnalysisEmbeddedAttribute; } } #nullable enable internal sealed override bool IsInterpolatedStringHandlerType => GetEarlyDecodedWellKnownAttributeData()?.HasInterpolatedStringHandlerAttribute == true; #nullable disable internal sealed override bool ShouldAddWinRTMembers { get { return false; } } internal sealed override bool IsWindowsRuntimeImport { get { TypeWellKnownAttributeData data = this.GetDecodedWellKnownAttributeData(); return data != null && data.HasWindowsRuntimeImportAttribute; } } public sealed override bool IsSerializable { get { var data = this.GetDecodedWellKnownAttributeData(); return data != null && data.HasSerializableAttribute; } } public sealed override bool AreLocalsZeroed { get { var data = this.GetDecodedWellKnownAttributeData(); return data?.HasSkipLocalsInitAttribute != true && (ContainingType?.AreLocalsZeroed ?? ContainingModule.AreLocalsZeroed); } } internal override bool IsDirectlyExcludedFromCodeCoverage => GetDecodedWellKnownAttributeData()?.HasExcludeFromCodeCoverageAttribute == true; private bool HasInstanceFields() { var fields = this.GetFieldsToEmit(); foreach (var field in fields) { if (!field.IsStatic) { return true; } } return false; } internal sealed override TypeLayout Layout { get { var data = GetDecodedWellKnownAttributeData(); if (data != null && data.HasStructLayoutAttribute) { return data.Layout; } if (this.TypeKind == TypeKind.Struct) { // CLI spec 22.37.16: // "A ValueType shall have a non-zero size - either by defining at least one field, or by providing a non-zero ClassSize" // // Dev11 compiler sets the value to 1 for structs with no instance fields and no size specified. // It does not change the size value if it was explicitly specified to be 0, nor does it report an error. return new TypeLayout(LayoutKind.Sequential, this.HasInstanceFields() ? 0 : 1, alignment: 0); } return default(TypeLayout); } } internal bool HasStructLayoutAttribute { get { var data = GetDecodedWellKnownAttributeData(); return data != null && data.HasStructLayoutAttribute; } } internal override CharSet MarshallingCharSet { get { var data = GetDecodedWellKnownAttributeData(); return (data != null && data.HasStructLayoutAttribute) ? data.MarshallingCharSet : DefaultMarshallingCharSet; } } internal sealed override bool HasDeclarativeSecurity { get { var data = this.GetDecodedWellKnownAttributeData(); return data != null && data.HasDeclarativeSecurity; } } internal bool HasSecurityCriticalAttributes { get { var data = this.GetDecodedWellKnownAttributeData(); return data != null && data.HasSecurityCriticalAttributes; } } internal sealed override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation() { var attributesBag = this.GetAttributesBag(); var wellKnownData = (TypeWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; if (wellKnownData != null) { SecurityWellKnownAttributeData securityData = wellKnownData.SecurityInformation; if (securityData != null) { return securityData.GetSecurityAttributes(attributesBag.Attributes); } } return null; } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { var data = GetEarlyDecodedWellKnownAttributeData(); return data != null ? data.ConditionalSymbols : ImmutableArray<string>.Empty; } internal override void PostDecodeWellKnownAttributes(ImmutableArray<CSharpAttributeData> boundAttributes, ImmutableArray<AttributeSyntax> allAttributeSyntaxNodes, BindingDiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData) { Debug.Assert(!boundAttributes.IsDefault); Debug.Assert(!allAttributeSyntaxNodes.IsDefault); Debug.Assert(boundAttributes.Length == allAttributeSyntaxNodes.Length); Debug.Assert(_lazyCustomAttributesBag != null); Debug.Assert(_lazyCustomAttributesBag.IsDecodedWellKnownAttributeDataComputed); Debug.Assert(symbolPart == AttributeLocation.None); var data = (TypeWellKnownAttributeData)decodedData; if (this.IsComImport) { Debug.Assert(boundAttributes.Any()); // Symbol with ComImportAttribute must have a GuidAttribute if (data == null || data.GuidString == null) { int index = boundAttributes.IndexOfAttribute(this, AttributeDescription.ComImportAttribute); diagnostics.Add(ErrorCode.ERR_ComImportWithoutUuidAttribute, allAttributeSyntaxNodes[index].Name.Location, this.Name); } if (this.TypeKind == TypeKind.Class) { var baseType = this.BaseTypeNoUseSiteDiagnostics; if ((object)baseType != null && baseType.SpecialType != SpecialType.System_Object) { // CS0424: '{0}': a class with the ComImport attribute cannot specify a base class diagnostics.Add(ErrorCode.ERR_ComImportWithBase, this.Locations[0], this.Name); } var initializers = this.StaticInitializers; if (!initializers.IsDefaultOrEmpty) { foreach (var initializerGroup in initializers) { foreach (var singleInitializer in initializerGroup) { if (!singleInitializer.FieldOpt.IsMetadataConstant) { // CS8028: '{0}': a class with the ComImport attribute cannot specify field initializers. diagnostics.Add(ErrorCode.ERR_ComImportWithInitializers, singleInitializer.Syntax.GetLocation(), this.Name); } } } } initializers = this.InstanceInitializers; if (!initializers.IsDefaultOrEmpty) { foreach (var initializerGroup in initializers) { foreach (var singleInitializer in initializerGroup) { // CS8028: '{0}': a class with the ComImport attribute cannot specify field initializers. diagnostics.Add(ErrorCode.ERR_ComImportWithInitializers, singleInitializer.Syntax.GetLocation(), this.Name); } } } } } else if ((object)this.ComImportCoClass != null) { Debug.Assert(boundAttributes.Any()); // Symbol with CoClassAttribute must have a ComImportAttribute int index = boundAttributes.IndexOfAttribute(this, AttributeDescription.CoClassAttribute); diagnostics.Add(ErrorCode.WRN_CoClassWithoutComImport, allAttributeSyntaxNodes[index].Location, this.Name); } // Report ERR_DefaultMemberOnIndexedType if type has a default member attribute and has indexers. if (data != null && data.HasDefaultMemberAttribute && this.Indexers.Any()) { Debug.Assert(boundAttributes.Any()); int index = boundAttributes.IndexOfAttribute(this, AttributeDescription.DefaultMemberAttribute); diagnostics.Add(ErrorCode.ERR_DefaultMemberOnIndexedType, allAttributeSyntaxNodes[index].Name.Location); } base.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData); } /// <remarks> /// These won't be returned by GetAttributes on source methods, but they /// will be returned by GetAttributes on metadata symbols. /// </remarks> internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); CSharpCompilation compilation = this.DeclaringCompilation; if (this.ContainsExtensionMethods) { // No need to check if [Extension] attribute was explicitly set since // we'll issue CS1112 error in those cases and won't generate IL. AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor)); } if (this.IsRefLikeType) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsByRefLikeAttribute(this)); var obsoleteData = ObsoleteAttributeData; Debug.Assert(obsoleteData != ObsoleteAttributeData.Uninitialized, "getting synthesized attributes before attributes are decoded"); // If user specified an Obsolete attribute, we cannot emit ours. // NB: we do not check the kind of deprecation. // we will not emit Obsolete even if Deprecated or Experimental was used. // we do not want to get into a scenario where different kinds of deprecation are combined together. // if (obsoleteData == null && !this.IsRestrictedType(ignoreSpanLikeTypes: true)) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_ObsoleteAttribute__ctor, ImmutableArray.Create( new TypedConstant(compilation.GetSpecialType(SpecialType.System_String), TypedConstantKind.Primitive, PEModule.ByRefLikeMarker), // message new TypedConstant(compilation.GetSpecialType(SpecialType.System_Boolean), TypedConstantKind.Primitive, true)), // error=true isOptionalUse: true)); } } if (this.IsReadOnly) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); } if (this.Indexers.Any()) { string defaultMemberName = this.Indexers.First().MetadataName; // UNDONE: IndexerNameAttribute var defaultMemberNameConstant = new TypedConstant(compilation.GetSpecialType(SpecialType.System_String), TypedConstantKind.Primitive, defaultMemberName); AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Reflection_DefaultMemberAttribute__ctor, ImmutableArray.Create(defaultMemberNameConstant))); } if (this.declaration.Declarations.All(d => d.IsSimpleProgram)) { AddSynthesizedAttribute(ref attributes, this.DeclaringCompilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } } #endregion internal override NamedTypeSymbol AsNativeInteger() { Debug.Assert(this.SpecialType == SpecialType.System_IntPtr || this.SpecialType == SpecialType.System_UIntPtr); return ContainingAssembly.GetNativeIntegerType(this); } internal override NamedTypeSymbol NativeIntegerUnderlyingType => null; internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { return t2 is NativeIntegerTypeSymbol nativeInteger ? nativeInteger.Equals(this, comparison) : base.Equals(t2, comparison); } #nullable enable internal bool IsSimpleProgram { get { return this.declaration.Declarations.Any(d => d.IsSimpleProgram); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { // This is a type symbol associated with a type definition in source code. // That is, for a generic type C<T> this is the instance type C<T>. internal sealed partial class SourceNamedTypeSymbol : SourceMemberContainerTypeSymbol, IAttributeTargetSymbol { private ImmutableArray<TypeParameterSymbol> _lazyTypeParameters; /// <summary> /// A collection of type parameter constraint types, populated when /// constraint types for the first type parameter are requested. /// </summary> private ImmutableArray<ImmutableArray<TypeWithAnnotations>> _lazyTypeParameterConstraintTypes; /// <summary> /// A collection of type parameter constraint kinds, populated when /// constraint kinds for the first type parameter are requested. /// </summary> private ImmutableArray<TypeParameterConstraintKind> _lazyTypeParameterConstraintKinds; private CustomAttributesBag<CSharpAttributeData> _lazyCustomAttributesBag; private string _lazyDocComment; private string _lazyExpandedDocComment; private ThreeState _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.Unknown; protected override Location GetCorrespondingBaseListLocation(NamedTypeSymbol @base) { Location backupLocation = null; foreach (SyntaxReference part in SyntaxReferences) { TypeDeclarationSyntax typeBlock = (TypeDeclarationSyntax)part.GetSyntax(); BaseListSyntax bases = typeBlock.BaseList; if (bases == null) { continue; } SeparatedSyntaxList<BaseTypeSyntax> inheritedTypeDecls = bases.Types; var baseBinder = this.DeclaringCompilation.GetBinder(bases); baseBinder = baseBinder.WithAdditionalFlagsAndContainingMemberOrLambda(BinderFlags.SuppressConstraintChecks, this); if ((object)backupLocation == null) { backupLocation = inheritedTypeDecls[0].Type.GetLocation(); } foreach (BaseTypeSyntax baseTypeSyntax in inheritedTypeDecls) { TypeSyntax t = baseTypeSyntax.Type; TypeSymbol bt = baseBinder.BindType(t, BindingDiagnosticBag.Discarded).Type; if (TypeSymbol.Equals(bt, @base, TypeCompareKind.ConsiderEverything2)) { return t.GetLocation(); } } } return backupLocation; } internal SourceNamedTypeSymbol(NamespaceOrTypeSymbol containingSymbol, MergedTypeDeclaration declaration, BindingDiagnosticBag diagnostics, TupleExtraData tupleData = null) : base(containingSymbol, declaration, diagnostics, tupleData) { switch (declaration.Kind) { case DeclarationKind.Struct: case DeclarationKind.Interface: case DeclarationKind.Enum: case DeclarationKind.Delegate: case DeclarationKind.Class: case DeclarationKind.Record: case DeclarationKind.RecordStruct: break; default: Debug.Assert(false, "bad declaration kind"); break; } if (containingSymbol.Kind == SymbolKind.NamedType) { // Nested types are never unified. _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.False; } } protected override NamedTypeSymbol WithTupleDataCore(TupleExtraData newData) { return new SourceNamedTypeSymbol(ContainingType, declaration, BindingDiagnosticBag.Discarded, newData); } #region Syntax private static SyntaxToken GetName(CSharpSyntaxNode node) { switch (node.Kind()) { case SyntaxKind.EnumDeclaration: return ((EnumDeclarationSyntax)node).Identifier; case SyntaxKind.DelegateDeclaration: return ((DelegateDeclarationSyntax)node).Identifier; case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: return ((BaseTypeDeclarationSyntax)node).Identifier; default: return default(SyntaxToken); } } public override string GetDocumentationCommentXml(CultureInfo preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { ref var lazyDocComment = ref expandIncludes ? ref _lazyExpandedDocComment : ref _lazyDocComment; return SourceDocumentationCommentUtils.GetAndCacheDocumentationComment(this, expandIncludes, ref lazyDocComment); } #endregion #region Type Parameters private ImmutableArray<TypeParameterSymbol> MakeTypeParameters(BindingDiagnosticBag diagnostics) { if (declaration.Arity == 0) { return ImmutableArray<TypeParameterSymbol>.Empty; } var typeParameterMismatchReported = false; var typeParameterNames = new string[declaration.Arity]; var typeParameterVarianceKeywords = new string[declaration.Arity]; var parameterBuilders1 = new List<List<TypeParameterBuilder>>(); foreach (var syntaxRef in this.SyntaxReferences) { var typeDecl = (CSharpSyntaxNode)syntaxRef.GetSyntax(); var syntaxTree = syntaxRef.SyntaxTree; TypeParameterListSyntax tpl; SyntaxKind typeKind = typeDecl.Kind(); switch (typeKind) { case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: tpl = ((TypeDeclarationSyntax)typeDecl).TypeParameterList; break; case SyntaxKind.DelegateDeclaration: tpl = ((DelegateDeclarationSyntax)typeDecl).TypeParameterList; break; case SyntaxKind.EnumDeclaration: default: // there is no such thing as a generic enum, so code should never reach here. throw ExceptionUtilities.UnexpectedValue(typeDecl.Kind()); } bool isInterfaceOrDelegate = typeKind == SyntaxKind.InterfaceDeclaration || typeKind == SyntaxKind.DelegateDeclaration; var parameterBuilder = new List<TypeParameterBuilder>(); parameterBuilders1.Add(parameterBuilder); int i = 0; foreach (var tp in tpl.Parameters) { if (tp.VarianceKeyword.Kind() != SyntaxKind.None && !isInterfaceOrDelegate) { diagnostics.Add(ErrorCode.ERR_IllegalVarianceSyntax, tp.VarianceKeyword.GetLocation()); } var name = typeParameterNames[i]; var location = new SourceLocation(tp.Identifier); var varianceKind = typeParameterVarianceKeywords[i]; ReportTypeNamedRecord(tp.Identifier.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, location); if (name == null) { name = typeParameterNames[i] = tp.Identifier.ValueText; varianceKind = typeParameterVarianceKeywords[i] = tp.VarianceKeyword.ValueText; for (int j = 0; j < i; j++) { if (name == typeParameterNames[j]) { typeParameterMismatchReported = true; diagnostics.Add(ErrorCode.ERR_DuplicateTypeParameter, location, name); goto next; } } if (!ReferenceEquals(ContainingType, null)) { var tpEnclosing = ContainingType.FindEnclosingTypeParameter(name); if ((object)tpEnclosing != null) { // Type parameter '{0}' has the same name as the type parameter from outer type '{1}' diagnostics.Add(ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, location, name, tpEnclosing.ContainingType); } } next:; } else if (!typeParameterMismatchReported) { // Note: the "this", below, refers to the name of the current class, which includes its type // parameter names. But the type parameter names have not been computed yet. Therefore, we // take advantage of the fact that "this" won't undergo "ToString()" until later, when the // diagnostic is printed, by which time the type parameters field will have been filled in. if (varianceKind != tp.VarianceKeyword.ValueText) { // Dev10 reports CS1067, even if names also don't match typeParameterMismatchReported = true; diagnostics.Add( ErrorCode.ERR_PartialWrongTypeParamsVariance, declaration.NameLocations.First(), this); // see comment above } else if (name != tp.Identifier.ValueText) { typeParameterMismatchReported = true; diagnostics.Add( ErrorCode.ERR_PartialWrongTypeParams, declaration.NameLocations.First(), this); // see comment above } } parameterBuilder.Add(new TypeParameterBuilder(syntaxTree.GetReference(tp), this, location)); i++; } } var parameterBuilders2 = parameterBuilders1.Transpose(); // type arguments are positional var parameters = parameterBuilders2.Select((builders, i) => builders[0].MakeSymbol(i, builders, diagnostics)); return parameters.AsImmutable(); } /// <summary> /// Returns the constraint types for the given type parameter. /// </summary> internal ImmutableArray<TypeWithAnnotations> GetTypeParameterConstraintTypes(int ordinal) { var constraintTypes = GetTypeParameterConstraintTypes(); return (constraintTypes.Length > 0) ? constraintTypes[ordinal] : ImmutableArray<TypeWithAnnotations>.Empty; } private ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() { var constraintTypes = _lazyTypeParameterConstraintTypes; if (constraintTypes.IsDefault) { GetTypeParameterConstraintKinds(); var diagnostics = BindingDiagnosticBag.GetInstance(); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintTypes, MakeTypeParameterConstraintTypes(diagnostics))) { this.AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); constraintTypes = _lazyTypeParameterConstraintTypes; } return constraintTypes; } /// <summary> /// Returns the constraint kind for the given type parameter. /// </summary> internal TypeParameterConstraintKind GetTypeParameterConstraintKind(int ordinal) { var constraintKinds = GetTypeParameterConstraintKinds(); return (constraintKinds.Length > 0) ? constraintKinds[ordinal] : TypeParameterConstraintKind.None; } private ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() { var constraintKinds = _lazyTypeParameterConstraintKinds; if (constraintKinds.IsDefault) { ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintKinds, MakeTypeParameterConstraintKinds()); constraintKinds = _lazyTypeParameterConstraintKinds; } return constraintKinds; } private ImmutableArray<ImmutableArray<TypeWithAnnotations>> MakeTypeParameterConstraintTypes(BindingDiagnosticBag diagnostics) { var typeParameters = this.TypeParameters; var results = ImmutableArray<TypeParameterConstraintClause>.Empty; int arity = typeParameters.Length; if (arity > 0) { bool skipPartialDeclarationsWithoutConstraintClauses = SkipPartialDeclarationsWithoutConstraintClauses(); ArrayBuilder<ImmutableArray<TypeParameterConstraintClause>> otherPartialClauses = null; foreach (var decl in declaration.Declarations) { var syntaxRef = decl.SyntaxReference; var constraintClauses = GetConstraintClauses((CSharpSyntaxNode)syntaxRef.GetSyntax(), out TypeParameterListSyntax typeParameterList); if (skipPartialDeclarationsWithoutConstraintClauses && constraintClauses.Count == 0) { continue; } var binderFactory = this.DeclaringCompilation.GetBinderFactory(syntaxRef.SyntaxTree); Binder binder; ImmutableArray<TypeParameterConstraintClause> constraints; if (constraintClauses.Count == 0) { binder = binderFactory.GetBinder(typeParameterList.Parameters[0]); constraints = binder.GetDefaultTypeParameterConstraintClauses(typeParameterList); } else { binder = binderFactory.GetBinder(constraintClauses[0]); // Wrap binder from factory in a generic constraints specific binder // to avoid checking constraints when binding type names. Debug.Assert(!binder.Flags.Includes(BinderFlags.GenericConstraintsClause)); binder = binder.WithContainingMemberOrLambda(this).WithAdditionalFlags(BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks); constraints = binder.BindTypeParameterConstraintClauses(this, typeParameters, typeParameterList, constraintClauses, diagnostics, performOnlyCycleSafeValidation: false); } Debug.Assert(constraints.Length == arity); if (results.Length == 0) { results = constraints; } else { (otherPartialClauses ??= ArrayBuilder<ImmutableArray<TypeParameterConstraintClause>>.GetInstance()).Add(constraints); } } results = MergeConstraintTypesForPartialDeclarations(results, otherPartialClauses, diagnostics); if (results.All(clause => clause.ConstraintTypes.IsEmpty)) { results = ImmutableArray<TypeParameterConstraintClause>.Empty; } otherPartialClauses?.Free(); } return results.SelectAsArray(clause => clause.ConstraintTypes); } private bool SkipPartialDeclarationsWithoutConstraintClauses() { foreach (var decl in declaration.Declarations) { if (GetConstraintClauses((CSharpSyntaxNode)decl.SyntaxReference.GetSyntax(), out _).Count != 0) { return true; } } return false; } private ImmutableArray<TypeParameterConstraintKind> MakeTypeParameterConstraintKinds() { var typeParameters = this.TypeParameters; var results = ImmutableArray<TypeParameterConstraintClause>.Empty; int arity = typeParameters.Length; if (arity > 0) { bool skipPartialDeclarationsWithoutConstraintClauses = SkipPartialDeclarationsWithoutConstraintClauses(); ArrayBuilder<ImmutableArray<TypeParameterConstraintClause>> otherPartialClauses = null; foreach (var decl in declaration.Declarations) { var syntaxRef = decl.SyntaxReference; var constraintClauses = GetConstraintClauses((CSharpSyntaxNode)syntaxRef.GetSyntax(), out TypeParameterListSyntax typeParameterList); if (skipPartialDeclarationsWithoutConstraintClauses && constraintClauses.Count == 0) { continue; } var binderFactory = this.DeclaringCompilation.GetBinderFactory(syntaxRef.SyntaxTree); Binder binder; ImmutableArray<TypeParameterConstraintClause> constraints; if (constraintClauses.Count == 0) { binder = binderFactory.GetBinder(typeParameterList.Parameters[0]); constraints = binder.GetDefaultTypeParameterConstraintClauses(typeParameterList); } else { binder = binderFactory.GetBinder(constraintClauses[0]); // Wrap binder from factory in a generic constraints specific binder // to avoid checking constraints when binding type names. // Also, suppress type argument binding in constraint types, this helps to avoid cycles while we figure out constraint kinds. Debug.Assert(!binder.Flags.Includes(BinderFlags.GenericConstraintsClause)); binder = binder.WithContainingMemberOrLambda(this).WithAdditionalFlags(BinderFlags.GenericConstraintsClause | BinderFlags.SuppressConstraintChecks | BinderFlags.SuppressTypeArgumentBinding); // We will recompute this diagnostics more accurately later, when binding without BinderFlags.SuppressTypeArgumentBinding constraints = binder.BindTypeParameterConstraintClauses(this, typeParameters, typeParameterList, constraintClauses, BindingDiagnosticBag.Discarded, performOnlyCycleSafeValidation: true); } Debug.Assert(constraints.Length == arity); if (results.Length == 0) { results = constraints; } else { (otherPartialClauses ??= ArrayBuilder<ImmutableArray<TypeParameterConstraintClause>>.GetInstance()).Add(constraints); } } results = MergeConstraintKindsForPartialDeclarations(results, otherPartialClauses); results = ConstraintsHelper.AdjustConstraintKindsBasedOnConstraintTypes(this, typeParameters, results); if (results.All(clause => clause.Constraints == TypeParameterConstraintKind.None)) { results = ImmutableArray<TypeParameterConstraintClause>.Empty; } otherPartialClauses?.Free(); } return results.SelectAsArray(clause => clause.Constraints); } private static SyntaxList<TypeParameterConstraintClauseSyntax> GetConstraintClauses(CSharpSyntaxNode node, out TypeParameterListSyntax typeParameterList) { switch (node.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: var typeDeclaration = (TypeDeclarationSyntax)node; typeParameterList = typeDeclaration.TypeParameterList; return typeDeclaration.ConstraintClauses; case SyntaxKind.DelegateDeclaration: var delegateDeclaration = (DelegateDeclarationSyntax)node; typeParameterList = delegateDeclaration.TypeParameterList; return delegateDeclaration.ConstraintClauses; default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } /// <summary> /// Note, only nullability aspects are merged if possible, other mismatches are treated as failures. /// </summary> private ImmutableArray<TypeParameterConstraintClause> MergeConstraintTypesForPartialDeclarations(ImmutableArray<TypeParameterConstraintClause> constraintClauses, ArrayBuilder<ImmutableArray<TypeParameterConstraintClause>> otherPartialClauses, BindingDiagnosticBag diagnostics) { if (otherPartialClauses == null) { return constraintClauses; } ArrayBuilder<TypeParameterConstraintClause> builder = null; var typeParameters = TypeParameters; int arity = typeParameters.Length; Debug.Assert(constraintClauses.Length == arity); for (int i = 0; i < arity; i++) { var constraint = constraintClauses[i]; ImmutableArray<TypeWithAnnotations> originalConstraintTypes = constraint.ConstraintTypes; ArrayBuilder<TypeWithAnnotations> mergedConstraintTypes = null; SmallDictionary<TypeWithAnnotations, int> originalConstraintTypesMap = null; // Constraints defined on multiple partial declarations. // Report any mismatched constraints. bool report = (GetTypeParameterConstraintKind(i) & TypeParameterConstraintKind.PartialMismatch) != 0; foreach (ImmutableArray<TypeParameterConstraintClause> otherPartialConstraints in otherPartialClauses) { if (!mergeConstraints(originalConstraintTypes, ref originalConstraintTypesMap, ref mergedConstraintTypes, otherPartialConstraints[i])) { report = true; } } if (report) { // "Partial declarations of '{0}' have inconsistent constraints for type parameter '{1}'" diagnostics.Add(ErrorCode.ERR_PartialWrongConstraints, Locations[0], this, typeParameters[i]); } if (mergedConstraintTypes != null) { #if DEBUG Debug.Assert(originalConstraintTypes.Length == mergedConstraintTypes.Count); for (int j = 0; j < originalConstraintTypes.Length; j++) { Debug.Assert(originalConstraintTypes[j].Equals(mergedConstraintTypes[j], TypeCompareKind.ObliviousNullableModifierMatchesAny)); } #endif if (builder == null) { builder = ArrayBuilder<TypeParameterConstraintClause>.GetInstance(constraintClauses.Length); builder.AddRange(constraintClauses); } builder[i] = TypeParameterConstraintClause.Create(constraint.Constraints, mergedConstraintTypes?.ToImmutableAndFree() ?? originalConstraintTypes); } } if (builder != null) { constraintClauses = builder.ToImmutableAndFree(); } return constraintClauses; static bool mergeConstraints(ImmutableArray<TypeWithAnnotations> originalConstraintTypes, ref SmallDictionary<TypeWithAnnotations, int> originalConstraintTypesMap, ref ArrayBuilder<TypeWithAnnotations> mergedConstraintTypes, TypeParameterConstraintClause clause) { bool result = true; if (originalConstraintTypes.Length == 0) { if (clause.ConstraintTypes.Length == 0) { return result; } return false; } else if (clause.ConstraintTypes.Length == 0) { return false; } originalConstraintTypesMap ??= toDictionary(originalConstraintTypes, TypeWithAnnotations.EqualsComparer.IgnoreNullableModifiersForReferenceTypesComparer); SmallDictionary<TypeWithAnnotations, int> clauseConstraintTypesMap = toDictionary(clause.ConstraintTypes, originalConstraintTypesMap.Comparer); foreach (int index1 in originalConstraintTypesMap.Values) { TypeWithAnnotations constraintType1 = mergedConstraintTypes?[index1] ?? originalConstraintTypes[index1]; int index2; if (!clauseConstraintTypesMap.TryGetValue(constraintType1, out index2)) { // No matching type result = false; continue; } TypeWithAnnotations constraintType2 = clause.ConstraintTypes[index2]; if (!constraintType1.Equals(constraintType2, TypeCompareKind.ObliviousNullableModifierMatchesAny)) { // Nullability mismatch that doesn't involve oblivious result = false; continue; } if (!constraintType1.Equals(constraintType2, TypeCompareKind.ConsiderEverything)) { // Mismatch with oblivious, merge if (mergedConstraintTypes == null) { mergedConstraintTypes = ArrayBuilder<TypeWithAnnotations>.GetInstance(originalConstraintTypes.Length); mergedConstraintTypes.AddRange(originalConstraintTypes); } mergedConstraintTypes[index1] = constraintType1.MergeEquivalentTypes(constraintType2, VarianceKind.None); } } foreach (var constraintType in clauseConstraintTypesMap.Keys) { if (!originalConstraintTypesMap.ContainsKey(constraintType)) { result = false; break; } } return result; } static SmallDictionary<TypeWithAnnotations, int> toDictionary(ImmutableArray<TypeWithAnnotations> constraintTypes, IEqualityComparer<TypeWithAnnotations> comparer) { var result = new SmallDictionary<TypeWithAnnotations, int>(comparer); for (int i = constraintTypes.Length - 1; i >= 0; i--) { result[constraintTypes[i]] = i; // Use the first type among the duplicates as the source of the nullable information } return result; } } /// <summary> /// Note, only nullability aspects are merged if possible, other mismatches are treated as failures. /// </summary> private ImmutableArray<TypeParameterConstraintClause> MergeConstraintKindsForPartialDeclarations(ImmutableArray<TypeParameterConstraintClause> constraintClauses, ArrayBuilder<ImmutableArray<TypeParameterConstraintClause>> otherPartialClauses) { if (otherPartialClauses == null) { return constraintClauses; } ArrayBuilder<TypeParameterConstraintClause> builder = null; var typeParameters = TypeParameters; int arity = typeParameters.Length; Debug.Assert(constraintClauses.Length == arity); for (int i = 0; i < arity; i++) { var constraint = constraintClauses[i]; TypeParameterConstraintKind mergedKind = constraint.Constraints; ImmutableArray<TypeWithAnnotations> originalConstraintTypes = constraint.ConstraintTypes; foreach (ImmutableArray<TypeParameterConstraintClause> otherPartialConstraints in otherPartialClauses) { mergeConstraints(ref mergedKind, originalConstraintTypes, otherPartialConstraints[i]); } if (constraint.Constraints != mergedKind) { Debug.Assert((constraint.Constraints & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull)) == (mergedKind & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull))); Debug.Assert((mergedKind & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) == 0 || (constraint.Constraints & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0); Debug.Assert((constraint.Constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) == (mergedKind & TypeParameterConstraintKind.AllReferenceTypeKinds) || (constraint.Constraints & TypeParameterConstraintKind.AllReferenceTypeKinds) == TypeParameterConstraintKind.ReferenceType); if (builder == null) { builder = ArrayBuilder<TypeParameterConstraintClause>.GetInstance(constraintClauses.Length); builder.AddRange(constraintClauses); } builder[i] = TypeParameterConstraintClause.Create(mergedKind, originalConstraintTypes); } } if (builder != null) { constraintClauses = builder.ToImmutableAndFree(); } return constraintClauses; static void mergeConstraints(ref TypeParameterConstraintKind mergedKind, ImmutableArray<TypeWithAnnotations> originalConstraintTypes, TypeParameterConstraintClause clause) { if ((mergedKind & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull)) != (clause.Constraints & (TypeParameterConstraintKind.AllNonNullableKinds | TypeParameterConstraintKind.NotNull))) { mergedKind |= TypeParameterConstraintKind.PartialMismatch; } if ((mergedKind & TypeParameterConstraintKind.ReferenceType) != 0 && (clause.Constraints & TypeParameterConstraintKind.ReferenceType) != 0) { // Try merging nullability of a 'class' constraint TypeParameterConstraintKind clause1Constraints = mergedKind & TypeParameterConstraintKind.AllReferenceTypeKinds; TypeParameterConstraintKind clause2Constraints = clause.Constraints & TypeParameterConstraintKind.AllReferenceTypeKinds; if (clause1Constraints != clause2Constraints) { if (clause1Constraints == TypeParameterConstraintKind.ReferenceType) // Oblivious { // Take nullability from clause2 mergedKind = (mergedKind & (~TypeParameterConstraintKind.AllReferenceTypeKinds)) | clause2Constraints; } else if (clause2Constraints != TypeParameterConstraintKind.ReferenceType) { // Neither nullability is oblivious and they do not match. Cannot merge. mergedKind |= TypeParameterConstraintKind.PartialMismatch; } } } if (originalConstraintTypes.Length == 0 && clause.ConstraintTypes.Length == 0) { // Try merging nullability of implied 'object' constraint if (((mergedKind | clause.Constraints) & ~(TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType | TypeParameterConstraintKind.Constructor)) == 0 && (mergedKind & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) != 0 && // 'object~' (clause.Constraints & TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType) == 0) // 'object?' { // Merged value is 'object?' mergedKind &= ~TypeParameterConstraintKind.ObliviousNullabilityIfReferenceType; } } } } internal sealed override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotationsNoUseSiteDiagnostics { get { return GetTypeParametersAsTypeArguments(); } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { if (_lazyTypeParameters.IsDefault) { var diagnostics = BindingDiagnosticBag.GetInstance(); if (ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameters, MakeTypeParameters(diagnostics))) { AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } return _lazyTypeParameters; } } #endregion #region Attributes /// <summary> /// Gets all the attribute lists for this named type. If <paramref name="quickAttributes"/> is provided /// the attribute lists will only be returned if there is reasonable belief that /// the type has one of the attributes specified by <paramref name="quickAttributes"/> on it. /// This can avoid going back to syntax if we know the type definitely doesn't have an attribute /// on it that could be the one specified by <paramref name="quickAttributes"/>. Pass <see langword="null"/> /// to get all attribute declarations. /// </summary> internal ImmutableArray<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations(QuickAttributes? quickAttributes = null) { // if the compilation has any global aliases to these quick attributes, then we have to return // all the attributes on the decl. For example, if there is a `global using X = Y;` and // then we have to return any attributes on the type as they might say `[X]`. if (quickAttributes != null) { foreach (var decl in this.DeclaringCompilation.MergedRootDeclaration.Declarations) { if (decl is RootSingleNamespaceDeclaration rootNamespaceDecl && (rootNamespaceDecl.GlobalAliasedQuickAttributes & quickAttributes) != 0) { return declaration.GetAttributeDeclarations(quickAttributes: null); } } } return declaration.GetAttributeDeclarations(quickAttributes); } IAttributeTargetSymbol IAttributeTargetSymbol.AttributesOwner { get { return this; } } AttributeLocation IAttributeTargetSymbol.DefaultAttributeLocation { get { return AttributeLocation.Type; } } AttributeLocation IAttributeTargetSymbol.AllowedAttributeLocations { get { switch (TypeKind) { case TypeKind.Delegate: return AttributeLocation.Type | AttributeLocation.Return; case TypeKind.Enum: case TypeKind.Interface: return AttributeLocation.Type; case TypeKind.Struct: case TypeKind.Class: return AttributeLocation.Type; default: return AttributeLocation.None; } } } /// <summary> /// Returns a bag of applied custom attributes and data decoded from well-known attributes. Returns null if there are no attributes applied on the symbol. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> private CustomAttributesBag<CSharpAttributeData> GetAttributesBag() { var bag = _lazyCustomAttributesBag; if (bag != null && bag.IsSealed) { return bag; } if (LoadAndValidateAttributes(OneOrMany.Create(this.GetAttributeDeclarations()), ref _lazyCustomAttributesBag)) { var completed = state.NotePartComplete(CompletionPart.Attributes); Debug.Assert(completed); } Debug.Assert(_lazyCustomAttributesBag.IsSealed); return _lazyCustomAttributesBag; } /// <summary> /// Gets the attributes applied on this symbol. /// Returns an empty array if there are no attributes. /// </summary> public sealed override ImmutableArray<CSharpAttributeData> GetAttributes() { return this.GetAttributesBag().Attributes; } /// <summary> /// Returns data decoded from well-known attributes applied to the symbol or null if there are no applied attributes. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> private TypeWellKnownAttributeData GetDecodedWellKnownAttributeData() { var attributesBag = _lazyCustomAttributesBag; if (attributesBag == null || !attributesBag.IsDecodedWellKnownAttributeDataComputed) { attributesBag = this.GetAttributesBag(); } return (TypeWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; } #nullable enable /// <summary> /// Returns data decoded from special early bound well-known attributes applied to the symbol or null if there are no applied attributes. /// </summary> /// <remarks> /// Forces binding and decoding of attributes. /// </remarks> internal TypeEarlyWellKnownAttributeData? GetEarlyDecodedWellKnownAttributeData() { var attributesBag = _lazyCustomAttributesBag; if (attributesBag == null || !attributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) { attributesBag = this.GetAttributesBag(); } return (TypeEarlyWellKnownAttributeData)attributesBag.EarlyDecodedWellKnownAttributeData; } internal override (CSharpAttributeData?, BoundAttribute?) EarlyDecodeWellKnownAttribute(ref EarlyDecodeWellKnownAttributeArguments<EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation> arguments) { bool hasAnyDiagnostics; CSharpAttributeData? attributeData; BoundAttribute? boundAttribute; if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ComImportAttribute)) { (attributeData, boundAttribute) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out hasAnyDiagnostics); if (!attributeData.HasErrors) { arguments.GetOrCreateData<TypeEarlyWellKnownAttributeData>().HasComImportAttribute = true; if (!hasAnyDiagnostics) { return (attributeData, boundAttribute); } } return (null, null); } if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CodeAnalysisEmbeddedAttribute)) { (attributeData, boundAttribute) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out hasAnyDiagnostics); if (!attributeData.HasErrors) { arguments.GetOrCreateData<TypeEarlyWellKnownAttributeData>().HasCodeAnalysisEmbeddedAttribute = true; if (!hasAnyDiagnostics) { return (attributeData, boundAttribute); } } return (null, null); } if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ConditionalAttribute)) { (attributeData, boundAttribute) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out hasAnyDiagnostics); if (!attributeData.HasErrors) { string? name = attributeData.GetConstructorArgument<string>(0, SpecialType.System_String); arguments.GetOrCreateData<TypeEarlyWellKnownAttributeData>().AddConditionalSymbol(name); if (!hasAnyDiagnostics) { return (attributeData, boundAttribute); } } return (null, null); } ObsoleteAttributeData? obsoleteData; if (EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(ref arguments, out attributeData, out boundAttribute, out obsoleteData)) { if (obsoleteData != null) { arguments.GetOrCreateData<TypeEarlyWellKnownAttributeData>().ObsoleteAttributeData = obsoleteData; } return (attributeData, boundAttribute); } if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.AttributeUsageAttribute)) { (attributeData, boundAttribute) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out hasAnyDiagnostics); if (!attributeData.HasErrors) { AttributeUsageInfo info = this.DecodeAttributeUsageAttribute(attributeData, arguments.AttributeSyntax, diagnose: false); if (!info.IsNull) { var typeData = arguments.GetOrCreateData<TypeEarlyWellKnownAttributeData>(); if (typeData.AttributeUsageInfo.IsNull) { typeData.AttributeUsageInfo = info; } if (!hasAnyDiagnostics) { return (attributeData, boundAttribute); } } } return (null, null); } // We want to decode this early because it can influence overload resolution, which could affect attribute binding itself. Consider an attribute with these // constructors: // // MyAttribute(string s) // MyAttribute(CustomBuilder c) // CustomBuilder has InterpolatedStringHandlerAttribute on the type // // If it's applied with [MyAttribute($"{1}")], overload resolution rules say that we should prefer the CustomBuilder overload over the string overload. This // is an error scenario regardless (non-constant interpolated string), but it's good to get right as it will affect public API results. if (CSharpAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.InterpolatedStringHandlerAttribute)) { (attributeData, boundAttribute) = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, out hasAnyDiagnostics); if (!attributeData.HasErrors) { arguments.GetOrCreateData<TypeEarlyWellKnownAttributeData>().HasInterpolatedStringHandlerAttribute = true; if (!hasAnyDiagnostics) { return (attributeData, boundAttribute); } } return (null, null); } return base.EarlyDecodeWellKnownAttribute(ref arguments); } #nullable disable internal override AttributeUsageInfo GetAttributeUsageInfo() { Debug.Assert(this.SpecialType == SpecialType.System_Object || this.DeclaringCompilation.IsAttributeType(this)); TypeEarlyWellKnownAttributeData data = this.GetEarlyDecodedWellKnownAttributeData(); if (data != null && !data.AttributeUsageInfo.IsNull) { return data.AttributeUsageInfo; } return ((object)this.BaseTypeNoUseSiteDiagnostics != null) ? this.BaseTypeNoUseSiteDiagnostics.GetAttributeUsageInfo() : AttributeUsageInfo.Default; } /// <summary> /// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute. /// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet. /// </summary> internal override ObsoleteAttributeData ObsoleteAttributeData { get { var lazyCustomAttributesBag = _lazyCustomAttributesBag; if (lazyCustomAttributesBag != null && lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed) { var data = (TypeEarlyWellKnownAttributeData)lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData; return data != null ? data.ObsoleteAttributeData : null; } foreach (var decl in this.declaration.Declarations) { if (decl.HasAnyAttributes) { return ObsoleteAttributeData.Uninitialized; } } return null; } } internal sealed override void DecodeWellKnownAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { Debug.Assert((object)arguments.AttributeSyntaxOpt != null); var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics; var attribute = arguments.Attribute; Debug.Assert(!attribute.HasErrors); Debug.Assert(arguments.SymbolPart == AttributeLocation.None); if (attribute.IsTargetAttribute(this, AttributeDescription.AttributeUsageAttribute)) { DecodeAttributeUsageAttribute(attribute, arguments.AttributeSyntaxOpt, diagnose: true, diagnosticsOpt: diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.DefaultMemberAttribute)) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().HasDefaultMemberAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.CoClassAttribute)) { DecodeCoClassAttribute(ref arguments); } else if (attribute.IsTargetAttribute(this, AttributeDescription.ConditionalAttribute)) { ValidateConditionalAttribute(attribute, arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.GuidAttribute)) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().GuidString = attribute.DecodeGuidAttribute(arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.SpecialNameAttribute)) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().HasSpecialNameAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.SerializableAttribute)) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().HasSerializableAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.ExcludeFromCodeCoverageAttribute)) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().HasExcludeFromCodeCoverageAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.StructLayoutAttribute)) { AttributeData.DecodeStructLayoutAttribute<TypeWellKnownAttributeData, AttributeSyntax, CSharpAttributeData, AttributeLocation>( ref arguments, this.DefaultMarshallingCharSet, defaultAutoLayoutSize: 0, messageProvider: MessageProvider.Instance); } else if (attribute.IsTargetAttribute(this, AttributeDescription.SuppressUnmanagedCodeSecurityAttribute)) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().HasSuppressUnmanagedCodeSecurityAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.ClassInterfaceAttribute)) { attribute.DecodeClassInterfaceAttribute(arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.InterfaceTypeAttribute)) { attribute.DecodeInterfaceTypeAttribute(arguments.AttributeSyntaxOpt, diagnostics); } else if (attribute.IsTargetAttribute(this, AttributeDescription.WindowsRuntimeImportAttribute)) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().HasWindowsRuntimeImportAttribute = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.RequiredAttributeAttribute)) { // CS1608: The Required attribute is not permitted on C# types diagnostics.Add(ErrorCode.ERR_CantUseRequiredAttribute, arguments.AttributeSyntaxOpt.Name.Location); } else if (ReportExplicitUseOfReservedAttributes(in arguments, ReservedAttributes.DynamicAttribute | ReservedAttributes.IsReadOnlyAttribute | ReservedAttributes.IsUnmanagedAttribute | ReservedAttributes.IsByRefLikeAttribute | ReservedAttributes.TupleElementNamesAttribute | ReservedAttributes.NullableAttribute | ReservedAttributes.NullableContextAttribute | ReservedAttributes.NativeIntegerAttribute | ReservedAttributes.CaseSensitiveExtensionAttribute)) { } else if (attribute.IsTargetAttribute(this, AttributeDescription.SecurityCriticalAttribute) || attribute.IsTargetAttribute(this, AttributeDescription.SecuritySafeCriticalAttribute)) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().HasSecurityCriticalAttributes = true; } else if (attribute.IsTargetAttribute(this, AttributeDescription.SkipLocalsInitAttribute)) { CSharpAttributeData.DecodeSkipLocalsInitAttribute<TypeWellKnownAttributeData>(DeclaringCompilation, ref arguments); } else if (_lazyIsExplicitDefinitionOfNoPiaLocalType == ThreeState.Unknown && attribute.IsTargetAttribute(this, AttributeDescription.TypeIdentifierAttribute)) { _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.True; } else { var compilation = this.DeclaringCompilation; if (attribute.IsSecurityAttribute(compilation)) { attribute.DecodeSecurityAttribute<TypeWellKnownAttributeData>(this, compilation, ref arguments); } } } internal override bool IsExplicitDefinitionOfNoPiaLocalType { get { if (_lazyIsExplicitDefinitionOfNoPiaLocalType == ThreeState.Unknown) { CheckPresenceOfTypeIdentifierAttribute(); if (_lazyIsExplicitDefinitionOfNoPiaLocalType == ThreeState.Unknown) { _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.False; } } Debug.Assert(_lazyIsExplicitDefinitionOfNoPiaLocalType != ThreeState.Unknown); return _lazyIsExplicitDefinitionOfNoPiaLocalType == ThreeState.True; } } private void CheckPresenceOfTypeIdentifierAttribute() { // Have we already decoded well-known attributes? if (_lazyCustomAttributesBag?.IsDecodedWellKnownAttributeDataComputed == true) { return; } // We want this function to be as cheap as possible, it is called for every top level type // and we don't want to bind attributes attached to the declaration unless there is a chance // that one of them is TypeIdentifier attribute. ImmutableArray<SyntaxList<AttributeListSyntax>> attributeLists = GetAttributeDeclarations(QuickAttributes.TypeIdentifier); foreach (SyntaxList<AttributeListSyntax> list in attributeLists) { var syntaxTree = list.Node.SyntaxTree; QuickAttributeChecker checker = this.DeclaringCompilation.GetBinderFactory(list.Node.SyntaxTree).GetBinder(list.Node).QuickAttributeChecker; foreach (AttributeListSyntax attrList in list) { foreach (AttributeSyntax attr in attrList.Attributes) { if (checker.IsPossibleMatch(attr, QuickAttributes.TypeIdentifier)) { // This attribute syntax might be an application of TypeIdentifierAttribute. // Let's bind it. // For simplicity we bind all attributes. GetAttributes(); return; } } } } } // Process the specified AttributeUsage attribute on the given ownerSymbol private AttributeUsageInfo DecodeAttributeUsageAttribute(CSharpAttributeData attribute, AttributeSyntax node, bool diagnose, BindingDiagnosticBag diagnosticsOpt = null) { Debug.Assert(diagnose == (diagnosticsOpt != null)); Debug.Assert(!attribute.HasErrors); Debug.Assert(!this.IsErrorType()); // AttributeUsage can only be specified for attribute classes if (!this.DeclaringCompilation.IsAttributeType(this)) { if (diagnose) { diagnosticsOpt.Add(ErrorCode.ERR_AttributeUsageOnNonAttributeClass, node.Name.Location, node.GetErrorDisplayName()); } return AttributeUsageInfo.Null; } else { AttributeUsageInfo info = attribute.DecodeAttributeUsageAttribute(); // Validate first ctor argument for AttributeUsage specification is a valid AttributeTargets enum member if (!info.HasValidAttributeTargets) { if (diagnose) { // invalid attribute target CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(0, node); diagnosticsOpt.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, node.GetErrorDisplayName()); } return AttributeUsageInfo.Null; } return info; } } private void DecodeCoClassAttribute(ref DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments) { var attribute = arguments.Attribute; Debug.Assert(!attribute.HasErrors); if (this.IsInterfaceType() && (!arguments.HasDecodedData || (object)((TypeWellKnownAttributeData)arguments.DecodedData).ComImportCoClass == null)) { TypedConstant argument = attribute.CommonConstructorArguments[0]; Debug.Assert(argument.Kind == TypedConstantKind.Type); var coClassType = argument.ValueInternal as NamedTypeSymbol; if ((object)coClassType != null && coClassType.TypeKind == TypeKind.Class) { arguments.GetOrCreateData<TypeWellKnownAttributeData>().ComImportCoClass = coClassType; } } } internal override bool IsComImport { get { TypeEarlyWellKnownAttributeData data = this.GetEarlyDecodedWellKnownAttributeData(); return data != null && data.HasComImportAttribute; } } internal override NamedTypeSymbol ComImportCoClass { get { TypeWellKnownAttributeData data = this.GetDecodedWellKnownAttributeData(); return data != null ? data.ComImportCoClass : null; } } private void ValidateConditionalAttribute(CSharpAttributeData attribute, AttributeSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(this.IsConditional); Debug.Assert(!attribute.HasErrors); if (!this.DeclaringCompilation.IsAttributeType(this)) { // CS1689: Attribute '{0}' is only valid on methods or attribute classes diagnostics.Add(ErrorCode.ERR_ConditionalOnNonAttributeClass, node.Location, node.GetErrorDisplayName()); } else { string name = attribute.GetConstructorArgument<string>(0, SpecialType.System_String); if (name == null || !SyntaxFacts.IsValidIdentifier(name)) { // CS0633: The argument to the '{0}' attribute must be a valid identifier CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(0, node); diagnostics.Add(ErrorCode.ERR_BadArgumentToAttribute, attributeArgumentSyntax.Location, node.GetErrorDisplayName()); } } } internal override bool HasSpecialName { get { var data = GetDecodedWellKnownAttributeData(); return data != null && data.HasSpecialNameAttribute; } } internal override bool HasCodeAnalysisEmbeddedAttribute { get { var data = GetEarlyDecodedWellKnownAttributeData(); return data != null && data.HasCodeAnalysisEmbeddedAttribute; } } #nullable enable internal sealed override bool IsInterpolatedStringHandlerType => GetEarlyDecodedWellKnownAttributeData()?.HasInterpolatedStringHandlerAttribute == true; #nullable disable internal sealed override bool ShouldAddWinRTMembers { get { return false; } } internal sealed override bool IsWindowsRuntimeImport { get { TypeWellKnownAttributeData data = this.GetDecodedWellKnownAttributeData(); return data != null && data.HasWindowsRuntimeImportAttribute; } } public sealed override bool IsSerializable { get { var data = this.GetDecodedWellKnownAttributeData(); return data != null && data.HasSerializableAttribute; } } public sealed override bool AreLocalsZeroed { get { var data = this.GetDecodedWellKnownAttributeData(); return data?.HasSkipLocalsInitAttribute != true && (ContainingType?.AreLocalsZeroed ?? ContainingModule.AreLocalsZeroed); } } internal override bool IsDirectlyExcludedFromCodeCoverage => GetDecodedWellKnownAttributeData()?.HasExcludeFromCodeCoverageAttribute == true; private bool HasInstanceFields() { var fields = this.GetFieldsToEmit(); foreach (var field in fields) { if (!field.IsStatic) { return true; } } return false; } internal sealed override TypeLayout Layout { get { var data = GetDecodedWellKnownAttributeData(); if (data != null && data.HasStructLayoutAttribute) { return data.Layout; } if (this.TypeKind == TypeKind.Struct) { // CLI spec 22.37.16: // "A ValueType shall have a non-zero size - either by defining at least one field, or by providing a non-zero ClassSize" // // Dev11 compiler sets the value to 1 for structs with no instance fields and no size specified. // It does not change the size value if it was explicitly specified to be 0, nor does it report an error. return new TypeLayout(LayoutKind.Sequential, this.HasInstanceFields() ? 0 : 1, alignment: 0); } return default(TypeLayout); } } internal bool HasStructLayoutAttribute { get { var data = GetDecodedWellKnownAttributeData(); return data != null && data.HasStructLayoutAttribute; } } internal override CharSet MarshallingCharSet { get { var data = GetDecodedWellKnownAttributeData(); return (data != null && data.HasStructLayoutAttribute) ? data.MarshallingCharSet : DefaultMarshallingCharSet; } } internal sealed override bool HasDeclarativeSecurity { get { var data = this.GetDecodedWellKnownAttributeData(); return data != null && data.HasDeclarativeSecurity; } } internal bool HasSecurityCriticalAttributes { get { var data = this.GetDecodedWellKnownAttributeData(); return data != null && data.HasSecurityCriticalAttributes; } } internal sealed override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation() { var attributesBag = this.GetAttributesBag(); var wellKnownData = (TypeWellKnownAttributeData)attributesBag.DecodedWellKnownAttributeData; if (wellKnownData != null) { SecurityWellKnownAttributeData securityData = wellKnownData.SecurityInformation; if (securityData != null) { return securityData.GetSecurityAttributes(attributesBag.Attributes); } } return null; } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { var data = GetEarlyDecodedWellKnownAttributeData(); return data != null ? data.ConditionalSymbols : ImmutableArray<string>.Empty; } internal override void PostDecodeWellKnownAttributes(ImmutableArray<CSharpAttributeData> boundAttributes, ImmutableArray<AttributeSyntax> allAttributeSyntaxNodes, BindingDiagnosticBag diagnostics, AttributeLocation symbolPart, WellKnownAttributeData decodedData) { Debug.Assert(!boundAttributes.IsDefault); Debug.Assert(!allAttributeSyntaxNodes.IsDefault); Debug.Assert(boundAttributes.Length == allAttributeSyntaxNodes.Length); Debug.Assert(_lazyCustomAttributesBag != null); Debug.Assert(_lazyCustomAttributesBag.IsDecodedWellKnownAttributeDataComputed); Debug.Assert(symbolPart == AttributeLocation.None); var data = (TypeWellKnownAttributeData)decodedData; if (this.IsComImport) { Debug.Assert(boundAttributes.Any()); // Symbol with ComImportAttribute must have a GuidAttribute if (data == null || data.GuidString == null) { int index = boundAttributes.IndexOfAttribute(this, AttributeDescription.ComImportAttribute); diagnostics.Add(ErrorCode.ERR_ComImportWithoutUuidAttribute, allAttributeSyntaxNodes[index].Name.Location, this.Name); } if (this.TypeKind == TypeKind.Class) { var baseType = this.BaseTypeNoUseSiteDiagnostics; if ((object)baseType != null && baseType.SpecialType != SpecialType.System_Object) { // CS0424: '{0}': a class with the ComImport attribute cannot specify a base class diagnostics.Add(ErrorCode.ERR_ComImportWithBase, this.Locations[0], this.Name); } var initializers = this.StaticInitializers; if (!initializers.IsDefaultOrEmpty) { foreach (var initializerGroup in initializers) { foreach (var singleInitializer in initializerGroup) { if (!singleInitializer.FieldOpt.IsMetadataConstant) { // CS8028: '{0}': a class with the ComImport attribute cannot specify field initializers. diagnostics.Add(ErrorCode.ERR_ComImportWithInitializers, singleInitializer.Syntax.GetLocation(), this.Name); } } } } initializers = this.InstanceInitializers; if (!initializers.IsDefaultOrEmpty) { foreach (var initializerGroup in initializers) { foreach (var singleInitializer in initializerGroup) { // CS8028: '{0}': a class with the ComImport attribute cannot specify field initializers. diagnostics.Add(ErrorCode.ERR_ComImportWithInitializers, singleInitializer.Syntax.GetLocation(), this.Name); } } } } } else if ((object)this.ComImportCoClass != null) { Debug.Assert(boundAttributes.Any()); // Symbol with CoClassAttribute must have a ComImportAttribute int index = boundAttributes.IndexOfAttribute(this, AttributeDescription.CoClassAttribute); diagnostics.Add(ErrorCode.WRN_CoClassWithoutComImport, allAttributeSyntaxNodes[index].Location, this.Name); } // Report ERR_DefaultMemberOnIndexedType if type has a default member attribute and has indexers. if (data != null && data.HasDefaultMemberAttribute && this.Indexers.Any()) { Debug.Assert(boundAttributes.Any()); int index = boundAttributes.IndexOfAttribute(this, AttributeDescription.DefaultMemberAttribute); diagnostics.Add(ErrorCode.ERR_DefaultMemberOnIndexedType, allAttributeSyntaxNodes[index].Name.Location); } base.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData); } /// <remarks> /// These won't be returned by GetAttributes on source methods, but they /// will be returned by GetAttributes on metadata symbols. /// </remarks> internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); CSharpCompilation compilation = this.DeclaringCompilation; if (this.ContainsExtensionMethods) { // No need to check if [Extension] attribute was explicitly set since // we'll issue CS1112 error in those cases and won't generate IL. AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_ExtensionAttribute__ctor)); } if (this.IsRefLikeType) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsByRefLikeAttribute(this)); var obsoleteData = ObsoleteAttributeData; Debug.Assert(obsoleteData != ObsoleteAttributeData.Uninitialized, "getting synthesized attributes before attributes are decoded"); // If user specified an Obsolete attribute, we cannot emit ours. // NB: we do not check the kind of deprecation. // we will not emit Obsolete even if Deprecated or Experimental was used. // we do not want to get into a scenario where different kinds of deprecation are combined together. // if (obsoleteData == null && !this.IsRestrictedType(ignoreSpanLikeTypes: true)) { AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute(WellKnownMember.System_ObsoleteAttribute__ctor, ImmutableArray.Create( new TypedConstant(compilation.GetSpecialType(SpecialType.System_String), TypedConstantKind.Primitive, PEModule.ByRefLikeMarker), // message new TypedConstant(compilation.GetSpecialType(SpecialType.System_Boolean), TypedConstantKind.Primitive, true)), // error=true isOptionalUse: true)); } } if (this.IsReadOnly) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeIsReadOnlyAttribute(this)); } if (this.Indexers.Any()) { string defaultMemberName = this.Indexers.First().MetadataName; // UNDONE: IndexerNameAttribute var defaultMemberNameConstant = new TypedConstant(compilation.GetSpecialType(SpecialType.System_String), TypedConstantKind.Primitive, defaultMemberName); AddSynthesizedAttribute(ref attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Reflection_DefaultMemberAttribute__ctor, ImmutableArray.Create(defaultMemberNameConstant))); } if (this.declaration.Declarations.All(d => d.IsSimpleProgram)) { AddSynthesizedAttribute(ref attributes, this.DeclaringCompilation.TrySynthesizeAttribute(WellKnownMember.System_Runtime_CompilerServices_CompilerGeneratedAttribute__ctor)); } } #endregion internal override NamedTypeSymbol AsNativeInteger() { Debug.Assert(this.SpecialType == SpecialType.System_IntPtr || this.SpecialType == SpecialType.System_UIntPtr); return ContainingAssembly.GetNativeIntegerType(this); } internal override NamedTypeSymbol NativeIntegerUnderlyingType => null; internal override bool Equals(TypeSymbol t2, TypeCompareKind comparison) { return t2 is NativeIntegerTypeSymbol nativeInteger ? nativeInteger.Equals(this, comparison) : base.Equals(t2, comparison); } #nullable enable internal bool IsSimpleProgram { get { return this.declaration.Declarations.Any(d => d.IsSimpleProgram); } } } }
1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Test/Symbol/Compilation/CompilationAPITests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Reflection.PortableExecutable; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using VB = Microsoft.CodeAnalysis.VisualBasic; using KeyValuePairUtil = Roslyn.Utilities.KeyValuePairUtil; using System.Security.Cryptography; using static Roslyn.Test.Utilities.TestHelpers; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class CompilationAPITests : CSharpTestBase { private CSharpCompilationOptions WithDiagnosticOptions( SyntaxTree tree, params (string, ReportDiagnostic)[] options) => TestOptions.DebugDll.WithSyntaxTreeOptionsProvider(new TestSyntaxTreeOptionsProvider(tree, options)); [Fact] public void TreeDiagnosticOptionsDoNotAffectTreeDiagnostics() { #pragma warning disable CS0618 // This test is intentionally calling the obsolete method to assert the diagnosticOptions input is now ignored var tree = SyntaxFactory.ParseSyntaxTree("class C { long _f = 0l;}", options: null, path: "", encoding: null, diagnosticOptions: CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress)), cancellationToken: default); tree.GetDiagnostics().Verify( // (1,22): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 22)); #pragma warning restore CS0618 } [Fact] public void PerTreeVsGlobalSuppress() { var tree = SyntaxFactory.ParseSyntaxTree("class C { long _f = 0l;}"); var options = TestOptions.DebugDll .WithGeneralDiagnosticOption(ReportDiagnostic.Suppress); var comp = CreateCompilation(tree, options: options); comp.VerifyDiagnostics(); options = options.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider((tree, new[] { ("CS0078", ReportDiagnostic.Warn) }))); comp = CreateCompilation(tree, options: options); // Syntax tree diagnostic options override global settting comp.VerifyDiagnostics( // (1,22): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 22)); } [Fact] public void PerTreeDiagnosticOptionsParseWarnings() { var tree = SyntaxFactory.ParseSyntaxTree("class C { long _f = 0l;}"); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (1,22): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 22), // (1,16): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 16)); var options = WithDiagnosticOptions(tree, ("CS0078", ReportDiagnostic.Suppress)); comp = CreateCompilation(tree, options: options); comp.VerifyDiagnostics( // (1,16): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 16)); } [Fact] public void PerTreeDiagnosticOptionsVsPragma() { var tree = SyntaxFactory.ParseSyntaxTree(@" class C { #pragma warning disable CS0078 long _f = 0l; #pragma warning restore CS0078 }"); tree.GetDiagnostics().Verify( // (4,12): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // long _f = 0l; Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(4, 12)); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (4,6): warning CS0414: The field 'C._f' is assigned but its value is never used // long _f = 0l; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(4, 6)); var options = WithDiagnosticOptions(tree, ("CS0078", ReportDiagnostic.Error)); comp = CreateCompilation(tree, options: options); // Pragma should have precedence over per-tree options comp.VerifyDiagnostics( // (4,6): warning CS0414: The field 'C._f' is assigned but its value is never used // long _f = 0l; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(4, 6)); } [Fact] public void PerTreeDiagnosticOptionsVsSpecificOptions() { var tree = SyntaxFactory.ParseSyntaxTree("class C { long _f = 0l; }"); var options = WithDiagnosticOptions(tree, ("CS0078", ReportDiagnostic.Suppress)); var comp = CreateCompilation(tree, options: options); comp.VerifyDiagnostics( // (1,16): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 16) ); options = options.WithSpecificDiagnosticOptions( CreateImmutableDictionary(("CS0078", ReportDiagnostic.Error))); var comp2 = CreateCompilation(tree, options: options); // Specific diagnostic options have precedence over per-tree options comp2.VerifyDiagnostics( // (1,16): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 16), // (1,22): error CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 22).WithWarningAsError(true)); } [Fact] public void DifferentDiagnosticOptionsForTrees() { var tree = SyntaxFactory.ParseSyntaxTree(@" class C { long _f = 0l; }"); var newTree = SyntaxFactory.ParseSyntaxTree(@" class D { long _f = 0l; }"); var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider( (tree, new[] { ("CS0078", ReportDiagnostic.Suppress) }), (newTree, new[] { ("CS0078", ReportDiagnostic.Error) }) ) ); var comp = CreateCompilation(new[] { tree, newTree }, options: options); comp.VerifyDiagnostics( // (1,23): error CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class D { long _f = 0l; } Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 23).WithWarningAsError(true), // (1,17): warning CS0414: The field 'D._f' is assigned but its value is never used // class D { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("D._f").WithLocation(1, 17), // (1,17): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 17) ); } [Fact] public void TreeOptionsComparerRespected() { var tree = SyntaxFactory.ParseSyntaxTree(@" class C { long _f = 0l; }"); // Default options have case insensitivity var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider((tree, new[] { ("cs0078", ReportDiagnostic.Suppress) })) ); CreateCompilation(tree, options: options).VerifyDiagnostics( // (1,17): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 17) ); options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider( StringComparer.Ordinal, globalOption: default, (tree, new[] { ("cs0078", ReportDiagnostic.Suppress) })) ); CreateCompilation(tree, options: options).VerifyDiagnostics( // (1,23): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 23), // (1,17): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 17) ); } [Fact] public void WarningLevelRespectedForLexerWarnings() { var source = @"public class C { public long Field = 0l; }"; CreateCompilation(source).VerifyDiagnostics( // (1,39): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // public class C { public long Field = 0l; } Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 39) ); CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(0)).VerifyDiagnostics( ); } [WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")] [WorkItem(9153, "https://github.com/dotnet/roslyn/issues/9153")] [Fact] public void PublicSignWithRelativeKeyPath() { var options = TestOptions.DebugDll .WithPublicSign(true).WithCryptoKeyFile("test.snk"); var comp = CSharpCompilation.Create("test", options: options); comp.VerifyDiagnostics( // error CS7104: Option 'CryptoKeyFile' must be an absolute path. Diagnostic(ErrorCode.ERR_OptionMustBeAbsolutePath).WithArguments("CryptoKeyFile").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1) ); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath() { CreateCompilation("", options: TestOptions.ReleaseDll.WithPublicSign(true).WithCryptoKeyFile("")).VerifyDiagnostics( // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath2() { CreateCompilation("", options: TestOptions.ReleaseDll.WithPublicSign(true).WithCryptoKeyFile("\"\"")).VerifyDiagnostics( // error CS8106: Option 'CryptoKeyFile' must be an absolute path. Diagnostic(ErrorCode.ERR_OptionMustBeAbsolutePath).WithArguments("CryptoKeyFile").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [Fact] [WorkItem(233669, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=233669")] public void CompilationName() { // report an error, rather then silently ignoring the directory // (see cli partition II 22.30) CSharpCompilation.Create(@"C:/goo/Test.exe").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), // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1) ); CSharpCompilation.Create(@"C:\goo\Test.exe").GetDeclarationDiagnostics().Verify( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); var compilationOptions = TestOptions.DebugDll.WithWarningLevel(0); CSharpCompilation.Create(@"\goo/Test.exe", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create(@"C:Test.exe", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create(@"Te\0st.exe", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create(@" \t ", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name cannot start with whitespace. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name cannot start with whitespace.").WithLocation(1, 1) ); CSharpCompilation.Create(@"\uD800", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create(@"", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name cannot be empty. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name cannot be empty.").WithLocation(1, 1) ); CSharpCompilation.Create(@" a", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name cannot start with whitespace. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name cannot start with whitespace.").WithLocation(1, 1) ); CSharpCompilation.Create(@"\u2000a", options: compilationOptions).VerifyEmitDiagnostics( // U+20700 is whitespace // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create("..\\..\\RelativePath", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); // other characters than directory and volume separators are ok: CSharpCompilation.Create(@";,*?<>#!@&", options: compilationOptions).VerifyEmitDiagnostics(); CSharpCompilation.Create("goo", options: compilationOptions).VerifyEmitDiagnostics(); CSharpCompilation.Create(".goo", options: compilationOptions).VerifyEmitDiagnostics(); CSharpCompilation.Create("goo ", options: compilationOptions).VerifyEmitDiagnostics(); // can end with whitespace CSharpCompilation.Create("....", options: compilationOptions).VerifyEmitDiagnostics(); CSharpCompilation.Create(null, options: compilationOptions).VerifyEmitDiagnostics(); } [Fact] public void CreateAPITest() { var listSyntaxTree = new List<SyntaxTree>(); var listRef = new List<MetadataReference>(); var s1 = @"using Goo; namespace A.B { class C { class D { class E { } } } class G<T> { class Q<S1,S2> { } } class G<T1,T2> { } }"; SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree(s1); listSyntaxTree.Add(t1); // System.dll listRef.Add(Net451.System.WithEmbedInteropTypes(true)); var ops = TestOptions.ReleaseExe; // Create Compilation with Option is not null var comp = CSharpCompilation.Create("Compilation", listSyntaxTree, listRef, ops); Assert.Equal(ops, comp.Options); Assert.NotEqual(default, comp.SyntaxTrees); Assert.NotNull(comp.References); Assert.Equal(1, comp.SyntaxTrees.Length); Assert.Equal(1, comp.ExternalReferences.Length); var ref1 = comp.ExternalReferences[0]; Assert.True(ref1.Properties.EmbedInteropTypes); Assert.True(ref1.Properties.Aliases.IsEmpty); // Create Compilation with PreProcessorSymbols of Option is empty var ops1 = TestOptions.DebugExe; // Create Compilation with Assembly name contains invalid char var asmname = "ÃÃâ€Â"; comp = CSharpCompilation.Create(asmname, listSyntaxTree, listRef, ops); var comp1 = CSharpCompilation.Create(asmname, listSyntaxTree, listRef, null); } [Fact] public void EmitToNonWritableStreams() { var peStream = new TestStream(canRead: false, canSeek: false, canWrite: false); var pdbStream = new TestStream(canRead: false, canSeek: false, canWrite: false); var c = CSharpCompilation.Create("a", new[] { SyntaxFactory.ParseSyntaxTree("class C { static void Main() {} }") }, new[] { MscorlibRef }); Assert.Throws<ArgumentException>(() => c.Emit(peStream)); Assert.Throws<ArgumentException>(() => c.Emit(new MemoryStream(), pdbStream)); } [Fact] public void EmitOptionsDiagnostics() { var c = CreateCompilation("class C {}"); var stream = new MemoryStream(); var options = new EmitOptions( debugInformationFormat: (DebugInformationFormat)(-1), outputNameOverride: " ", fileAlignment: 513, subsystemVersion: SubsystemVersion.Create(1000000, -1000000), pdbChecksumAlgorithm: new HashAlgorithmName("invalid hash algorithm name")); EmitResult result = c.Emit(stream, options: options); result.Diagnostics.Verify( // error CS2042: Invalid debug information format: -1 Diagnostic(ErrorCode.ERR_InvalidDebugInformationFormat).WithArguments("-1").WithLocation(1, 1), // error CS2041: Invalid output name: Name cannot start with whitespace. Diagnostic(ErrorCode.ERR_InvalidOutputName).WithArguments("Name cannot start with whitespace.").WithLocation(1, 1), // error CS2024: Invalid file section alignment '513' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("513").WithLocation(1, 1), // error CS1773: Invalid version 1000000.-1000000 for /subsystemversion. The version must be 6.02 or greater for ARM or AppContainerExe, and 4.00 or greater otherwise Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("1000000.-1000000").WithLocation(1, 1), // error CS8113: Invalid hash algorithm name: 'invalid hash algorithm name' Diagnostic(ErrorCode.ERR_InvalidHashAlgorithmName).WithArguments("invalid hash algorithm name").WithLocation(1, 1)); Assert.False(result.Success); } [Fact] public void EmitOptions_PdbChecksumAndDeterminism() { var options = new EmitOptions(pdbChecksumAlgorithm: default(HashAlgorithmName)); var diagnosticBag = new DiagnosticBag(); options.ValidateOptions(diagnosticBag, MessageProvider.Instance, isDeterministic: true); diagnosticBag.Verify( // error CS8113: Invalid hash algorithm name: '' Diagnostic(ErrorCode.ERR_InvalidHashAlgorithmName).WithArguments("")); diagnosticBag.Clear(); options.ValidateOptions(diagnosticBag, MessageProvider.Instance, isDeterministic: false); diagnosticBag.Verify(); } [Fact] public void Emit_BadArgs() { var comp = CSharpCompilation.Create("Compilation", options: TestOptions.ReleaseDll); Assert.Throws<ArgumentNullException>("peStream", () => comp.Emit(peStream: null)); Assert.Throws<ArgumentException>("peStream", () => comp.Emit(peStream: new TestStream(canRead: true, canWrite: false, canSeek: true))); Assert.Throws<ArgumentException>("pdbStream", () => comp.Emit(peStream: new MemoryStream(), pdbStream: new TestStream(canRead: true, canWrite: false, canSeek: true))); Assert.Throws<ArgumentException>("pdbStream", () => comp.Emit(peStream: new MemoryStream(), pdbStream: new MemoryStream(), options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded))); Assert.Throws<ArgumentException>("sourceLinkStream", () => comp.Emit( peStream: new MemoryStream(), pdbStream: new MemoryStream(), options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), sourceLinkStream: new TestStream(canRead: false, canWrite: true, canSeek: true))); Assert.Throws<ArgumentException>("embeddedTexts", () => comp.Emit( peStream: new MemoryStream(), pdbStream: null, options: null, embeddedTexts: new[] { EmbeddedText.FromStream("_", new MemoryStream()) })); Assert.Throws<ArgumentException>("embeddedTexts", () => comp.Emit( peStream: new MemoryStream(), pdbStream: null, options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), embeddedTexts: new[] { EmbeddedText.FromStream("_", new MemoryStream()) })); Assert.Throws<ArgumentException>("win32Resources", () => comp.Emit( peStream: new MemoryStream(), win32Resources: new TestStream(canRead: true, canWrite: false, canSeek: false))); Assert.Throws<ArgumentException>("win32Resources", () => comp.Emit( peStream: new MemoryStream(), win32Resources: new TestStream(canRead: false, canWrite: false, canSeek: true))); // we don't report an error when we can't write to the XML doc stream: Assert.True(comp.Emit( peStream: new MemoryStream(), pdbStream: new MemoryStream(), xmlDocumentationStream: new TestStream(canRead: true, canWrite: false, canSeek: true)).Success); } [Fact] public void ReferenceAPITest() { var opt = TestOptions.DebugExe; // Create Compilation takes two args var comp = CSharpCompilation.Create("Compilation", options: TestOptions.DebugExe); var ref1 = Net451.mscorlib; var ref2 = Net451.System; var ref3 = new TestMetadataReference(fullPath: @"c:\xml.bms"); var ref4 = new TestMetadataReference(fullPath: @"c:\aaa.dll"); // Add a new empty item comp = comp.AddReferences(Enumerable.Empty<MetadataReference>()); Assert.Equal(0, comp.ExternalReferences.Length); // Add a new valid item comp = comp.AddReferences(ref1); var assemblySmb = comp.GetReferencedAssemblySymbol(ref1); Assert.NotNull(assemblySmb); Assert.Equal("mscorlib", assemblySmb.Name, StringComparer.OrdinalIgnoreCase); Assert.Equal(1, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Assembly, comp.ExternalReferences[0].Properties.Kind); Assert.Equal(ref1, comp.ExternalReferences[0]); // Replace an existing item with another valid item comp = comp.ReplaceReference(ref1, ref2); Assert.Equal(1, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Assembly, comp.ExternalReferences[0].Properties.Kind); Assert.Equal(ref2, comp.ExternalReferences[0]); // Remove an existing item comp = comp.RemoveReferences(ref2); Assert.Equal(0, comp.ExternalReferences.Length); // Overload with Hashset var hs = new HashSet<MetadataReference> { ref1, ref2, ref3 }; var compCollection = CSharpCompilation.Create("Compilation", references: hs, options: opt); compCollection = compCollection.AddReferences(ref1, ref2, ref3, ref4).RemoveReferences(hs); Assert.Equal(1, compCollection.ExternalReferences.Length); compCollection = compCollection.AddReferences(hs).RemoveReferences(ref1, ref2, ref3, ref4); Assert.Equal(0, compCollection.ExternalReferences.Length); // Overload with Collection var col = new Collection<MetadataReference> { ref1, ref2, ref3 }; compCollection = CSharpCompilation.Create("Compilation", references: col, options: opt); compCollection = compCollection.AddReferences(col).RemoveReferences(ref1, ref2, ref3); Assert.Equal(0, compCollection.ExternalReferences.Length); compCollection = compCollection.AddReferences(ref1, ref2, ref3).RemoveReferences(col); Assert.Equal(0, comp.ExternalReferences.Length); // Overload with ConcurrentStack var stack = new ConcurrentStack<MetadataReference> { }; stack.Push(ref1); stack.Push(ref2); stack.Push(ref3); compCollection = CSharpCompilation.Create("Compilation", references: stack, options: opt); compCollection = compCollection.AddReferences(stack).RemoveReferences(ref1, ref3, ref2); Assert.Equal(0, compCollection.ExternalReferences.Length); compCollection = compCollection.AddReferences(ref2, ref1, ref3).RemoveReferences(stack); Assert.Equal(0, compCollection.ExternalReferences.Length); // Overload with ConcurrentQueue var queue = new ConcurrentQueue<MetadataReference> { }; queue.Enqueue(ref1); queue.Enqueue(ref2); queue.Enqueue(ref3); compCollection = CSharpCompilation.Create("Compilation", references: queue, options: opt); compCollection = compCollection.AddReferences(queue).RemoveReferences(ref3, ref2, ref1); Assert.Equal(0, compCollection.ExternalReferences.Length); compCollection = compCollection.AddReferences(ref2, ref1, ref3).RemoveReferences(queue); Assert.Equal(0, compCollection.ExternalReferences.Length); } [Fact] public void ReferenceDirectiveTests() { var t1 = Parse(@" #r ""a.dll"" #r ""a.dll"" ", filename: "1.csx", options: TestOptions.Script); var rd1 = t1.GetRoot().GetDirectives().Cast<ReferenceDirectiveTriviaSyntax>().ToArray(); Assert.Equal(2, rd1.Length); var t2 = Parse(@" #r ""a.dll"" #r ""b.dll"" ", options: TestOptions.Script); var rd2 = t2.GetRoot().GetDirectives().Cast<ReferenceDirectiveTriviaSyntax>().ToArray(); Assert.Equal(2, rd2.Length); var t3 = Parse(@" #r ""a.dll"" ", filename: "1.csx", options: TestOptions.Script); var rd3 = t3.GetRoot().GetDirectives().Cast<ReferenceDirectiveTriviaSyntax>().ToArray(); Assert.Equal(1, rd3.Length); var t4 = Parse(@" #r ""a.dll"" ", filename: "4.csx", options: TestOptions.Script); var rd4 = t4.GetRoot().GetDirectives().Cast<ReferenceDirectiveTriviaSyntax>().ToArray(); Assert.Equal(1, rd4.Length); var c = CreateCompilationWithMscorlib45(new[] { t1, t2 }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver( new TestMetadataReferenceResolver(files: new Dictionary<string, PortableExecutableReference>() { { @"a.dll", Net451.MicrosoftCSharp }, { @"b.dll", Net451.MicrosoftVisualBasic }, }))); c.VerifyDiagnostics(); // same containing script file name and directive string Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd1[0])); Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd1[1])); Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd2[0])); Assert.Same(Net451.MicrosoftVisualBasic, c.GetDirectiveReference(rd2[1])); Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd3[0])); // different script name or directive string: Assert.Null(c.GetDirectiveReference(rd4[0])); } [Fact, WorkItem(530131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530131")] public void MetadataReferenceWithInvalidAlias() { var refcomp = CSharpCompilation.Create("DLL", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree("public class C {}") }, references: new MetadataReference[] { MscorlibRef }); var mtref = refcomp.EmitToImageReference(aliases: ImmutableArray.Create("a", "Alias(*#$@^%*&)")); // not use exported type var comp = CSharpCompilation.Create("APP", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( @"class D {}" ) }, references: new MetadataReference[] { MscorlibRef, mtref } ); Assert.Empty(comp.GetDiagnostics()); // use exported type with partial alias comp = CSharpCompilation.Create("APP1", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( @"extern alias Alias; class D : Alias::C {}" ) }, references: new MetadataReference[] { MscorlibRef, mtref } ); var errs = comp.GetDiagnostics(); // error CS0430: The extern alias 'Alias' was not specified in a /reference option Assert.Equal(430, errs.FirstOrDefault().Code); // use exported type with invalid alias comp = CSharpCompilation.Create("APP2", options: TestOptions.ReleaseExe, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( "extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {}", options: TestOptions.Regular9) }, references: new MetadataReference[] { MscorlibRef, mtref } ); comp.VerifyDiagnostics( // (1,21): error CS1040: Preprocessor directives must appear as the first non-whitespace character on a line // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_BadDirectivePlacement, "#").WithLocation(1, 21), // (1,61): error CS1026: ) expected // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(1, 61), // (1,61): error CS1002: ; expected // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 61), // (1,14): error CS8112: Local function 'Alias()' must declare a body because it is not marked 'static extern'. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Alias").WithArguments("Alias()").WithLocation(1, 14), // (1,8): error CS0246: The type or namespace name 'alias' could not be found (are you missing a using directive or an assembly reference?) // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias").WithArguments("alias").WithLocation(1, 8), // (1,14): warning CS0626: Method, operator, or accessor 'Alias()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "Alias").WithArguments("Alias()").WithLocation(1, 14), // (1,14): warning CS8321: The local function 'Alias' is declared but never used // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Alias").WithArguments("Alias").WithLocation(1, 14) ); } [Fact, WorkItem(530131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530131")] public void MetadataReferenceWithInvalidAliasWithCSharp6() { var refcomp = CSharpCompilation.Create("DLL", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree("public class C {}", options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)) }, references: new MetadataReference[] { MscorlibRef }); var mtref = refcomp.EmitToImageReference(aliases: ImmutableArray.Create("a", "Alias(*#$@^%*&)")); // not use exported type var comp = CSharpCompilation.Create("APP", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( @"class D {}", options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)) }, references: new MetadataReference[] { MscorlibRef, mtref } ); Assert.Empty(comp.GetDiagnostics()); // use exported type with partial alias comp = CSharpCompilation.Create("APP1", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( @"extern alias Alias; class D : Alias::C {}", options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)) }, references: new MetadataReference[] { MscorlibRef, mtref } ); var errs = comp.GetDiagnostics(); // error CS0430: The extern alias 'Alias' was not specified in a /reference option Assert.Equal(430, errs.FirstOrDefault().Code); // use exported type with invalid alias comp = CSharpCompilation.Create("APP2", options: TestOptions.ReleaseExe, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( "extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {}", options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)) }, references: new MetadataReference[] { MscorlibRef, mtref } ); comp.VerifyDiagnostics( // (1,1): error CS8059: Feature 'top-level statements' is not available in C# 6. Please use language version 9.0 or greater. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {}").WithArguments("top-level statements", "9.0").WithLocation(1, 1), // (1,1): error CS8059: Feature 'extern local functions' is not available in C# 6. Please use language version 9.0 or greater. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "extern").WithArguments("extern local functions", "9.0").WithLocation(1, 1), // (1,14): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "Alias").WithArguments("local functions", "7.0").WithLocation(1, 14), // (1,21): error CS1040: Preprocessor directives must appear as the first non-whitespace character on a line // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_BadDirectivePlacement, "#").WithLocation(1, 21), // (1,61): error CS1026: ) expected // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(1, 61), // (1,61): error CS1002: ; expected // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 61), // (1,14): error CS8112: Local function 'Alias()' must declare a body because it is not marked 'static extern'. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Alias").WithArguments("Alias()").WithLocation(1, 14), // (1,8): error CS0246: The type or namespace name 'alias' could not be found (are you missing a using directive or an assembly reference?) // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias").WithArguments("alias").WithLocation(1, 8), // (1,14): warning CS0626: Method, operator, or accessor 'Alias()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "Alias").WithArguments("Alias()").WithLocation(1, 14), // (1,14): warning CS8321: The local function 'Alias' is declared but never used // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Alias").WithArguments("Alias").WithLocation(1, 14) ); } [Fact] public void SyntreeAPITest() { var s1 = "namespace System.Linq {}"; var s2 = @" namespace NA.NB { partial class C<T> { public partial class D { intttt F; } } class C { } } "; var s3 = @"int x;"; var s4 = @"Imports System "; var s5 = @" class D { public static int Goo() { long l = 25l; return 0; } } "; SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree(s1); SyntaxTree withErrorTree = SyntaxFactory.ParseSyntaxTree(s2); SyntaxTree withErrorTree1 = SyntaxFactory.ParseSyntaxTree(s3); SyntaxTree withErrorTreeVB = SyntaxFactory.ParseSyntaxTree(s4); SyntaxTree withExpressionRootTree = SyntaxFactory.ParseExpression(s3).SyntaxTree; var withWarning = SyntaxFactory.ParseSyntaxTree(s5); // Create compilation takes three args var comp = CSharpCompilation.Create("Compilation", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(s1) }, options: TestOptions.ReleaseDll); comp = comp.AddSyntaxTrees(t1, withErrorTree, withErrorTree1, withErrorTreeVB); Assert.Equal(5, comp.SyntaxTrees.Length); comp = comp.RemoveSyntaxTrees(t1, withErrorTree, withErrorTree1, withErrorTreeVB); Assert.Equal(1, comp.SyntaxTrees.Length); // Add a new empty item comp = comp.AddSyntaxTrees(Enumerable.Empty<SyntaxTree>()); Assert.Equal(1, comp.SyntaxTrees.Length); // Add a new valid item comp = comp.AddSyntaxTrees(t1); Assert.Equal(2, comp.SyntaxTrees.Length); Assert.Contains(t1, comp.SyntaxTrees); Assert.False(comp.SyntaxTrees.Contains(SyntaxFactory.ParseSyntaxTree(s1))); comp = comp.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(s1)); Assert.Equal(3, comp.SyntaxTrees.Length); // Replace an existing item with another valid item comp = comp.ReplaceSyntaxTree(t1, SyntaxFactory.ParseSyntaxTree(s1)); Assert.Equal(3, comp.SyntaxTrees.Length); // Replace an existing item with same item comp = comp.AddSyntaxTrees(t1).ReplaceSyntaxTree(t1, t1); Assert.Equal(4, comp.SyntaxTrees.Length); // add again and verify that it throws Assert.Throws<ArgumentException>(() => comp.AddSyntaxTrees(t1)); // replace with existing and verify that it throws Assert.Throws<ArgumentException>(() => comp.ReplaceSyntaxTree(t1, comp.SyntaxTrees[0])); // SyntaxTrees have reference equality. This removal should fail. Assert.Throws<ArgumentException>(() => comp = comp.RemoveSyntaxTrees(SyntaxFactory.ParseSyntaxTree(s1))); Assert.Equal(4, comp.SyntaxTrees.Length); // Remove non-existing item Assert.Throws<ArgumentException>(() => comp = comp.RemoveSyntaxTrees(withErrorTree)); Assert.Equal(4, comp.SyntaxTrees.Length); // Add syntaxtree with error comp = comp.AddSyntaxTrees(withErrorTree1); var error = comp.GetDiagnostics(); Assert.InRange(comp.GetDiagnostics().Count(), 0, int.MaxValue); Assert.InRange(comp.GetDeclarationDiagnostics().Count(), 0, int.MaxValue); Assert.True(comp.SyntaxTrees.Contains(t1)); SyntaxTree t4 = SyntaxFactory.ParseSyntaxTree("Using System;"); SyntaxTree t5 = SyntaxFactory.ParseSyntaxTree("Usingsssssssssssss System;"); SyntaxTree t6 = SyntaxFactory.ParseSyntaxTree("Import System;"); // Overload with Hashset var hs = new HashSet<SyntaxTree> { t4, t5, t6 }; var compCollection = CSharpCompilation.Create("Compilation", syntaxTrees: hs); compCollection = compCollection.RemoveSyntaxTrees(hs); Assert.Equal(0, compCollection.SyntaxTrees.Length); compCollection = compCollection.AddSyntaxTrees(hs).RemoveSyntaxTrees(t4, t5, t6); Assert.Equal(0, compCollection.SyntaxTrees.Length); // Overload with Collection var col = new Collection<SyntaxTree> { t4, t5, t6 }; compCollection = CSharpCompilation.Create("Compilation", syntaxTrees: col); compCollection = compCollection.RemoveSyntaxTrees(t4, t5, t6); Assert.Equal(0, compCollection.SyntaxTrees.Length); Assert.Throws<ArgumentException>(() => compCollection = compCollection.AddSyntaxTrees(t4, t5).RemoveSyntaxTrees(col)); Assert.Equal(0, compCollection.SyntaxTrees.Length); // Overload with ConcurrentStack var stack = new ConcurrentStack<SyntaxTree> { }; stack.Push(t4); stack.Push(t5); stack.Push(t6); compCollection = CSharpCompilation.Create("Compilation", syntaxTrees: stack); compCollection = compCollection.RemoveSyntaxTrees(t4, t6, t5); Assert.Equal(0, compCollection.SyntaxTrees.Length); Assert.Throws<ArgumentException>(() => compCollection = compCollection.AddSyntaxTrees(t4, t6).RemoveSyntaxTrees(stack)); Assert.Equal(0, compCollection.SyntaxTrees.Length); // Overload with ConcurrentQueue var queue = new ConcurrentQueue<SyntaxTree> { }; queue.Enqueue(t4); queue.Enqueue(t5); queue.Enqueue(t6); compCollection = CSharpCompilation.Create("Compilation", syntaxTrees: queue); compCollection = compCollection.RemoveSyntaxTrees(t4, t6, t5); Assert.Equal(0, compCollection.SyntaxTrees.Length); Assert.Throws<ArgumentException>(() => compCollection = compCollection.AddSyntaxTrees(t4, t6).RemoveSyntaxTrees(queue)); Assert.Equal(0, compCollection.SyntaxTrees.Length); // Get valid binding var bind = comp.GetSemanticModel(syntaxTree: t1); Assert.Equal(t1, bind.SyntaxTree); Assert.Equal("C#", bind.Language); // Remove syntaxtree without error comp = comp.RemoveSyntaxTrees(t1); Assert.InRange(comp.GetDiagnostics().Count(), 0, int.MaxValue); // Remove syntaxtree with error comp = comp.RemoveSyntaxTrees(withErrorTree1); var e = comp.GetDiagnostics(cancellationToken: default(CancellationToken)); Assert.Equal(0, comp.GetDiagnostics(cancellationToken: default(CancellationToken)).Count()); // Add syntaxtree which is VB language comp = comp.AddSyntaxTrees(withErrorTreeVB); error = comp.GetDiagnostics(cancellationToken: CancellationToken.None); Assert.InRange(comp.GetDiagnostics().Count(), 0, int.MaxValue); comp = comp.RemoveSyntaxTrees(withErrorTreeVB); Assert.Equal(0, comp.GetDiagnostics().Count()); // Add syntaxtree with error comp = comp.AddSyntaxTrees(withWarning); error = comp.GetDeclarationDiagnostics(); Assert.InRange(error.Count(), 1, int.MaxValue); comp = comp.RemoveSyntaxTrees(withWarning); Assert.Equal(0, comp.GetDiagnostics().Count()); // Compilation.Create with syntaxtree with a non-CompilationUnit root node: should throw an ArgumentException. Assert.False(withExpressionRootTree.HasCompilationUnitRoot, "how did we get a CompilationUnit root?"); Assert.Throws<ArgumentException>(() => CSharpCompilation.Create("Compilation", new SyntaxTree[] { withExpressionRootTree })); // AddSyntaxTrees with a non-CompilationUnit root node: should throw an ArgumentException. Assert.Throws<ArgumentException>(() => comp.AddSyntaxTrees(withExpressionRootTree)); // ReplaceSyntaxTrees syntaxtree with a non-CompilationUnit root node: should throw an ArgumentException. Assert.Throws<ArgumentException>(() => comp.ReplaceSyntaxTree(comp.SyntaxTrees[0], withExpressionRootTree)); } [Fact] public void ChainedOperations() { var s1 = "using System.Linq;"; var s2 = ""; var s3 = "Import System"; SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree(s1); SyntaxTree t2 = SyntaxFactory.ParseSyntaxTree(s2); SyntaxTree t3 = SyntaxFactory.ParseSyntaxTree(s3); var listSyntaxTree = new List<SyntaxTree>(); listSyntaxTree.Add(t1); listSyntaxTree.Add(t2); // Remove second SyntaxTree CSharpCompilation comp = CSharpCompilation.Create(options: TestOptions.ReleaseDll, assemblyName: "Compilation", references: null, syntaxTrees: null); comp = comp.AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(t2); Assert.Equal(1, comp.SyntaxTrees.Length); // Remove mid SyntaxTree listSyntaxTree.Add(t3); comp = comp.RemoveSyntaxTrees(t1).AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(t2); Assert.Equal(2, comp.SyntaxTrees.Length); // remove list listSyntaxTree.Remove(t2); comp = comp.AddSyntaxTrees().RemoveSyntaxTrees(listSyntaxTree); comp = comp.AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(listSyntaxTree); Assert.Equal(0, comp.SyntaxTrees.Length); listSyntaxTree.Clear(); listSyntaxTree.Add(t1); listSyntaxTree.Add(t1); // Chained operation count > 2 Assert.Throws<ArgumentException>(() => comp = comp.AddSyntaxTrees(listSyntaxTree).AddReferences().ReplaceSyntaxTree(t1, t2)); comp = comp.AddSyntaxTrees(t1).AddReferences().ReplaceSyntaxTree(t1, t2); Assert.Equal(1, comp.SyntaxTrees.Length); Assert.Equal(0, comp.ExternalReferences.Length); // Create compilation with args is disordered CSharpCompilation comp1 = CSharpCompilation.Create(assemblyName: "Compilation", syntaxTrees: null, options: TestOptions.ReleaseDll, references: null); var ref1 = Net451.mscorlib; var listRef = new List<MetadataReference>(); listRef.Add(ref1); listRef.Add(ref1); // Remove with no args comp1 = comp1.AddReferences(listRef).AddSyntaxTrees(t1).RemoveReferences().RemoveSyntaxTrees(); Assert.Equal(1, comp1.ExternalReferences.Length); Assert.Equal(1, comp1.SyntaxTrees.Length); } [WorkItem(713356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713356")] [ClrOnlyFact] public void MissedModuleA() { var netModule1 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", source: new string[] { "public class C1 {}" }); netModule1.VerifyEmitDiagnostics(); var netModule2 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a2", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C2 { public static void M() { var a = new C1(); } }" }); netModule2.VerifyEmitDiagnostics(); var assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule2.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics( Diagnostic(ErrorCode.ERR_MissingNetModuleReference).WithArguments("a1.netmodule")); assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule1.EmitToImageReference(), netModule2.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics(); CompileAndVerify(assembly); } [WorkItem(713356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713356")] [Fact] public void MissedModuleB_OneError() { var netModule1 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", source: new string[] { "public class C1 {}" }); netModule1.VerifyEmitDiagnostics(); var netModule2 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a2", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C2 { public static void M() { var a = new C1(); } }" }); netModule2.VerifyEmitDiagnostics(); var netModule3 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a3", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C2a { public static void M() { var a = new C1(); } }" }); netModule3.VerifyEmitDiagnostics(); var assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule2.EmitToImageReference(), netModule3.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics( Diagnostic(ErrorCode.ERR_MissingNetModuleReference).WithArguments("a1.netmodule")); } [WorkItem(718500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718500")] [WorkItem(716762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716762")] [Fact] public void MissedModuleB_NoErrorForUnmanagedModules() { var netModule1 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", source: new string[] { @" using System; using System.Runtime.InteropServices; public class C2 { [DllImport(""user32.dll"", CharSet = CharSet.Unicode)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); }" }); netModule1.VerifyEmitDiagnostics(); var assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics(); } [WorkItem(715872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715872")] [Fact] public void MissedModuleC() { var netModule1 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", source: new string[] { "public class C1 {}" }); netModule1.VerifyEmitDiagnostics(); var netModule2 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C2 { public static void M() { var a = new C1(); } }" }); netModule2.VerifyEmitDiagnostics(); var assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule1.EmitToImageReference(), netModule2.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics(Diagnostic(ErrorCode.ERR_NetModuleNameMustBeUnique).WithArguments("a1.netmodule")); } [Fact] public void MixedRefType() { var vbComp = VB.VisualBasicCompilation.Create("CompilationVB"); var comp = CSharpCompilation.Create("Compilation"); vbComp = vbComp.AddReferences(SystemRef); // Add VB reference to C# compilation foreach (var item in vbComp.References) { comp = comp.AddReferences(item); comp = comp.ReplaceReference(item, item); } Assert.Equal(1, comp.ExternalReferences.Length); var text1 = @"class A {}"; var comp1 = CSharpCompilation.Create("Test1", new[] { SyntaxFactory.ParseSyntaxTree(text1) }); var comp2 = CSharpCompilation.Create("Test2", new[] { SyntaxFactory.ParseSyntaxTree(text1) }); var compRef1 = comp1.ToMetadataReference(); var compRef2 = comp2.ToMetadataReference(); var compRef = vbComp.ToMetadataReference(embedInteropTypes: true); var ref1 = Net451.mscorlib; var ref2 = Net451.System; // Add CompilationReference comp = CSharpCompilation.Create( "Test1", new[] { SyntaxFactory.ParseSyntaxTree(text1) }, new MetadataReference[] { compRef1, compRef2 }); Assert.Equal(2, comp.ExternalReferences.Length); Assert.True(comp.References.Contains(compRef1)); Assert.True(comp.References.Contains(compRef2)); var smb = comp.GetReferencedAssemblySymbol(compRef1); Assert.Equal(SymbolKind.Assembly, smb.Kind); Assert.Equal("Test1", smb.Identity.Name, StringComparer.OrdinalIgnoreCase); // Mixed reference type comp = comp.AddReferences(ref1); Assert.Equal(3, comp.ExternalReferences.Length); Assert.True(comp.References.Contains(ref1)); // Replace Compilation reference with Assembly file reference comp = comp.ReplaceReference(compRef2, ref2); Assert.Equal(3, comp.ExternalReferences.Length); Assert.True(comp.References.Contains(ref2)); // Replace Assembly file reference with Compilation reference comp = comp.ReplaceReference(ref1, compRef2); Assert.Equal(3, comp.ExternalReferences.Length); Assert.True(comp.References.Contains(compRef2)); var modRef1 = TestReferences.MetadataTests.NetModule01.ModuleCS00; // Add Module file reference comp = comp.AddReferences(modRef1); // Not implemented code //var modSmb = comp.GetReferencedModuleSymbol(modRef1); //Assert.Equal("ModuleCS00.mod", modSmb.Name); //Assert.Equal(4, comp.References.Count); //Assert.True(comp.References.Contains(modRef1)); //smb = comp.GetReferencedAssemblySymbol(reference: modRef1); //Assert.Equal(smb.Kind, SymbolKind.Assembly); //Assert.Equal("Test1", smb.Identity.Name, StringComparer.OrdinalIgnoreCase); // GetCompilationNamespace Not implemented(Derived Class AssemblySymbol) //var m = smb.GlobalNamespace.GetMembers(); //var nsSmb = smb.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; //var ns = comp.GetCompilationNamespace(ns: nsSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); //var asbSmb = smb as Symbol; //var ns1 = comp.GetCompilationNamespace(ns: asbSmb as NamespaceSymbol); //Assert.Equal(ns1.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns1.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // Get Referenced Module Symbol //var moduleSmb = comp.GetReferencedModuleSymbol(reference: modRef1); //Assert.Equal(SymbolKind.NetModule, moduleSmb.Kind); //Assert.Equal("ModuleCS00.mod", moduleSmb.Name, StringComparer.OrdinalIgnoreCase); // GetCompilationNamespace Not implemented(Derived Class ModuleSymbol) //nsSmb = moduleSmb.GlobalNamespace.GetMembers("Runtime").Single() as NamespaceSymbol; //ns = comp.GetCompilationNamespace(ns: nsSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); //var modSmbol = moduleSmb as Symbol; //ns1 = comp.GetCompilationNamespace(ns: modSmbol as NamespaceSymbol); //Assert.Equal(ns1.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns1.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // Get Compilation Namespace //nsSmb = comp.GlobalNamespace; //ns = comp.GetCompilationNamespace(ns: nsSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // GetCompilationNamespace Not implemented(Derived Class MergedNamespaceSymbol) //NamespaceSymbol merged = MergedNamespaceSymbol.Create(new NamespaceExtent(new MockAssemblySymbol("Merged")), null, null); //ns = comp.GetCompilationNamespace(ns: merged); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // GetCompilationNamespace Not implemented(Derived Class RetargetingNamespaceSymbol) //Retargeting.RetargetingNamespaceSymbol retargetSmb = nsSmb as Retargeting.RetargetingNamespaceSymbol; //ns = comp.GetCompilationNamespace(ns: retargetSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // GetCompilationNamespace Not implemented(Derived Class PENamespaceSymbol) //Symbols.Metadata.PE.PENamespaceSymbol pensSmb = nsSmb as Symbols.Metadata.PE.PENamespaceSymbol; //ns = comp.GetCompilationNamespace(ns: pensSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // Replace Module file reference with compilation reference comp = comp.RemoveReferences(compRef1).ReplaceReference(modRef1, compRef1); Assert.Equal(3, comp.ExternalReferences.Length); // Check the reference order after replace Assert.True(comp.ExternalReferences[2] is CSharpCompilationReference, "Expected compilation reference"); Assert.Equal(compRef1, comp.ExternalReferences[2]); // Replace compilation Module file reference with Module file reference comp = comp.ReplaceReference(compRef1, modRef1); // Check the reference order after replace Assert.Equal(3, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Module, comp.ExternalReferences[2].Properties.Kind); Assert.Equal(modRef1, comp.ExternalReferences[2]); // Add VB compilation ref Assert.Throws<ArgumentException>(() => comp.AddReferences(compRef)); foreach (var item in comp.References) { comp = comp.RemoveReferences(item); } Assert.Equal(0, comp.ExternalReferences.Length); // Not Implemented // var asmByteRef = MetadataReference.CreateFromImage(new byte[5], embedInteropTypes: true); //var asmObjectRef = new AssemblyObjectReference(assembly: System.Reflection.Assembly.GetAssembly(typeof(object)),embedInteropTypes :true); //comp =comp.AddReferences(asmByteRef, asmObjectRef); //Assert.Equal(2, comp.References.Count); //Assert.Equal(ReferenceKind.AssemblyBytes, comp.References[0].Kind); //Assert.Equal(ReferenceKind.AssemblyObject , comp.References[1].Kind); //Assert.Equal(asmByteRef, comp.References[0]); //Assert.Equal(asmObjectRef, comp.References[1]); //Assert.True(comp.References[0].EmbedInteropTypes); //Assert.True(comp.References[1].EmbedInteropTypes); } [Fact] public void NegGetCompilationNamespace() { var comp = CSharpCompilation.Create("Compilation"); // Throw exception when the parameter of GetCompilationNamespace is null Assert.Throws<NullReferenceException>( delegate { comp.GetCompilationNamespace(namespaceSymbol: (INamespaceSymbol)null); }); Assert.Throws<NullReferenceException>( delegate { comp.GetCompilationNamespace(namespaceSymbol: (NamespaceSymbol)null); }); } [WorkItem(537623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537623")] [Fact] public void NegCreateCompilation() { Assert.Throws<ArgumentNullException>(() => CSharpCompilation.Create("goo", syntaxTrees: new SyntaxTree[] { null })); Assert.Throws<ArgumentNullException>(() => CSharpCompilation.Create("goo", references: new MetadataReference[] { null })); } [WorkItem(537637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537637")] [Fact] public void NegGetSymbol() { // Create Compilation with miss mid args var comp = CSharpCompilation.Create("Compilation"); Assert.Null(comp.GetReferencedAssemblySymbol(reference: MscorlibRef)); var modRef1 = TestReferences.MetadataTests.NetModule01.ModuleCS00; // Get not exist Referenced Module Symbol Assert.Null(comp.GetReferencedModuleSymbol(modRef1)); // Throw exception when the parameter of GetReferencedAssemblySymbol is null Assert.Throws<ArgumentNullException>( delegate { comp.GetReferencedAssemblySymbol(null); }); // Throw exception when the parameter of GetReferencedModuleSymbol is null Assert.Throws<ArgumentNullException>( delegate { var modSmb1 = comp.GetReferencedModuleSymbol(null); }); } [WorkItem(537778, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537778")] // Throw exception when the parameter of the parameter type of GetReferencedAssemblySymbol is VB.CompilationReference [Fact] public void NegGetSymbol1() { var opt = TestOptions.ReleaseDll; var comp = CSharpCompilation.Create("Compilation"); var vbComp = VB.VisualBasicCompilation.Create("CompilationVB"); vbComp = vbComp.AddReferences(SystemRef); var compRef = vbComp.ToMetadataReference(); Assert.Throws<ArgumentException>(() => comp.AddReferences(compRef)); // Throw exception when the parameter of GetBinding is null Assert.Throws<ArgumentNullException>( delegate { comp.GetSemanticModel(null); }); // Throw exception when the parameter of GetTypeByNameAndArity is NULL //Assert.Throws<Exception>( //delegate //{ // comp.GetTypeByNameAndArity(fullName: null, arity: 1); //}); // Throw exception when the parameter of GetTypeByNameAndArity is less than 0 //Assert.Throws<Exception>( //delegate //{ // comp.GetTypeByNameAndArity(string.Empty, -4); //}); } // Add already existing item [Fact, WorkItem(537574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537574")] public void NegReference2() { var ref1 = Net451.mscorlib; var ref2 = Net451.System; var ref3 = Net451.SystemData; var ref4 = Net451.SystemXml; var comp = CSharpCompilation.Create("Compilation"); comp = comp.AddReferences(ref1, ref1); Assert.Equal(1, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Assembly, comp.ExternalReferences[0].Properties.Kind); Assert.Equal(ref1, comp.ExternalReferences[0]); var listRef = new List<MetadataReference> { ref1, ref2, ref3, ref4 }; // Chained operation count > 3 // ReplaceReference throws if the reference to be replaced is not found. comp = comp.AddReferences(listRef).AddReferences(ref2).RemoveReferences(ref1, ref3, ref4).ReplaceReference(ref2, ref2); Assert.Equal(1, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Assembly, comp.ExternalReferences[0].Properties.Kind); Assert.Equal(ref2, comp.ExternalReferences[0]); Assert.Throws<ArgumentException>(() => comp.AddReferences(listRef).AddReferences(ref2).RemoveReferences(ref1, ref2, ref3, ref4).ReplaceReference(ref2, ref2)); } // Add a new invalid item [Fact, WorkItem(537575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537575")] public void NegReference3() { var ref1 = InvalidRef; var comp = CSharpCompilation.Create("Compilation"); // Remove non-existing item Assert.Throws<ArgumentException>(() => comp = comp.RemoveReferences(ref1)); // Add a new invalid item comp = comp.AddReferences(ref1); Assert.Equal(1, comp.ExternalReferences.Length); // Replace a non-existing item with another invalid item Assert.Throws<ArgumentException>(() => comp = comp.ReplaceReference(MscorlibRef, ref1)); Assert.Equal(1, comp.ExternalReferences.Length); } // Replace a non-existing item with null [Fact, WorkItem(537567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537567")] public void NegReference4() { var ref1 = Net451.mscorlib; var comp = CSharpCompilation.Create("Compilation"); Assert.Throws<ArgumentException>( delegate { comp = comp.ReplaceReference(ref1, null); }); // Replace null and the arg order of replace is vise Assert.Throws<ArgumentNullException>( delegate { comp = comp.ReplaceReference(newReference: ref1, oldReference: null); }); } // Replace a non-existing item with another valid item [Fact, WorkItem(537566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537566")] public void NegReference5() { var ref1 = Net451.mscorlib; var ref2 = Net451.SystemXml; var comp = CSharpCompilation.Create("Compilation"); Assert.Throws<ArgumentException>( delegate { comp = comp.ReplaceReference(ref1, ref2); }); SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree("Using System;"); // Replace a non-existing item with another valid item and disorder the args Assert.Throws<ArgumentException>( delegate { comp.ReplaceReference(newReference: Net451.System, oldReference: ref2); }); Assert.Equal(0, comp.SyntaxTrees.Length); Assert.Throws<ArgumentException>(() => comp.ReplaceSyntaxTree(newTree: SyntaxFactory.ParseSyntaxTree("Using System;"), oldTree: t1)); Assert.Equal(0, comp.SyntaxTrees.Length); } [WorkItem(527256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527256")] // Throw exception when the parameter of SyntaxTrees.Contains is null [Fact] public void NegSyntaxTreesContains() { var comp = CSharpCompilation.Create("Compilation"); Assert.False(comp.SyntaxTrees.Contains(null)); } [WorkItem(537784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537784")] // Throw exception when the parameter of GetSpecialType() is out of range [Fact] public void NegGetSpecialType() { var comp = CSharpCompilation.Create("Compilation"); // Throw exception when the parameter of GetBinding is out of range Assert.Throws<ArgumentOutOfRangeException>( delegate { comp.GetSpecialType((SpecialType)100); }); Assert.Throws<ArgumentOutOfRangeException>( delegate { comp.GetSpecialType(SpecialType.None); }); Assert.Throws<ArgumentOutOfRangeException>( delegate { comp.GetSpecialType((SpecialType)000); }); Assert.Throws<ArgumentOutOfRangeException>( delegate { comp.GetSpecialType(default(SpecialType)); }); } [WorkItem(538168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538168")] // Replace a non-existing item with another valid item and disorder the args [Fact] public void NegTree2() { var comp = CSharpCompilation.Create("API"); SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree("Using System;"); Assert.Throws<ArgumentException>( delegate { comp = comp.ReplaceSyntaxTree(newTree: SyntaxFactory.ParseSyntaxTree("Using System;"), oldTree: t1); }); } [WorkItem(537576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537576")] // Add already existing item [Fact] public void NegSynTree1() { var comp = CSharpCompilation.Create("Compilation"); SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree("Using System;"); Assert.Throws<ArgumentException>(() => (comp.AddSyntaxTrees(t1, t1))); Assert.Equal(0, comp.SyntaxTrees.Length); } [Fact] public void NegSynTree() { var comp = CSharpCompilation.Create("Compilation"); SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("Using Goo;"); // Throw exception when add null SyntaxTree Assert.Throws<ArgumentNullException>( delegate { comp.AddSyntaxTrees(null); }); // Throw exception when Remove null SyntaxTree Assert.Throws<ArgumentNullException>( delegate { comp.RemoveSyntaxTrees(null); }); // No exception when replacing a SyntaxTree with null var compP = comp.AddSyntaxTrees(syntaxTree); comp = compP.ReplaceSyntaxTree(syntaxTree, null); Assert.Equal(0, comp.SyntaxTrees.Length); // Throw exception when remove null SyntaxTree Assert.Throws<ArgumentNullException>( delegate { comp = comp.ReplaceSyntaxTree(null, syntaxTree); }); var s1 = "Imports System.Text"; SyntaxTree t1 = VB.VisualBasicSyntaxTree.ParseText(s1); SyntaxTree t2 = t1; var t3 = t2; var vbComp = VB.VisualBasicCompilation.Create("CompilationVB"); vbComp = vbComp.AddSyntaxTrees(t1, VB.VisualBasicSyntaxTree.ParseText("Using Goo;")); // Throw exception when cast SyntaxTree foreach (var item in vbComp.SyntaxTrees) { t3 = item; Exception invalidCastSynTreeEx = Assert.Throws<InvalidCastException>( delegate { comp = comp.AddSyntaxTrees(t3); }); invalidCastSynTreeEx = Assert.Throws<InvalidCastException>( delegate { comp = comp.RemoveSyntaxTrees(t3); }); invalidCastSynTreeEx = Assert.Throws<InvalidCastException>( delegate { comp = comp.ReplaceSyntaxTree(t3, t3); }); } // Get Binding with tree is not exist SyntaxTree t4 = SyntaxFactory.ParseSyntaxTree(s1); Assert.Throws<ArgumentException>( delegate { comp.RemoveSyntaxTrees(new SyntaxTree[] { t4 }).GetSemanticModel(t4); }); } [Fact] public void GetEntryPoint_Exe() { var source = @" class A { static void Main() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var mainMethod = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<MethodSymbol>("Main"); Assert.Equal(mainMethod, compilation.GetEntryPoint(default(CancellationToken))); var entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(mainMethod, entryPointAndDiagnostics.MethodSymbol); entryPointAndDiagnostics.Diagnostics.Verify(); } [Fact] public void GetEntryPoint_Dll() { var source = @" class A { static void Main() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); Assert.Null(compilation.GetEntryPoint(default(CancellationToken))); Assert.Same(CSharpCompilation.EntryPoint.None, compilation.GetEntryPointAndDiagnostics(default(CancellationToken))); } [Fact] public void GetEntryPoint_Module() { var source = @" class A { static void Main() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseModule); compilation.VerifyDiagnostics(); Assert.Null(compilation.GetEntryPoint(default(CancellationToken))); Assert.Same(CSharpCompilation.EntryPoint.None, compilation.GetEntryPointAndDiagnostics(default(CancellationToken))); } [Fact] public void CreateCompilationForModule() { var source = @" class A { static void Main() { } } "; // equivalent of csc with no /moduleassemblyname specified: var compilation = CSharpCompilation.Create(assemblyName: null, options: TestOptions.ReleaseModule, syntaxTrees: new[] { Parse(source) }, references: new[] { MscorlibRef }); compilation.VerifyEmitDiagnostics(); Assert.Null(compilation.AssemblyName); Assert.Equal("?", compilation.Assembly.Name); Assert.Equal("?", compilation.Assembly.Identity.Name); // no name is allowed for assembly as well, although it isn't useful: compilation = CSharpCompilation.Create(assemblyName: null, options: TestOptions.ReleaseDll, syntaxTrees: new[] { Parse(source) }, references: new[] { MscorlibRef }); compilation.VerifyEmitDiagnostics(); Assert.Null(compilation.AssemblyName); Assert.Equal("?", compilation.Assembly.Name); Assert.Equal("?", compilation.Assembly.Identity.Name); // equivalent of csc with /moduleassemblyname specified: compilation = CSharpCompilation.Create(assemblyName: "ModuleAssemblyName", options: TestOptions.ReleaseModule, syntaxTrees: new[] { Parse(source) }, references: new[] { MscorlibRef }); compilation.VerifyDiagnostics(); Assert.Equal("ModuleAssemblyName", compilation.AssemblyName); Assert.Equal("ModuleAssemblyName", compilation.Assembly.Name); Assert.Equal("ModuleAssemblyName", compilation.Assembly.Identity.Name); } [WorkItem(8506, "https://github.com/dotnet/roslyn/issues/8506")] [WorkItem(17403, "https://github.com/dotnet/roslyn/issues/17403")] [Fact] public void CrossCorlibSystemObjectReturnType_Script() { // MinAsyncCorlibRef corlib is used since it provides just enough corlib type definitions // and Task APIs necessary for script hosting are provided by MinAsyncRef. This ensures that // `System.Object, mscorlib, Version=4.0.0.0` will not be provided (since it's unversioned). // // In the original bug, Xamarin iOS, Android, and Mac Mobile profile corlibs were // realistic cross-compilation targets. void AssertCompilationCorlib(CSharpCompilation compilation) { Assert.True(compilation.IsSubmission); var taskOfT = compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T); var taskOfObject = taskOfT.Construct(compilation.ObjectType); var entryPoint = compilation.GetEntryPoint(default(CancellationToken)); Assert.Same(compilation.ObjectType.ContainingAssembly, taskOfT.ContainingAssembly); Assert.Same(compilation.ObjectType.ContainingAssembly, taskOfObject.ContainingAssembly); Assert.Equal(taskOfObject, entryPoint.ReturnType); } var firstCompilation = CSharpCompilation.CreateScriptCompilation( "submission-assembly-1", references: new[] { MinAsyncCorlibRef }, syntaxTree: Parse("true", options: TestOptions.Script) ).VerifyDiagnostics(); AssertCompilationCorlib(firstCompilation); var secondCompilation = CSharpCompilation.CreateScriptCompilation( "submission-assembly-2", previousScriptCompilation: firstCompilation, syntaxTree: Parse("false", options: TestOptions.Script)) .WithScriptCompilationInfo(new CSharpScriptCompilationInfo(firstCompilation, null, null)) .VerifyDiagnostics(); AssertCompilationCorlib(secondCompilation); Assert.Same(firstCompilation.ObjectType, secondCompilation.ObjectType); Assert.Null(new CSharpScriptCompilationInfo(null, null, null) .WithPreviousScriptCompilation(firstCompilation) .ReturnTypeOpt); } [WorkItem(3719, "https://github.com/dotnet/roslyn/issues/3719")] [Fact] public void GetEntryPoint_Script() { var source = @"System.Console.WriteLine(1);"; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Script); compilation.VerifyDiagnostics(); var scriptMethod = compilation.GetMember<MethodSymbol>("Script.<Main>"); Assert.NotNull(scriptMethod); var method = compilation.GetEntryPoint(default(CancellationToken)); Assert.Equal(method, scriptMethod); var entryPoint = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(entryPoint.MethodSymbol, scriptMethod); } [Fact] public void GetEntryPoint_Script_MainIgnored() { var source = @" class A { static void Main() { } } "; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,17): warning CS7022: The entry point of the program is global script code; ignoring 'A.Main()' entry point. // static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("A.Main()").WithLocation(4, 17)); var scriptMethod = compilation.GetMember<MethodSymbol>("Script.<Main>"); Assert.NotNull(scriptMethod); var entryPoint = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(entryPoint.MethodSymbol, scriptMethod); entryPoint.Diagnostics.Verify( // (4,17): warning CS7022: The entry point of the program is global script code; ignoring 'A.Main()' entry point. // static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("A.Main()").WithLocation(4, 17)); } [Fact] public void GetEntryPoint_Submission() { var source = @"1 + 1"; var compilation = CSharpCompilation.CreateScriptCompilation("sub", references: new[] { MscorlibRef }, syntaxTree: Parse(source, options: TestOptions.Script)); compilation.VerifyDiagnostics(); var scriptMethod = compilation.GetMember<MethodSymbol>("Script.<Factory>"); Assert.NotNull(scriptMethod); var method = compilation.GetEntryPoint(default(CancellationToken)); Assert.Equal(method, scriptMethod); var entryPoint = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(entryPoint.MethodSymbol, scriptMethod); entryPoint.Diagnostics.Verify(); } [Fact] public void GetEntryPoint_Submission_MainIgnored() { var source = @" class A { static void Main() { } } "; var compilation = CSharpCompilation.CreateScriptCompilation("sub", references: new[] { MscorlibRef }, syntaxTree: Parse(source, options: TestOptions.Script)); compilation.VerifyDiagnostics( // (4,17): warning CS7022: The entry point of the program is global script code; ignoring 'A.Main()' entry point. // static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("A.Main()").WithLocation(4, 17)); Assert.True(compilation.IsSubmission); var scriptMethod = compilation.GetMember<MethodSymbol>("Script.<Factory>"); Assert.NotNull(scriptMethod); var entryPoint = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(entryPoint.MethodSymbol, scriptMethod); entryPoint.Diagnostics.Verify( // (4,17): warning CS7022: The entry point of the program is global script code; ignoring 'A.Main()' entry point. // static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("A.Main()").WithLocation(4, 17)); } [Fact] public void GetEntryPoint_MainType() { var source = @" class A { static void Main() { } } class B { static void Main() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithMainTypeName("B")); compilation.VerifyDiagnostics(); var mainMethod = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMember<MethodSymbol>("Main"); Assert.Equal(mainMethod, compilation.GetEntryPoint(default(CancellationToken))); var entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(mainMethod, entryPointAndDiagnostics.MethodSymbol); entryPointAndDiagnostics.Diagnostics.Verify(); } [Fact] public void CanReadAndWriteDefaultWin32Res() { var comp = CSharpCompilation.Create("Compilation"); var mft = new MemoryStream(new byte[] { 0, 1, 2, 3, }); var res = comp.CreateDefaultWin32Resources(true, false, mft, null); var list = comp.MakeWin32ResourceList(res, new DiagnosticBag()); Assert.Equal(2, list.Count); } [Fact, WorkItem(750437, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750437")] public void ConflictingAliases() { var alias = Net451.System.WithAliases(new[] { "alias" }); var text = @"extern alias alias; using alias=alias; class myClass : alias::Uri { }"; var comp = CreateEmptyCompilation(text, references: new[] { MscorlibRef, alias }); Assert.Equal(2, comp.References.Count()); Assert.Equal("alias", comp.References.Last().Properties.Aliases.Single()); comp.VerifyDiagnostics( // (2,1): error CS1537: The using alias 'alias' appeared previously in this namespace // using alias=alias; Diagnostic(ErrorCode.ERR_DuplicateAlias, "using alias=alias;").WithArguments("alias"), // (3,17): error CS0104: 'alias' is an ambiguous reference between '<global namespace>' and '<global namespace>' // class myClass : alias::Uri Diagnostic(ErrorCode.ERR_AmbigContext, "alias").WithArguments("alias", "<global namespace>", "<global namespace>")); } [WorkItem(546088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546088")] [Fact] public void CompilationDiagsIncorrectResult() { string source1 = @" using SysAttribute = System.Attribute; using MyAttribute = MyAttribute2Attribute; public class MyAttributeAttribute : SysAttribute {} public class MyAttribute2Attribute : SysAttribute {} [MyAttribute] public class TestClass { } "; string source2 = @""; // Ask for model diagnostics first. { var compilation = CreateCompilation(source: new string[] { source1, source2 }); var tree2 = compilation.SyntaxTrees[1]; //tree for empty file var model2 = compilation.GetSemanticModel(tree2); model2.GetDiagnostics().Verify(); // None, since the file is empty. compilation.GetDiagnostics().Verify( // (8,2): error CS1614: 'MyAttribute' is ambiguous between 'MyAttribute2Attribute' and 'MyAttributeAttribute'; use either '@MyAttribute' or 'MyAttributeAttribute' // [MyAttribute] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "MyAttribute").WithArguments("MyAttribute", "MyAttribute2Attribute", "MyAttributeAttribute")); } // Ask for compilation diagnostics first. { var compilation = CreateCompilation(source: new string[] { source1, source2 }); var tree2 = compilation.SyntaxTrees[1]; //tree for empty file var model2 = compilation.GetSemanticModel(tree2); compilation.GetDiagnostics().Verify( // (10,2): error CS1614: 'MyAttribute' is ambiguous between 'MyAttribute2Attribute' and 'MyAttributeAttribute'; use either '@MyAttribute' or 'MyAttributeAttribute' // [MyAttribute] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "MyAttribute").WithArguments("MyAttribute", "MyAttribute2Attribute", "MyAttributeAttribute")); model2.GetDiagnostics().Verify(); // None, since the file is empty. } } [Fact] public void ReferenceManagerReuse_WithOptions() { var c1 = CSharpCompilation.Create("c", options: TestOptions.ReleaseDll); var c2 = c1.WithOptions(TestOptions.ReleaseExe); Assert.True(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsApplication)); Assert.True(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.ReleaseDll); Assert.True(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.ReleaseDll.WithOutputKind(OutputKind.NetModule)); Assert.False(c1.ReferenceManagerEquals(c2)); c1 = CSharpCompilation.Create("c", options: TestOptions.ReleaseModule); c2 = c1.WithOptions(TestOptions.ReleaseExe); Assert.False(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.ReleaseDll); Assert.False(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.CreateTestOptions(OutputKind.WindowsApplication, OptimizationLevel.Debug)); Assert.False(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.DebugModule.WithAllowUnsafe(true)); Assert.True(c1.ReferenceManagerEquals(c2)); } [Fact] public void ReferenceManagerReuse_WithMetadataReferenceResolver() { var c1 = CSharpCompilation.Create("c", options: TestOptions.ReleaseDll); var c2 = c1.WithOptions(TestOptions.ReleaseDll.WithMetadataReferenceResolver(new TestMetadataReferenceResolver())); Assert.False(c1.ReferenceManagerEquals(c2)); var c3 = c1.WithOptions(TestOptions.ReleaseDll.WithMetadataReferenceResolver(c1.Options.MetadataReferenceResolver)); Assert.True(c1.ReferenceManagerEquals(c3)); } [Fact] public void ReferenceManagerReuse_WithXmlFileResolver() { var c1 = CSharpCompilation.Create("c", options: TestOptions.ReleaseDll); var c2 = c1.WithOptions(TestOptions.ReleaseDll.WithXmlReferenceResolver(new XmlFileResolver(null))); Assert.False(c1.ReferenceManagerEquals(c2)); var c3 = c1.WithOptions(TestOptions.ReleaseDll.WithXmlReferenceResolver(c1.Options.XmlReferenceResolver)); Assert.True(c1.ReferenceManagerEquals(c3)); } [Fact] public void ReferenceManagerReuse_WithName() { var c1 = CSharpCompilation.Create("c1"); var c2 = c1.WithAssemblyName("c2"); Assert.False(c1.ReferenceManagerEquals(c2)); var c3 = c1.WithAssemblyName("c1"); Assert.True(c1.ReferenceManagerEquals(c3)); var c4 = c1.WithAssemblyName(null); Assert.False(c1.ReferenceManagerEquals(c4)); var c5 = c4.WithAssemblyName(null); Assert.True(c4.ReferenceManagerEquals(c5)); } [Fact] public void ReferenceManagerReuse_WithReferences() { var c1 = CSharpCompilation.Create("c1"); var c2 = c1.WithReferences(new[] { MscorlibRef }); Assert.False(c1.ReferenceManagerEquals(c2)); var c3 = c2.WithReferences(new[] { MscorlibRef, SystemCoreRef }); Assert.False(c3.ReferenceManagerEquals(c2)); c3 = c2.AddReferences(SystemCoreRef); Assert.False(c3.ReferenceManagerEquals(c2)); c3 = c2.RemoveAllReferences(); Assert.False(c3.ReferenceManagerEquals(c2)); c3 = c2.ReplaceReference(MscorlibRef, SystemCoreRef); Assert.False(c3.ReferenceManagerEquals(c2)); c3 = c2.RemoveReferences(MscorlibRef); Assert.False(c3.ReferenceManagerEquals(c2)); } [Fact] public void ReferenceManagerReuse_WithSyntaxTrees() { var ta = Parse("class C { }", options: TestOptions.Regular10); var tb = Parse(@" class C { }", options: TestOptions.Script); var tc = Parse(@" #r ""bar"" // error: #r in regular code class D { }", options: TestOptions.Regular10); var tr = Parse(@" #r ""goo"" class C { }", options: TestOptions.Script); var ts = Parse(@" #r ""bar"" class C { }", options: TestOptions.Script); var a = CSharpCompilation.Create("c", syntaxTrees: new[] { ta }); // add: var ab = a.AddSyntaxTrees(tb); Assert.True(a.ReferenceManagerEquals(ab)); var ac = a.AddSyntaxTrees(tc); Assert.True(a.ReferenceManagerEquals(ac)); var ar = a.AddSyntaxTrees(tr); Assert.False(a.ReferenceManagerEquals(ar)); var arc = ar.AddSyntaxTrees(tc); Assert.True(ar.ReferenceManagerEquals(arc)); // remove: var ar2 = arc.RemoveSyntaxTrees(tc); Assert.True(arc.ReferenceManagerEquals(ar2)); var c = arc.RemoveSyntaxTrees(ta, tr); Assert.False(arc.ReferenceManagerEquals(c)); var none1 = c.RemoveSyntaxTrees(tc); Assert.True(c.ReferenceManagerEquals(none1)); var none2 = arc.RemoveAllSyntaxTrees(); Assert.False(arc.ReferenceManagerEquals(none2)); var none3 = ac.RemoveAllSyntaxTrees(); Assert.True(ac.ReferenceManagerEquals(none3)); // replace: var asc = arc.ReplaceSyntaxTree(tr, ts); Assert.False(arc.ReferenceManagerEquals(asc)); var brc = arc.ReplaceSyntaxTree(ta, tb); Assert.True(arc.ReferenceManagerEquals(brc)); var abc = arc.ReplaceSyntaxTree(tr, tb); Assert.False(arc.ReferenceManagerEquals(abc)); var ars = arc.ReplaceSyntaxTree(tc, ts); Assert.False(arc.ReferenceManagerEquals(ars)); } [Fact] public void ReferenceManagerReuse_WithScriptCompilationInfo() { // Note: The following results would change if we optimized sharing more: https://github.com/dotnet/roslyn/issues/43397 var c1 = CSharpCompilation.CreateScriptCompilation("c1"); Assert.NotNull(c1.ScriptCompilationInfo); Assert.Null(c1.ScriptCompilationInfo.PreviousScriptCompilation); var c2 = c1.WithScriptCompilationInfo(null); Assert.Null(c2.ScriptCompilationInfo); Assert.True(c2.ReferenceManagerEquals(c1)); var c3 = c2.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: null, returnType: typeof(int), globalsType: null)); Assert.NotNull(c3.ScriptCompilationInfo); Assert.Null(c3.ScriptCompilationInfo.PreviousScriptCompilation); Assert.True(c3.ReferenceManagerEquals(c2)); var c4 = c3.WithScriptCompilationInfo(null); Assert.Null(c4.ScriptCompilationInfo); Assert.True(c4.ReferenceManagerEquals(c3)); var c5 = c4.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: c1, returnType: typeof(int), globalsType: null)); Assert.False(c5.ReferenceManagerEquals(c4)); var c6 = c5.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: c1, returnType: typeof(bool), globalsType: null)); Assert.True(c6.ReferenceManagerEquals(c5)); var c7 = c6.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: c2, returnType: typeof(bool), globalsType: null)); Assert.False(c7.ReferenceManagerEquals(c6)); var c8 = c7.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: null, returnType: typeof(bool), globalsType: null)); Assert.False(c8.ReferenceManagerEquals(c7)); var c9 = c8.WithScriptCompilationInfo(null); Assert.True(c9.ReferenceManagerEquals(c8)); } private sealed class EvolvingTestReference : PortableExecutableReference { private readonly IEnumerator<Metadata> _metadataSequence; public int QueryCount; public EvolvingTestReference(IEnumerable<Metadata> metadataSequence) : base(MetadataReferenceProperties.Assembly) { _metadataSequence = metadataSequence.GetEnumerator(); } protected override DocumentationProvider CreateDocumentationProvider() { return DocumentationProvider.Default; } protected override Metadata GetMetadataImpl() { QueryCount++; _metadataSequence.MoveNext(); return _metadataSequence.Current; } protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) { throw new NotImplementedException(); } } [ConditionalFact(typeof(NoUsedAssembliesValidation), typeof(NoIOperationValidation), Reason = "IOperation skip: Compilation changes over time, adds new errors")] public void MetadataConsistencyWhileEvolvingCompilation() { var md1 = AssemblyMetadata.CreateFromImage(CreateCompilation("public class C { }").EmitToArray()); var md2 = AssemblyMetadata.CreateFromImage(CreateCompilation("public class D { }").EmitToArray()); var reference = new EvolvingTestReference(new[] { md1, md2 }); var c1 = CreateEmptyCompilation("public class Main { public static C C; }", new[] { MscorlibRef, reference, reference }); var c2 = c1.WithAssemblyName("c2"); var c3 = c2.AddSyntaxTrees(Parse("public class Main2 { public static int a; }")); var c4 = c3.WithOptions(TestOptions.DebugModule); var c5 = c4.WithReferences(new[] { MscorlibRef, reference }); c3.VerifyDiagnostics(); c1.VerifyDiagnostics(); c4.VerifyDiagnostics(); c2.VerifyDiagnostics(); Assert.Equal(1, reference.QueryCount); c5.VerifyDiagnostics( // (1,36): error CS0246: The type or namespace name 'C' could not be found (are you missing a using directive or an assembly reference?) // public class Main2 { public static C C; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C").WithArguments("C")); Assert.Equal(2, reference.QueryCount); } [Fact] public unsafe void LinkedNetmoduleMetadataMustProvideFullPEImage() { var netModule = TestResources.MetadataTests.NetModule01.ModuleCS00; PEHeaders h = new PEHeaders(new MemoryStream(netModule)); fixed (byte* ptr = &netModule[h.MetadataStartOffset]) { using (var mdModule = ModuleMetadata.CreateFromMetadata((IntPtr)ptr, h.MetadataSize)) { var c = CSharpCompilation.Create("Goo", references: new[] { MscorlibRef, mdModule.GetReference(display: "ModuleCS00") }, options: TestOptions.ReleaseDll); c.VerifyDiagnostics( // error CS7098: Linked netmodule metadata must provide a full PE image: 'ModuleCS00'. Diagnostic(ErrorCode.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage).WithArguments("ModuleCS00").WithLocation(1, 1)); } } } [Fact] public void AppConfig1() { var references = new MetadataReference[] { Net451.mscorlib, Net451.System, TestReferences.NetFx.silverlight_v5_0_5_0.System }; var compilation = CreateEmptyCompilation( new[] { Parse("") }, references, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); compilation.VerifyDiagnostics( // error CS1703: Multiple assemblies with equivalent identity have been imported: 'System.dll' and 'System.v5.0.5.0_silverlight.dll'. Remove one of the duplicate references. Diagnostic(ErrorCode.ERR_DuplicateImport).WithArguments("System.dll (net451)", "System.v5.0.5.0_silverlight.dll")); var appConfig = new MemoryStream(Encoding.UTF8.GetBytes( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/> </assemblyBinding> </runtime> </configuration>")); var comparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfig); compilation = CreateEmptyCompilation( new[] { Parse("") }, references, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(comparer)); compilation.VerifyDiagnostics(); } [Fact] public void AppConfig2() { // Create a dll with a reference to .NET system string libSource = @" using System.Runtime.Versioning; public class C { public static FrameworkName Goo() { return null; }}"; var libComp = CreateEmptyCompilation( libSource, references: new[] { MscorlibRef, Net451.System }, options: TestOptions.ReleaseDll); libComp.VerifyDiagnostics(); var refData = libComp.EmitToArray(); var mdRef = MetadataReference.CreateFromImage(refData); var references = new[] { Net451.mscorlib, Net451.System, TestReferences.NetFx.silverlight_v5_0_5_0.System, mdRef }; // Source references the type in the dll string src1 = @"class A { public static void Main(string[] args) { C.Goo(); } }"; var c1 = CreateEmptyCompilation( new[] { Parse(src1) }, references, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); c1.VerifyDiagnostics( // error CS1703: Multiple assemblies with equivalent identity have been imported: 'System.dll' and 'System.v5.0.5.0_silverlight.dll'. Remove one of the duplicate references. Diagnostic(ErrorCode.ERR_DuplicateImport).WithArguments("System.dll (net451)", "System.v5.0.5.0_silverlight.dll"), // error CS7069: Reference to type 'System.Runtime.Versioning.FrameworkName' claims it is defined in 'System', but it could not be found Diagnostic(ErrorCode.ERR_MissingTypeInAssembly, "C.Goo").WithArguments( "System.Runtime.Versioning.FrameworkName", "System")); var appConfig = new MemoryStream(Encoding.UTF8.GetBytes( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/> </assemblyBinding> </runtime> </configuration>")); var comparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfig); var src2 = @"class A { public static void Main(string[] args) { C.Goo(); } }"; var c2 = CreateEmptyCompilation( new[] { Parse(src2) }, references, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(comparer)); c2.VerifyDiagnostics(); } [Fact] [WorkItem(797640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797640")] public void GetMetadataReferenceAPITest() { var comp = CSharpCompilation.Create("Compilation"); var metadata = Net451.mscorlib; comp = comp.AddReferences(metadata); var assemblySmb = comp.GetReferencedAssemblySymbol(metadata); var reference = comp.GetMetadataReference(assemblySmb); Assert.NotNull(reference); var comp2 = CSharpCompilation.Create("Compilation"); comp2 = comp2.AddReferences(metadata); var reference2 = comp2.GetMetadataReference(assemblySmb); Assert.NotNull(reference2); } [Fact] [WorkItem(40466, "https://github.com/dotnet/roslyn/issues/40466")] public void GetMetadataReference_VisualBasicSymbols() { var comp = CreateCompilation(""); var vbComp = CreateVisualBasicCompilation("", referencedAssemblies: TargetFrameworkUtil.GetReferences(TargetFramework.Standard)); var assembly = (IAssemblySymbol)vbComp.GetBoundReferenceManager().GetReferencedAssemblies().First().Value; Assert.Null(comp.GetMetadataReference(assembly)); Assert.Null(comp.GetMetadataReference(vbComp.Assembly)); Assert.Null(comp.GetMetadataReference((IAssemblySymbol)null)); } [Fact] public void ConsistentParseOptions() { var tree1 = SyntaxFactory.ParseSyntaxTree("", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); var tree2 = SyntaxFactory.ParseSyntaxTree("", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); var tree3 = SyntaxFactory.ParseSyntaxTree("", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)); var assemblyName = GetUniqueName(); var compilationOptions = TestOptions.DebugDll; CSharpCompilation.Create(assemblyName, new[] { tree1, tree2 }, new[] { MscorlibRef }, compilationOptions); Assert.Throws<ArgumentException>(() => { CSharpCompilation.Create(assemblyName, new[] { tree1, tree3 }, new[] { MscorlibRef }, compilationOptions); }); } [Fact] public void SubmissionCompilation_Errors() { var genericParameter = typeof(List<>).GetGenericArguments()[0]; var open = typeof(Dictionary<,>).MakeGenericType(typeof(int), genericParameter); var ptr = typeof(int).MakePointerType(); var byref = typeof(int).MakeByRefType(); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", returnType: genericParameter)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", returnType: open)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", returnType: typeof(void))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", returnType: byref)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: genericParameter)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: open)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: typeof(void))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: typeof(int))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: ptr)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: byref)); var s0 = CSharpCompilation.CreateScriptCompilation("a0", globalsType: typeof(List<int>)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a1", previousScriptCompilation: s0, globalsType: typeof(List<bool>))); // invalid options: Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseExe)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.NetModule))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeMetadata))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeApplication))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsApplication))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithCryptoKeyContainer("goo"))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithCryptoKeyFile("goo.snk"))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithDelaySign(true))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithDelaySign(false))); } [Fact] public void HasSubmissionResult() { Assert.False(CSharpCompilation.CreateScriptCompilation("sub").HasSubmissionResult()); Assert.True(CreateSubmission("1", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("1;", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("void goo() { }", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("using System;", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("int i;", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("System.Console.WriteLine();", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("System.Console.WriteLine()", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.True(CreateSubmission("null", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.True(CreateSubmission("System.Console.WriteLine", parseOptions: TestOptions.Script).HasSubmissionResult()); } /// <summary> /// Previous submission has to have no errors. /// </summary> [Fact] public void PreviousSubmissionWithError() { var s0 = CreateSubmission("int a = \"x\";"); s0.VerifyDiagnostics( // (1,9): error CS0029: Cannot implicitly convert type 'string' to 'int' Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""x""").WithArguments("string", "int")); Assert.Throws<InvalidOperationException>(() => CreateSubmission("a + 1", previous: s0)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateArrayType_DefaultArgs() { var comp = (Compilation)CSharpCompilation.Create(""); var elementType = comp.GetSpecialType(SpecialType.System_Object); var arrayType = comp.CreateArrayTypeSymbol(elementType); Assert.Equal(1, arrayType.Rank); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementType.NullableAnnotation); Assert.Throws<ArgumentException>(() => comp.CreateArrayTypeSymbol(elementType, default)); Assert.Throws<ArgumentException>(() => comp.CreateArrayTypeSymbol(elementType, 0)); arrayType = comp.CreateArrayTypeSymbol(elementType, 1, default); Assert.Equal(1, arrayType.Rank); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementType.NullableAnnotation); Assert.Throws<ArgumentException>(() => comp.CreateArrayTypeSymbol(elementType, rank: default)); Assert.Throws<ArgumentException>(() => comp.CreateArrayTypeSymbol(elementType, rank: 0)); arrayType = comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: default); Assert.Equal(1, arrayType.Rank); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementType.NullableAnnotation); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateArrayType_ElementNullableAnnotation() { var comp = (Compilation)CSharpCompilation.Create(""); var elementType = comp.GetSpecialType(SpecialType.System_Object); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType).ElementType.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.None).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.None).ElementType.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.None).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.None).ElementType.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.NotAnnotated).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.NotAnnotated).ElementType.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.Annotated).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.Annotated).ElementType.NullableAnnotation); } [Fact] public void CreateAnonymousType_IncorrectLengths() { var compilation = CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)null), ImmutableArray.Create("m1", "m2"))); } [Fact] public void CreateAnonymousType_IncorrectLengths_IsReadOnly() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32), (ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), ImmutableArray.Create(true))); } [Fact] public void CreateAnonymousType_IncorrectLengths_Locations() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32), (ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), memberLocations: ImmutableArray.Create(Location.None))); } [Fact] public void CreateAnonymousType_WritableProperty() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32), (ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), ImmutableArray.Create(false, false))); } [Fact] public void CreateAnonymousType_NullLocations() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32), (ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), memberLocations: ImmutableArray.Create(Location.None, null))); } [Fact] public void CreateAnonymousType_NullArgument1() { var compilation = CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( default(ImmutableArray<ITypeSymbol>), ImmutableArray.Create("m1"))); } [Fact] public void CreateAnonymousType_NullArgument2() { var compilation = CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)null), default(ImmutableArray<string>))); } [Fact] public void CreateAnonymousType_NullArgument3() { var compilation = CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)null), ImmutableArray.Create("m1"))); } [Fact] public void CreateAnonymousType_NullArgument4() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create((string)null))); } [Fact] public void CreateAnonymousType1() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); var type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create<ITypeSymbol>(compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1")); Assert.True(type.IsAnonymousType); Assert.Equal(1, type.GetMembers().OfType<IPropertySymbol>().Count()); Assert.Equal("<anonymous type: int m1>", type.ToDisplayString()); Assert.All(type.GetMembers().OfType<IPropertySymbol>().Select(p => p.Locations.FirstOrDefault()), loc => Assert.Equal(loc, Location.None)); } [Fact] public void CreateAnonymousType_Locations() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); var tree = CSharpSyntaxTree.ParseText("class C { }"); var loc1 = Location.Create(tree, new TextSpan(0, 1)); var loc2 = Location.Create(tree, new TextSpan(1, 1)); var type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create<ITypeSymbol>(compilation.GetSpecialType(SpecialType.System_Int32), compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), memberLocations: ImmutableArray.Create(loc1, loc2)); Assert.True(type.IsAnonymousType); Assert.Equal(2, type.GetMembers().OfType<IPropertySymbol>().Count()); Assert.Equal(loc1, type.GetMembers("m1").Single().Locations.Single()); Assert.Equal(loc2, type.GetMembers("m2").Single().Locations.Single()); Assert.Equal("<anonymous type: int m1, int m2>", type.ToDisplayString()); } [Fact] public void CreateAnonymousType2() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); var type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create<ITypeSymbol>(compilation.GetSpecialType(SpecialType.System_Int32), compilation.GetSpecialType(SpecialType.System_Boolean)), ImmutableArray.Create("m1", "m2")); Assert.True(type.IsAnonymousType); Assert.Equal(2, type.GetMembers().OfType<IPropertySymbol>().Count()); Assert.Equal("<anonymous type: int m1, bool m2>", type.ToDisplayString()); Assert.All(type.GetMembers().OfType<IPropertySymbol>().Select(p => p.Locations.FirstOrDefault()), loc => Assert.Equal(loc, Location.None)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateAnonymousType_DefaultArgs() { var comp = (Compilation)CSharpCompilation.Create(""); var memberTypes = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); var memberNames = ImmutableArray.Create("P", "Q"); var type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, default, default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, default, default, default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberIsReadOnly: default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberLocations: default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberNullableAnnotations: default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateAnonymousType_MemberNullableAnnotations_Empty() { var comp = (Compilation)CSharpCompilation.Create(""); var type = comp.CreateAnonymousTypeSymbol(ImmutableArray<ITypeSymbol>.Empty, ImmutableArray<string>.Empty, memberNullableAnnotations: ImmutableArray<CodeAnalysis.NullableAnnotation>.Empty); Assert.Equal("<empty anonymous type>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(Array.Empty<CodeAnalysis.NullableAnnotation>(), GetAnonymousTypeNullableAnnotations(type)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateAnonymousType_MemberNullableAnnotations() { var comp = (Compilation)CSharpCompilation.Create(""); var memberTypes = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); var memberNames = ImmutableArray.Create("P", "Q"); var type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, GetAnonymousTypeNullableAnnotations(type)); Assert.Throws<ArgumentException>(() => comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated))); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated)); Assert.Equal("<anonymous type: System.Object! P, System.String? Q>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated }, GetAnonymousTypeNullableAnnotations(type)); } private static ImmutableArray<CodeAnalysis.NullableAnnotation> GetAnonymousTypeNullableAnnotations(ITypeSymbol type) { return type.GetMembers().OfType<IPropertySymbol>().SelectAsArray(p => { var result = p.Type.NullableAnnotation; Assert.Equal(result, p.NullableAnnotation); return result; }); } [Fact] [WorkItem(36046, "https://github.com/dotnet/roslyn/issues/36046")] public void ConstructTypeWithNullability() { var source = @"class Pair<T, U> { }"; var comp = (Compilation)CreateCompilation(source); var genericType = (INamedTypeSymbol)comp.GetMember("Pair"); var typeArguments = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); Assert.Throws<ArgumentException>(() => genericType.Construct(default(ImmutableArray<ITypeSymbol>), default(ImmutableArray<CodeAnalysis.NullableAnnotation>))); Assert.Throws<ArgumentException>(() => genericType.Construct(typeArguments: default, typeArgumentNullableAnnotations: default)); var type = genericType.Construct(typeArguments, default); Assert.Equal("Pair<System.Object, System.String>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, type.TypeArgumentNullableAnnotations); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, type.TypeArgumentNullableAnnotations()); Assert.Throws<ArgumentException>(() => genericType.Construct(typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation>.Empty)); Assert.Throws<ArgumentException>(() => genericType.Construct(ImmutableArray.Create<ITypeSymbol>(null, null), default)); type = genericType.Construct(typeArguments, ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated)); Assert.Equal("Pair<System.Object?, System.String!>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated }, type.TypeArgumentNullableAnnotations); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated }, type.TypeArgumentNullableAnnotations()); // Type arguments from VB. comp = CreateVisualBasicCompilation(""); typeArguments = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); Assert.Throws<ArgumentException>(() => genericType.Construct(typeArguments, default)); } [Fact] [WorkItem(37310, "https://github.com/dotnet/roslyn/issues/37310")] public void ConstructMethodWithNullability() { var source = @"class Program { static void M<T, U>() { } }"; var comp = (Compilation)CreateCompilation(source); var genericMethod = (IMethodSymbol)comp.GetMember("Program.M"); var typeArguments = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); Assert.Throws<ArgumentException>(() => genericMethod.Construct(default(ImmutableArray<ITypeSymbol>), default(ImmutableArray<CodeAnalysis.NullableAnnotation>))); Assert.Throws<ArgumentException>(() => genericMethod.Construct(typeArguments: default, typeArgumentNullableAnnotations: default)); var type = genericMethod.Construct(typeArguments, default); Assert.Equal("void Program.M<System.Object, System.String>()", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, type.TypeArgumentNullableAnnotations); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, type.TypeArgumentNullableAnnotations()); Assert.Throws<ArgumentException>(() => genericMethod.Construct(typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation>.Empty)); Assert.Throws<ArgumentException>(() => genericMethod.Construct(ImmutableArray.Create<ITypeSymbol>(null, null), default)); type = genericMethod.Construct(typeArguments, ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated)); Assert.Equal("void Program.M<System.Object?, System.String!>()", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated }, type.TypeArgumentNullableAnnotations); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated }, type.TypeArgumentNullableAnnotations()); // Type arguments from VB. comp = CreateVisualBasicCompilation(""); typeArguments = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); Assert.Throws<ArgumentException>(() => genericMethod.Construct(typeArguments, default)); } #region Script return values [ConditionalFact(typeof(DesktopOnly))] public void ReturnNullAsObject() { var script = CreateSubmission("return null;", returnType: typeof(object)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnStringAsObject() { var script = CreateSubmission("return \"¡Hola!\";", returnType: typeof(object)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnIntAsObject() { var script = CreateSubmission("return 42;", returnType: typeof(object)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void TrailingReturnVoidAsObject() { var script = CreateSubmission("return", returnType: typeof(object)); script.VerifyDiagnostics( // (1,7): error CS1733: Expected expression // return Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 7), // (1,7): error CS1002: ; expected // return Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 7)); Assert.False(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnIntAsInt() { var script = CreateSubmission("return 42;", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnNullResultType() { // test that passing null is the same as passing typeof(object) var script = CreateSubmission("return 42;", returnType: null); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnNoSemicolon() { var script = CreateSubmission("return 42", returnType: typeof(uint)); script.VerifyDiagnostics( // (1,10): error CS1002: ; expected // return 42 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 10)); Assert.False(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnAwait() { var script = CreateSubmission("return await System.Threading.Tasks.Task.FromResult(42);", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); script = CreateSubmission("return await System.Threading.Tasks.Task.FromResult(42);", returnType: typeof(Task<int>)); script.VerifyDiagnostics( // (1,8): error CS0029: Cannot implicitly convert type 'int' to 'System.Threading.Tasks.Task<int>' // return await System.Threading.Tasks.Task.FromResult(42); Diagnostic(ErrorCode.ERR_NoImplicitConv, "await System.Threading.Tasks.Task.FromResult(42)").WithArguments("int", "System.Threading.Tasks.Task<int>").WithLocation(1, 8)); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnTaskNoAwait() { var script = CreateSubmission("return System.Threading.Tasks.Task.FromResult(42);", returnType: typeof(int)); script.VerifyDiagnostics( // (1,8): error CS4016: Since this is an async method, the return expression must be of type 'int' rather than 'Task<int>' // return System.Threading.Tasks.Task.FromResult(42); Diagnostic(ErrorCode.ERR_BadAsyncReturnExpression, "System.Threading.Tasks.Task.FromResult(42)").WithArguments("int").WithLocation(1, 8)); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedScopes() { var script = CreateSubmission(@" bool condition = false; if (condition) { return 1; } else { return -1; }", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedScopeWithTrailingExpression() { var script = CreateSubmission(@" if (true) { return 1; } System.Console.WriteLine();", returnType: typeof(object)); script.VerifyDiagnostics( // (6,1): warning CS0162: Unreachable code detected // System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(6, 1)); Assert.True(script.HasSubmissionResult()); script = CreateSubmission(@" if (true) { return 1; } System.Console.WriteLine()", returnType: typeof(object)); script.VerifyDiagnostics( // (6,1): warning CS0162: Unreachable code detected // System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(6, 1)); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedScopeNoTrailingExpression() { var script = CreateSubmission(@" bool condition = false; if (condition) { return 1; } System.Console.WriteLine();", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedMethod() { var script = CreateSubmission(@" int TopMethod() { return 42; }", returnType: typeof(string)); script.VerifyDiagnostics(); Assert.False(script.HasSubmissionResult()); script = CreateSubmission(@" object TopMethod() { return new System.Exception(); } TopMethod().ToString()", returnType: typeof(string)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedLambda() { var script = CreateSubmission(@" System.Func<object> f = () => { return new System.Exception(); }; 42", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); script = CreateSubmission(@" System.Func<object> f = () => new System.Exception(); 42", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedAnonymousMethod() { var script = CreateSubmission(@" System.Func<object> f = delegate () { return new System.Exception(); }; 42", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void LoadedFileWithWrongReturnType() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "return \"Who returns a string?\";")); var script = CreateSubmission(@" #load ""a.csx"" 42", returnType: typeof(int), options: TestOptions.DebugDll.WithSourceReferenceResolver(resolver)); script.VerifyDiagnostics( // a.csx(1,8): error CS0029: Cannot implicitly convert type 'string' to 'int' // return "Who returns a string?" Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""Who returns a string?""").WithArguments("string", "int").WithLocation(1, 8), // (3,1): warning CS0162: Unreachable code detected // 42 Diagnostic(ErrorCode.WRN_UnreachableCode, "42").WithLocation(3, 1)); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnVoidInNestedMethodOrLambda() { var script = CreateSubmission(@" void M1() { return; } System.Action a = () => { return; }; 42", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); var compilation = CreateCompilationWithMscorlib45(@" void M1() { return; } System.Action a = () => { return; }; 42", parseOptions: TestOptions.Script); compilation.VerifyDiagnostics(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Reflection.PortableExecutable; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestHelpers; using static Roslyn.Test.Utilities.TestMetadata; using KeyValuePairUtil = Roslyn.Utilities.KeyValuePairUtil; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class CompilationAPITests : CSharpTestBase { private CSharpCompilationOptions WithDiagnosticOptions( SyntaxTree tree, params (string, ReportDiagnostic)[] options) => TestOptions.DebugDll.WithSyntaxTreeOptionsProvider(new TestSyntaxTreeOptionsProvider(tree, options)); [Fact] public void TreeDiagnosticOptionsDoNotAffectTreeDiagnostics() { #pragma warning disable CS0618 // This test is intentionally calling the obsolete method to assert the diagnosticOptions input is now ignored var tree = SyntaxFactory.ParseSyntaxTree("class C { long _f = 0l;}", options: null, path: "", encoding: null, diagnosticOptions: CreateImmutableDictionary(("CS0078", ReportDiagnostic.Suppress)), cancellationToken: default); tree.GetDiagnostics().Verify( // (1,22): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 22)); #pragma warning restore CS0618 } [Fact] public void PerTreeVsGlobalSuppress() { var tree = SyntaxFactory.ParseSyntaxTree("class C { long _f = 0l;}"); var options = TestOptions.DebugDll .WithGeneralDiagnosticOption(ReportDiagnostic.Suppress); var comp = CreateCompilation(tree, options: options); comp.VerifyDiagnostics(); options = options.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider((tree, new[] { ("CS0078", ReportDiagnostic.Warn) }))); comp = CreateCompilation(tree, options: options); // Syntax tree diagnostic options override global settting comp.VerifyDiagnostics( // (1,22): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 22)); } [Fact] public void PerTreeDiagnosticOptionsParseWarnings() { var tree = SyntaxFactory.ParseSyntaxTree("class C { long _f = 0l;}"); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (1,22): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 22), // (1,16): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 16)); var options = WithDiagnosticOptions(tree, ("CS0078", ReportDiagnostic.Suppress)); comp = CreateCompilation(tree, options: options); comp.VerifyDiagnostics( // (1,16): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l;} Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 16)); } [Fact] public void PerTreeDiagnosticOptionsVsPragma() { var tree = SyntaxFactory.ParseSyntaxTree(@" class C { #pragma warning disable CS0078 long _f = 0l; #pragma warning restore CS0078 }"); tree.GetDiagnostics().Verify( // (4,12): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // long _f = 0l; Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(4, 12)); var comp = CreateCompilation(tree); comp.VerifyDiagnostics( // (4,6): warning CS0414: The field 'C._f' is assigned but its value is never used // long _f = 0l; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(4, 6)); var options = WithDiagnosticOptions(tree, ("CS0078", ReportDiagnostic.Error)); comp = CreateCompilation(tree, options: options); // Pragma should have precedence over per-tree options comp.VerifyDiagnostics( // (4,6): warning CS0414: The field 'C._f' is assigned but its value is never used // long _f = 0l; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(4, 6)); } [Fact] public void PerTreeDiagnosticOptionsVsSpecificOptions() { var tree = SyntaxFactory.ParseSyntaxTree("class C { long _f = 0l; }"); var options = WithDiagnosticOptions(tree, ("CS0078", ReportDiagnostic.Suppress)); var comp = CreateCompilation(tree, options: options); comp.VerifyDiagnostics( // (1,16): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 16) ); options = options.WithSpecificDiagnosticOptions( CreateImmutableDictionary(("CS0078", ReportDiagnostic.Error))); var comp2 = CreateCompilation(tree, options: options); // Specific diagnostic options have precedence over per-tree options comp2.VerifyDiagnostics( // (1,16): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 16), // (1,22): error CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 22).WithWarningAsError(true)); } [Fact] public void DifferentDiagnosticOptionsForTrees() { var tree = SyntaxFactory.ParseSyntaxTree(@" class C { long _f = 0l; }"); var newTree = SyntaxFactory.ParseSyntaxTree(@" class D { long _f = 0l; }"); var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider( (tree, new[] { ("CS0078", ReportDiagnostic.Suppress) }), (newTree, new[] { ("CS0078", ReportDiagnostic.Error) }) ) ); var comp = CreateCompilation(new[] { tree, newTree }, options: options); comp.VerifyDiagnostics( // (1,23): error CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class D { long _f = 0l; } Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 23).WithWarningAsError(true), // (1,17): warning CS0414: The field 'D._f' is assigned but its value is never used // class D { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("D._f").WithLocation(1, 17), // (1,17): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 17) ); } [Fact] public void TreeOptionsComparerRespected() { var tree = SyntaxFactory.ParseSyntaxTree(@" class C { long _f = 0l; }"); // Default options have case insensitivity var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider((tree, new[] { ("cs0078", ReportDiagnostic.Suppress) })) ); CreateCompilation(tree, options: options).VerifyDiagnostics( // (1,17): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 17) ); options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider( StringComparer.Ordinal, globalOption: default, (tree, new[] { ("cs0078", ReportDiagnostic.Suppress) })) ); CreateCompilation(tree, options: options).VerifyDiagnostics( // (1,23): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 23), // (1,17): warning CS0414: The field 'C._f' is assigned but its value is never used // class C { long _f = 0l; } Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "_f").WithArguments("C._f").WithLocation(1, 17) ); } [Fact] public void WarningLevelRespectedForLexerWarnings() { var source = @"public class C { public long Field = 0l; }"; CreateCompilation(source).VerifyDiagnostics( // (1,39): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity // public class C { public long Field = 0l; } Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(1, 39) ); CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(0)).VerifyDiagnostics( ); } [WorkItem(8360, "https://github.com/dotnet/roslyn/issues/8360")] [WorkItem(9153, "https://github.com/dotnet/roslyn/issues/9153")] [Fact] public void PublicSignWithRelativeKeyPath() { var options = TestOptions.DebugDll .WithPublicSign(true).WithCryptoKeyFile("test.snk"); var comp = CSharpCompilation.Create("test", options: options); comp.VerifyDiagnostics( // error CS7104: Option 'CryptoKeyFile' must be an absolute path. Diagnostic(ErrorCode.ERR_OptionMustBeAbsolutePath).WithArguments("CryptoKeyFile").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1) ); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath() { CreateCompilation("", options: TestOptions.ReleaseDll.WithPublicSign(true).WithCryptoKeyFile("")).VerifyDiagnostics( // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [Fact] [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] public void PublicSignWithEmptyKeyPath2() { CreateCompilation("", options: TestOptions.ReleaseDll.WithPublicSign(true).WithCryptoKeyFile("\"\"")).VerifyDiagnostics( // error CS8106: Option 'CryptoKeyFile' must be an absolute path. Diagnostic(ErrorCode.ERR_OptionMustBeAbsolutePath).WithArguments("CryptoKeyFile").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [Fact] [WorkItem(233669, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=233669")] public void CompilationName() { // report an error, rather then silently ignoring the directory // (see cli partition II 22.30) CSharpCompilation.Create(@"C:/goo/Test.exe").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), // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1), // error CS5001: Program does not contain a static 'Main' method suitable for an entry point Diagnostic(ErrorCode.ERR_NoEntryPoint).WithLocation(1, 1) ); CSharpCompilation.Create(@"C:\goo\Test.exe").GetDeclarationDiagnostics().Verify( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); var compilationOptions = TestOptions.DebugDll.WithWarningLevel(0); CSharpCompilation.Create(@"\goo/Test.exe", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create(@"C:Test.exe", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create(@"Te\0st.exe", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create(@" \t ", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name cannot start with whitespace. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name cannot start with whitespace.").WithLocation(1, 1) ); CSharpCompilation.Create(@"\uD800", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create(@"", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name cannot be empty. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name cannot be empty.").WithLocation(1, 1) ); CSharpCompilation.Create(@" a", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name cannot start with whitespace. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name cannot start with whitespace.").WithLocation(1, 1) ); CSharpCompilation.Create(@"\u2000a", options: compilationOptions).VerifyEmitDiagnostics( // U+20700 is whitespace // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); CSharpCompilation.Create("..\\..\\RelativePath", options: compilationOptions).VerifyEmitDiagnostics( // error CS8203: Invalid assembly name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_BadAssemblyName).WithArguments("Name contains invalid characters.").WithLocation(1, 1) ); // other characters than directory and volume separators are ok: CSharpCompilation.Create(@";,*?<>#!@&", options: compilationOptions).VerifyEmitDiagnostics(); CSharpCompilation.Create("goo", options: compilationOptions).VerifyEmitDiagnostics(); CSharpCompilation.Create(".goo", options: compilationOptions).VerifyEmitDiagnostics(); CSharpCompilation.Create("goo ", options: compilationOptions).VerifyEmitDiagnostics(); // can end with whitespace CSharpCompilation.Create("....", options: compilationOptions).VerifyEmitDiagnostics(); CSharpCompilation.Create(null, options: compilationOptions).VerifyEmitDiagnostics(); } [Fact] public void CreateAPITest() { var listSyntaxTree = new List<SyntaxTree>(); var listRef = new List<MetadataReference>(); var s1 = @"using Goo; namespace A.B { class C { class D { class E { } } } class G<T> { class Q<S1,S2> { } } class G<T1,T2> { } }"; SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree(s1); listSyntaxTree.Add(t1); // System.dll listRef.Add(Net451.System.WithEmbedInteropTypes(true)); var ops = TestOptions.ReleaseExe; // Create Compilation with Option is not null var comp = CSharpCompilation.Create("Compilation", listSyntaxTree, listRef, ops); Assert.Equal(ops, comp.Options); Assert.NotEqual(default, comp.SyntaxTrees); Assert.NotNull(comp.References); Assert.Equal(1, comp.SyntaxTrees.Length); Assert.Equal(1, comp.ExternalReferences.Length); var ref1 = comp.ExternalReferences[0]; Assert.True(ref1.Properties.EmbedInteropTypes); Assert.True(ref1.Properties.Aliases.IsEmpty); // Create Compilation with PreProcessorSymbols of Option is empty var ops1 = TestOptions.DebugExe; // Create Compilation with Assembly name contains invalid char var asmname = "ÃÃâ€Â"; comp = CSharpCompilation.Create(asmname, listSyntaxTree, listRef, ops); var comp1 = CSharpCompilation.Create(asmname, listSyntaxTree, listRef, null); } [Fact] public void EmitToNonWritableStreams() { var peStream = new TestStream(canRead: false, canSeek: false, canWrite: false); var pdbStream = new TestStream(canRead: false, canSeek: false, canWrite: false); var c = CSharpCompilation.Create("a", new[] { SyntaxFactory.ParseSyntaxTree("class C { static void Main() {} }") }, new[] { MscorlibRef }); Assert.Throws<ArgumentException>(() => c.Emit(peStream)); Assert.Throws<ArgumentException>(() => c.Emit(new MemoryStream(), pdbStream)); } [Fact] public void EmitOptionsDiagnostics() { var c = CreateCompilation("class C {}"); var stream = new MemoryStream(); var options = new EmitOptions( debugInformationFormat: (DebugInformationFormat)(-1), outputNameOverride: " ", fileAlignment: 513, subsystemVersion: SubsystemVersion.Create(1000000, -1000000), pdbChecksumAlgorithm: new HashAlgorithmName("invalid hash algorithm name")); EmitResult result = c.Emit(stream, options: options); result.Diagnostics.Verify( // error CS2042: Invalid debug information format: -1 Diagnostic(ErrorCode.ERR_InvalidDebugInformationFormat).WithArguments("-1").WithLocation(1, 1), // error CS2041: Invalid output name: Name cannot start with whitespace. Diagnostic(ErrorCode.ERR_InvalidOutputName).WithArguments("Name cannot start with whitespace.").WithLocation(1, 1), // error CS2024: Invalid file section alignment '513' Diagnostic(ErrorCode.ERR_InvalidFileAlignment).WithArguments("513").WithLocation(1, 1), // error CS1773: Invalid version 1000000.-1000000 for /subsystemversion. The version must be 6.02 or greater for ARM or AppContainerExe, and 4.00 or greater otherwise Diagnostic(ErrorCode.ERR_InvalidSubsystemVersion).WithArguments("1000000.-1000000").WithLocation(1, 1), // error CS8113: Invalid hash algorithm name: 'invalid hash algorithm name' Diagnostic(ErrorCode.ERR_InvalidHashAlgorithmName).WithArguments("invalid hash algorithm name").WithLocation(1, 1)); Assert.False(result.Success); } [Fact] public void EmitOptions_PdbChecksumAndDeterminism() { var options = new EmitOptions(pdbChecksumAlgorithm: default(HashAlgorithmName)); var diagnosticBag = new DiagnosticBag(); options.ValidateOptions(diagnosticBag, MessageProvider.Instance, isDeterministic: true); diagnosticBag.Verify( // error CS8113: Invalid hash algorithm name: '' Diagnostic(ErrorCode.ERR_InvalidHashAlgorithmName).WithArguments("")); diagnosticBag.Clear(); options.ValidateOptions(diagnosticBag, MessageProvider.Instance, isDeterministic: false); diagnosticBag.Verify(); } [Fact] public void Emit_BadArgs() { var comp = CSharpCompilation.Create("Compilation", options: TestOptions.ReleaseDll); Assert.Throws<ArgumentNullException>("peStream", () => comp.Emit(peStream: null)); Assert.Throws<ArgumentException>("peStream", () => comp.Emit(peStream: new TestStream(canRead: true, canWrite: false, canSeek: true))); Assert.Throws<ArgumentException>("pdbStream", () => comp.Emit(peStream: new MemoryStream(), pdbStream: new TestStream(canRead: true, canWrite: false, canSeek: true))); Assert.Throws<ArgumentException>("pdbStream", () => comp.Emit(peStream: new MemoryStream(), pdbStream: new MemoryStream(), options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded))); Assert.Throws<ArgumentException>("sourceLinkStream", () => comp.Emit( peStream: new MemoryStream(), pdbStream: new MemoryStream(), options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), sourceLinkStream: new TestStream(canRead: false, canWrite: true, canSeek: true))); Assert.Throws<ArgumentException>("embeddedTexts", () => comp.Emit( peStream: new MemoryStream(), pdbStream: null, options: null, embeddedTexts: new[] { EmbeddedText.FromStream("_", new MemoryStream()) })); Assert.Throws<ArgumentException>("embeddedTexts", () => comp.Emit( peStream: new MemoryStream(), pdbStream: null, options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), embeddedTexts: new[] { EmbeddedText.FromStream("_", new MemoryStream()) })); Assert.Throws<ArgumentException>("win32Resources", () => comp.Emit( peStream: new MemoryStream(), win32Resources: new TestStream(canRead: true, canWrite: false, canSeek: false))); Assert.Throws<ArgumentException>("win32Resources", () => comp.Emit( peStream: new MemoryStream(), win32Resources: new TestStream(canRead: false, canWrite: false, canSeek: true))); // we don't report an error when we can't write to the XML doc stream: Assert.True(comp.Emit( peStream: new MemoryStream(), pdbStream: new MemoryStream(), xmlDocumentationStream: new TestStream(canRead: true, canWrite: false, canSeek: true)).Success); } [Fact] public void ReferenceAPITest() { var opt = TestOptions.DebugExe; // Create Compilation takes two args var comp = CSharpCompilation.Create("Compilation", options: TestOptions.DebugExe); var ref1 = Net451.mscorlib; var ref2 = Net451.System; var ref3 = new TestMetadataReference(fullPath: @"c:\xml.bms"); var ref4 = new TestMetadataReference(fullPath: @"c:\aaa.dll"); // Add a new empty item comp = comp.AddReferences(Enumerable.Empty<MetadataReference>()); Assert.Equal(0, comp.ExternalReferences.Length); // Add a new valid item comp = comp.AddReferences(ref1); var assemblySmb = comp.GetReferencedAssemblySymbol(ref1); Assert.NotNull(assemblySmb); Assert.Equal("mscorlib", assemblySmb.Name, StringComparer.OrdinalIgnoreCase); Assert.Equal(1, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Assembly, comp.ExternalReferences[0].Properties.Kind); Assert.Equal(ref1, comp.ExternalReferences[0]); // Replace an existing item with another valid item comp = comp.ReplaceReference(ref1, ref2); Assert.Equal(1, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Assembly, comp.ExternalReferences[0].Properties.Kind); Assert.Equal(ref2, comp.ExternalReferences[0]); // Remove an existing item comp = comp.RemoveReferences(ref2); Assert.Equal(0, comp.ExternalReferences.Length); // Overload with Hashset var hs = new HashSet<MetadataReference> { ref1, ref2, ref3 }; var compCollection = CSharpCompilation.Create("Compilation", references: hs, options: opt); compCollection = compCollection.AddReferences(ref1, ref2, ref3, ref4).RemoveReferences(hs); Assert.Equal(1, compCollection.ExternalReferences.Length); compCollection = compCollection.AddReferences(hs).RemoveReferences(ref1, ref2, ref3, ref4); Assert.Equal(0, compCollection.ExternalReferences.Length); // Overload with Collection var col = new Collection<MetadataReference> { ref1, ref2, ref3 }; compCollection = CSharpCompilation.Create("Compilation", references: col, options: opt); compCollection = compCollection.AddReferences(col).RemoveReferences(ref1, ref2, ref3); Assert.Equal(0, compCollection.ExternalReferences.Length); compCollection = compCollection.AddReferences(ref1, ref2, ref3).RemoveReferences(col); Assert.Equal(0, comp.ExternalReferences.Length); // Overload with ConcurrentStack var stack = new ConcurrentStack<MetadataReference> { }; stack.Push(ref1); stack.Push(ref2); stack.Push(ref3); compCollection = CSharpCompilation.Create("Compilation", references: stack, options: opt); compCollection = compCollection.AddReferences(stack).RemoveReferences(ref1, ref3, ref2); Assert.Equal(0, compCollection.ExternalReferences.Length); compCollection = compCollection.AddReferences(ref2, ref1, ref3).RemoveReferences(stack); Assert.Equal(0, compCollection.ExternalReferences.Length); // Overload with ConcurrentQueue var queue = new ConcurrentQueue<MetadataReference> { }; queue.Enqueue(ref1); queue.Enqueue(ref2); queue.Enqueue(ref3); compCollection = CSharpCompilation.Create("Compilation", references: queue, options: opt); compCollection = compCollection.AddReferences(queue).RemoveReferences(ref3, ref2, ref1); Assert.Equal(0, compCollection.ExternalReferences.Length); compCollection = compCollection.AddReferences(ref2, ref1, ref3).RemoveReferences(queue); Assert.Equal(0, compCollection.ExternalReferences.Length); } [Fact] public void ReferenceDirectiveTests() { var t1 = Parse(@" #r ""a.dll"" #r ""a.dll"" ", filename: "1.csx", options: TestOptions.Script); var rd1 = t1.GetRoot().GetDirectives().Cast<ReferenceDirectiveTriviaSyntax>().ToArray(); Assert.Equal(2, rd1.Length); var t2 = Parse(@" #r ""a.dll"" #r ""b.dll"" ", options: TestOptions.Script); var rd2 = t2.GetRoot().GetDirectives().Cast<ReferenceDirectiveTriviaSyntax>().ToArray(); Assert.Equal(2, rd2.Length); var t3 = Parse(@" #r ""a.dll"" ", filename: "1.csx", options: TestOptions.Script); var rd3 = t3.GetRoot().GetDirectives().Cast<ReferenceDirectiveTriviaSyntax>().ToArray(); Assert.Equal(1, rd3.Length); var t4 = Parse(@" #r ""a.dll"" ", filename: "4.csx", options: TestOptions.Script); var rd4 = t4.GetRoot().GetDirectives().Cast<ReferenceDirectiveTriviaSyntax>().ToArray(); Assert.Equal(1, rd4.Length); var c = CreateCompilationWithMscorlib45(new[] { t1, t2 }, options: TestOptions.ReleaseDll.WithMetadataReferenceResolver( new TestMetadataReferenceResolver(files: new Dictionary<string, PortableExecutableReference>() { { @"a.dll", Net451.MicrosoftCSharp }, { @"b.dll", Net451.MicrosoftVisualBasic }, }))); c.VerifyDiagnostics(); // same containing script file name and directive string Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd1[0])); Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd1[1])); Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd2[0])); Assert.Same(Net451.MicrosoftVisualBasic, c.GetDirectiveReference(rd2[1])); Assert.Same(Net451.MicrosoftCSharp, c.GetDirectiveReference(rd3[0])); // different script name or directive string: Assert.Null(c.GetDirectiveReference(rd4[0])); } [Fact, WorkItem(530131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530131")] public void MetadataReferenceWithInvalidAlias() { var refcomp = CSharpCompilation.Create("DLL", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree("public class C {}") }, references: new MetadataReference[] { MscorlibRef }); var mtref = refcomp.EmitToImageReference(aliases: ImmutableArray.Create("a", "Alias(*#$@^%*&)")); // not use exported type var comp = CSharpCompilation.Create("APP", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( @"class D {}" ) }, references: new MetadataReference[] { MscorlibRef, mtref } ); Assert.Empty(comp.GetDiagnostics()); // use exported type with partial alias comp = CSharpCompilation.Create("APP1", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( @"extern alias Alias; class D : Alias::C {}" ) }, references: new MetadataReference[] { MscorlibRef, mtref } ); var errs = comp.GetDiagnostics(); // error CS0430: The extern alias 'Alias' was not specified in a /reference option Assert.Equal(430, errs.FirstOrDefault().Code); // use exported type with invalid alias comp = CSharpCompilation.Create("APP2", options: TestOptions.ReleaseExe, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( "extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {}", options: TestOptions.Regular9) }, references: new MetadataReference[] { MscorlibRef, mtref } ); comp.VerifyDiagnostics( // (1,21): error CS1040: Preprocessor directives must appear as the first non-whitespace character on a line // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_BadDirectivePlacement, "#").WithLocation(1, 21), // (1,61): error CS1026: ) expected // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(1, 61), // (1,61): error CS1002: ; expected // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 61), // (1,14): error CS8112: Local function 'Alias()' must declare a body because it is not marked 'static extern'. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Alias").WithArguments("Alias()").WithLocation(1, 14), // (1,8): error CS0246: The type or namespace name 'alias' could not be found (are you missing a using directive or an assembly reference?) // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias").WithArguments("alias").WithLocation(1, 8), // (1,14): warning CS0626: Method, operator, or accessor 'Alias()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "Alias").WithArguments("Alias()").WithLocation(1, 14), // (1,14): warning CS8321: The local function 'Alias' is declared but never used // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Alias").WithArguments("Alias").WithLocation(1, 14) ); } [Fact, WorkItem(530131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530131")] public void MetadataReferenceWithInvalidAliasWithCSharp6() { var refcomp = CSharpCompilation.Create("DLL", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree("public class C {}", options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)) }, references: new MetadataReference[] { MscorlibRef }); var mtref = refcomp.EmitToImageReference(aliases: ImmutableArray.Create("a", "Alias(*#$@^%*&)")); // not use exported type var comp = CSharpCompilation.Create("APP", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( @"class D {}", options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)) }, references: new MetadataReference[] { MscorlibRef, mtref } ); Assert.Empty(comp.GetDiagnostics()); // use exported type with partial alias comp = CSharpCompilation.Create("APP1", options: TestOptions.ReleaseDll, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( @"extern alias Alias; class D : Alias::C {}", options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)) }, references: new MetadataReference[] { MscorlibRef, mtref } ); var errs = comp.GetDiagnostics(); // error CS0430: The extern alias 'Alias' was not specified in a /reference option Assert.Equal(430, errs.FirstOrDefault().Code); // use exported type with invalid alias comp = CSharpCompilation.Create("APP2", options: TestOptions.ReleaseExe, syntaxTrees: new SyntaxTree[] { SyntaxFactory.ParseSyntaxTree( "extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {}", options: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)) }, references: new MetadataReference[] { MscorlibRef, mtref } ); comp.VerifyDiagnostics( // (1,1): error CS8059: Feature 'top-level statements' is not available in C# 6. Please use language version 9.0 or greater. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {}").WithArguments("top-level statements", "9.0").WithLocation(1, 1), // (1,1): error CS8059: Feature 'extern local functions' is not available in C# 6. Please use language version 9.0 or greater. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "extern").WithArguments("extern local functions", "9.0").WithLocation(1, 1), // (1,14): error CS8059: Feature 'local functions' is not available in C# 6. Please use language version 7.0 or greater. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "Alias").WithArguments("local functions", "7.0").WithLocation(1, 14), // (1,21): error CS1040: Preprocessor directives must appear as the first non-whitespace character on a line // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_BadDirectivePlacement, "#").WithLocation(1, 21), // (1,61): error CS1026: ) expected // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(1, 61), // (1,61): error CS1002: ; expected // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 61), // (1,14): error CS8112: Local function 'Alias()' must declare a body because it is not marked 'static extern'. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Alias").WithArguments("Alias()").WithLocation(1, 14), // (1,8): error CS0246: The type or namespace name 'alias' could not be found (are you missing a using directive or an assembly reference?) // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "alias").WithArguments("alias").WithLocation(1, 8), // (1,14): warning CS0626: Method, operator, or accessor 'Alias()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "Alias").WithArguments("Alias()").WithLocation(1, 14), // (1,14): warning CS8321: The local function 'Alias' is declared but never used // extern alias Alias(*#$@^%*&); class D : Alias(*#$@^%*&).C {} Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Alias").WithArguments("Alias").WithLocation(1, 14) ); } [Fact] public void SyntreeAPITest() { var s1 = "namespace System.Linq {}"; var s2 = @" namespace NA.NB { partial class C<T> { public partial class D { intttt F; } } class C { } } "; var s3 = @"int x;"; var s4 = @"Imports System "; var s5 = @" class D { public static int Goo() { long l = 25l; return 0; } } "; SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree(s1); SyntaxTree withErrorTree = SyntaxFactory.ParseSyntaxTree(s2); SyntaxTree withErrorTree1 = SyntaxFactory.ParseSyntaxTree(s3); SyntaxTree withErrorTreeVB = SyntaxFactory.ParseSyntaxTree(s4); SyntaxTree withExpressionRootTree = SyntaxFactory.ParseExpression(s3).SyntaxTree; var withWarning = SyntaxFactory.ParseSyntaxTree(s5); // Create compilation takes three args var comp = CSharpCompilation.Create("Compilation", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(s1) }, options: TestOptions.ReleaseDll); comp = comp.AddSyntaxTrees(t1, withErrorTree, withErrorTree1, withErrorTreeVB); Assert.Equal(5, comp.SyntaxTrees.Length); comp = comp.RemoveSyntaxTrees(t1, withErrorTree, withErrorTree1, withErrorTreeVB); Assert.Equal(1, comp.SyntaxTrees.Length); // Add a new empty item comp = comp.AddSyntaxTrees(Enumerable.Empty<SyntaxTree>()); Assert.Equal(1, comp.SyntaxTrees.Length); // Add a new valid item comp = comp.AddSyntaxTrees(t1); Assert.Equal(2, comp.SyntaxTrees.Length); Assert.Contains(t1, comp.SyntaxTrees); Assert.False(comp.SyntaxTrees.Contains(SyntaxFactory.ParseSyntaxTree(s1))); comp = comp.AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(s1)); Assert.Equal(3, comp.SyntaxTrees.Length); // Replace an existing item with another valid item comp = comp.ReplaceSyntaxTree(t1, SyntaxFactory.ParseSyntaxTree(s1)); Assert.Equal(3, comp.SyntaxTrees.Length); // Replace an existing item with same item comp = comp.AddSyntaxTrees(t1).ReplaceSyntaxTree(t1, t1); Assert.Equal(4, comp.SyntaxTrees.Length); // add again and verify that it throws Assert.Throws<ArgumentException>(() => comp.AddSyntaxTrees(t1)); // replace with existing and verify that it throws Assert.Throws<ArgumentException>(() => comp.ReplaceSyntaxTree(t1, comp.SyntaxTrees[0])); // SyntaxTrees have reference equality. This removal should fail. Assert.Throws<ArgumentException>(() => comp = comp.RemoveSyntaxTrees(SyntaxFactory.ParseSyntaxTree(s1))); Assert.Equal(4, comp.SyntaxTrees.Length); // Remove non-existing item Assert.Throws<ArgumentException>(() => comp = comp.RemoveSyntaxTrees(withErrorTree)); Assert.Equal(4, comp.SyntaxTrees.Length); // Add syntaxtree with error comp = comp.AddSyntaxTrees(withErrorTree1); var error = comp.GetDiagnostics(); Assert.InRange(comp.GetDiagnostics().Count(), 0, int.MaxValue); Assert.InRange(comp.GetDeclarationDiagnostics().Count(), 0, int.MaxValue); Assert.True(comp.SyntaxTrees.Contains(t1)); SyntaxTree t4 = SyntaxFactory.ParseSyntaxTree("Using System;"); SyntaxTree t5 = SyntaxFactory.ParseSyntaxTree("Usingsssssssssssss System;"); SyntaxTree t6 = SyntaxFactory.ParseSyntaxTree("Import System;"); // Overload with Hashset var hs = new HashSet<SyntaxTree> { t4, t5, t6 }; var compCollection = CSharpCompilation.Create("Compilation", syntaxTrees: hs); compCollection = compCollection.RemoveSyntaxTrees(hs); Assert.Equal(0, compCollection.SyntaxTrees.Length); compCollection = compCollection.AddSyntaxTrees(hs).RemoveSyntaxTrees(t4, t5, t6); Assert.Equal(0, compCollection.SyntaxTrees.Length); // Overload with Collection var col = new Collection<SyntaxTree> { t4, t5, t6 }; compCollection = CSharpCompilation.Create("Compilation", syntaxTrees: col); compCollection = compCollection.RemoveSyntaxTrees(t4, t5, t6); Assert.Equal(0, compCollection.SyntaxTrees.Length); Assert.Throws<ArgumentException>(() => compCollection = compCollection.AddSyntaxTrees(t4, t5).RemoveSyntaxTrees(col)); Assert.Equal(0, compCollection.SyntaxTrees.Length); // Overload with ConcurrentStack var stack = new ConcurrentStack<SyntaxTree> { }; stack.Push(t4); stack.Push(t5); stack.Push(t6); compCollection = CSharpCompilation.Create("Compilation", syntaxTrees: stack); compCollection = compCollection.RemoveSyntaxTrees(t4, t6, t5); Assert.Equal(0, compCollection.SyntaxTrees.Length); Assert.Throws<ArgumentException>(() => compCollection = compCollection.AddSyntaxTrees(t4, t6).RemoveSyntaxTrees(stack)); Assert.Equal(0, compCollection.SyntaxTrees.Length); // Overload with ConcurrentQueue var queue = new ConcurrentQueue<SyntaxTree> { }; queue.Enqueue(t4); queue.Enqueue(t5); queue.Enqueue(t6); compCollection = CSharpCompilation.Create("Compilation", syntaxTrees: queue); compCollection = compCollection.RemoveSyntaxTrees(t4, t6, t5); Assert.Equal(0, compCollection.SyntaxTrees.Length); Assert.Throws<ArgumentException>(() => compCollection = compCollection.AddSyntaxTrees(t4, t6).RemoveSyntaxTrees(queue)); Assert.Equal(0, compCollection.SyntaxTrees.Length); // Get valid binding var bind = comp.GetSemanticModel(syntaxTree: t1); Assert.Equal(t1, bind.SyntaxTree); Assert.Equal("C#", bind.Language); // Remove syntaxtree without error comp = comp.RemoveSyntaxTrees(t1); Assert.InRange(comp.GetDiagnostics().Count(), 0, int.MaxValue); // Remove syntaxtree with error comp = comp.RemoveSyntaxTrees(withErrorTree1); var e = comp.GetDiagnostics(cancellationToken: default(CancellationToken)); Assert.Equal(0, comp.GetDiagnostics(cancellationToken: default(CancellationToken)).Count()); // Add syntaxtree which is VB language comp = comp.AddSyntaxTrees(withErrorTreeVB); error = comp.GetDiagnostics(cancellationToken: CancellationToken.None); Assert.InRange(comp.GetDiagnostics().Count(), 0, int.MaxValue); comp = comp.RemoveSyntaxTrees(withErrorTreeVB); Assert.Equal(0, comp.GetDiagnostics().Count()); // Add syntaxtree with error comp = comp.AddSyntaxTrees(withWarning); error = comp.GetDeclarationDiagnostics(); Assert.InRange(error.Count(), 1, int.MaxValue); comp = comp.RemoveSyntaxTrees(withWarning); Assert.Equal(0, comp.GetDiagnostics().Count()); // Compilation.Create with syntaxtree with a non-CompilationUnit root node: should throw an ArgumentException. Assert.False(withExpressionRootTree.HasCompilationUnitRoot, "how did we get a CompilationUnit root?"); Assert.Throws<ArgumentException>(() => CSharpCompilation.Create("Compilation", new SyntaxTree[] { withExpressionRootTree })); // AddSyntaxTrees with a non-CompilationUnit root node: should throw an ArgumentException. Assert.Throws<ArgumentException>(() => comp.AddSyntaxTrees(withExpressionRootTree)); // ReplaceSyntaxTrees syntaxtree with a non-CompilationUnit root node: should throw an ArgumentException. Assert.Throws<ArgumentException>(() => comp.ReplaceSyntaxTree(comp.SyntaxTrees[0], withExpressionRootTree)); } [Fact] public void ChainedOperations() { var s1 = "using System.Linq;"; var s2 = ""; var s3 = "Import System"; SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree(s1); SyntaxTree t2 = SyntaxFactory.ParseSyntaxTree(s2); SyntaxTree t3 = SyntaxFactory.ParseSyntaxTree(s3); var listSyntaxTree = new List<SyntaxTree>(); listSyntaxTree.Add(t1); listSyntaxTree.Add(t2); // Remove second SyntaxTree CSharpCompilation comp = CSharpCompilation.Create(options: TestOptions.ReleaseDll, assemblyName: "Compilation", references: null, syntaxTrees: null); comp = comp.AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(t2); Assert.Equal(1, comp.SyntaxTrees.Length); // Remove mid SyntaxTree listSyntaxTree.Add(t3); comp = comp.RemoveSyntaxTrees(t1).AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(t2); Assert.Equal(2, comp.SyntaxTrees.Length); // remove list listSyntaxTree.Remove(t2); comp = comp.AddSyntaxTrees().RemoveSyntaxTrees(listSyntaxTree); comp = comp.AddSyntaxTrees(listSyntaxTree).RemoveSyntaxTrees(listSyntaxTree); Assert.Equal(0, comp.SyntaxTrees.Length); listSyntaxTree.Clear(); listSyntaxTree.Add(t1); listSyntaxTree.Add(t1); // Chained operation count > 2 Assert.Throws<ArgumentException>(() => comp = comp.AddSyntaxTrees(listSyntaxTree).AddReferences().ReplaceSyntaxTree(t1, t2)); comp = comp.AddSyntaxTrees(t1).AddReferences().ReplaceSyntaxTree(t1, t2); Assert.Equal(1, comp.SyntaxTrees.Length); Assert.Equal(0, comp.ExternalReferences.Length); // Create compilation with args is disordered CSharpCompilation comp1 = CSharpCompilation.Create(assemblyName: "Compilation", syntaxTrees: null, options: TestOptions.ReleaseDll, references: null); var ref1 = Net451.mscorlib; var listRef = new List<MetadataReference>(); listRef.Add(ref1); listRef.Add(ref1); // Remove with no args comp1 = comp1.AddReferences(listRef).AddSyntaxTrees(t1).RemoveReferences().RemoveSyntaxTrees(); Assert.Equal(1, comp1.ExternalReferences.Length); Assert.Equal(1, comp1.SyntaxTrees.Length); } [WorkItem(713356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713356")] [ClrOnlyFact] public void MissedModuleA() { var netModule1 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", source: new string[] { "public class C1 {}" }); netModule1.VerifyEmitDiagnostics(); var netModule2 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a2", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C2 { public static void M() { var a = new C1(); } }" }); netModule2.VerifyEmitDiagnostics(); var assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule2.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics( Diagnostic(ErrorCode.ERR_MissingNetModuleReference).WithArguments("a1.netmodule")); assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule1.EmitToImageReference(), netModule2.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics(); CompileAndVerify(assembly); } [WorkItem(713356, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/713356")] [Fact] public void MissedModuleB_OneError() { var netModule1 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", source: new string[] { "public class C1 {}" }); netModule1.VerifyEmitDiagnostics(); var netModule2 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a2", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C2 { public static void M() { var a = new C1(); } }" }); netModule2.VerifyEmitDiagnostics(); var netModule3 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a3", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C2a { public static void M() { var a = new C1(); } }" }); netModule3.VerifyEmitDiagnostics(); var assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule2.EmitToImageReference(), netModule3.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics( Diagnostic(ErrorCode.ERR_MissingNetModuleReference).WithArguments("a1.netmodule")); } [WorkItem(718500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718500")] [WorkItem(716762, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/716762")] [Fact] public void MissedModuleB_NoErrorForUnmanagedModules() { var netModule1 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", source: new string[] { @" using System; using System.Runtime.InteropServices; public class C2 { [DllImport(""user32.dll"", CharSet = CharSet.Unicode)] public static extern int MessageBox(IntPtr hWnd, String text, String caption, uint type); }" }); netModule1.VerifyEmitDiagnostics(); var assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics(); } [WorkItem(715872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/715872")] [Fact] public void MissedModuleC() { var netModule1 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", source: new string[] { "public class C1 {}" }); netModule1.VerifyEmitDiagnostics(); var netModule2 = CreateCompilation( options: TestOptions.ReleaseModule, assemblyName: "a1", references: new MetadataReference[] { netModule1.EmitToImageReference() }, source: new string[] { @" public class C2 { public static void M() { var a = new C1(); } }" }); netModule2.VerifyEmitDiagnostics(); var assembly = CreateCompilation( options: TestOptions.ReleaseExe, assemblyName: "a", references: new MetadataReference[] { netModule1.EmitToImageReference(), netModule2.EmitToImageReference() }, source: new string[] { @" public class C3 { public static void Main(string[] args) { var a = new C2(); } }" }); assembly.VerifyEmitDiagnostics(Diagnostic(ErrorCode.ERR_NetModuleNameMustBeUnique).WithArguments("a1.netmodule")); } [Fact] public void MixedRefType() { var vbComp = VB.VisualBasicCompilation.Create("CompilationVB"); var comp = CSharpCompilation.Create("Compilation"); vbComp = vbComp.AddReferences(SystemRef); // Add VB reference to C# compilation foreach (var item in vbComp.References) { comp = comp.AddReferences(item); comp = comp.ReplaceReference(item, item); } Assert.Equal(1, comp.ExternalReferences.Length); var text1 = @"class A {}"; var comp1 = CSharpCompilation.Create("Test1", new[] { SyntaxFactory.ParseSyntaxTree(text1) }); var comp2 = CSharpCompilation.Create("Test2", new[] { SyntaxFactory.ParseSyntaxTree(text1) }); var compRef1 = comp1.ToMetadataReference(); var compRef2 = comp2.ToMetadataReference(); var compRef = vbComp.ToMetadataReference(embedInteropTypes: true); var ref1 = Net451.mscorlib; var ref2 = Net451.System; // Add CompilationReference comp = CSharpCompilation.Create( "Test1", new[] { SyntaxFactory.ParseSyntaxTree(text1) }, new MetadataReference[] { compRef1, compRef2 }); Assert.Equal(2, comp.ExternalReferences.Length); Assert.True(comp.References.Contains(compRef1)); Assert.True(comp.References.Contains(compRef2)); var smb = comp.GetReferencedAssemblySymbol(compRef1); Assert.Equal(SymbolKind.Assembly, smb.Kind); Assert.Equal("Test1", smb.Identity.Name, StringComparer.OrdinalIgnoreCase); // Mixed reference type comp = comp.AddReferences(ref1); Assert.Equal(3, comp.ExternalReferences.Length); Assert.True(comp.References.Contains(ref1)); // Replace Compilation reference with Assembly file reference comp = comp.ReplaceReference(compRef2, ref2); Assert.Equal(3, comp.ExternalReferences.Length); Assert.True(comp.References.Contains(ref2)); // Replace Assembly file reference with Compilation reference comp = comp.ReplaceReference(ref1, compRef2); Assert.Equal(3, comp.ExternalReferences.Length); Assert.True(comp.References.Contains(compRef2)); var modRef1 = TestReferences.MetadataTests.NetModule01.ModuleCS00; // Add Module file reference comp = comp.AddReferences(modRef1); // Not implemented code //var modSmb = comp.GetReferencedModuleSymbol(modRef1); //Assert.Equal("ModuleCS00.mod", modSmb.Name); //Assert.Equal(4, comp.References.Count); //Assert.True(comp.References.Contains(modRef1)); //smb = comp.GetReferencedAssemblySymbol(reference: modRef1); //Assert.Equal(smb.Kind, SymbolKind.Assembly); //Assert.Equal("Test1", smb.Identity.Name, StringComparer.OrdinalIgnoreCase); // GetCompilationNamespace Not implemented(Derived Class AssemblySymbol) //var m = smb.GlobalNamespace.GetMembers(); //var nsSmb = smb.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; //var ns = comp.GetCompilationNamespace(ns: nsSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); //var asbSmb = smb as Symbol; //var ns1 = comp.GetCompilationNamespace(ns: asbSmb as NamespaceSymbol); //Assert.Equal(ns1.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns1.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // Get Referenced Module Symbol //var moduleSmb = comp.GetReferencedModuleSymbol(reference: modRef1); //Assert.Equal(SymbolKind.NetModule, moduleSmb.Kind); //Assert.Equal("ModuleCS00.mod", moduleSmb.Name, StringComparer.OrdinalIgnoreCase); // GetCompilationNamespace Not implemented(Derived Class ModuleSymbol) //nsSmb = moduleSmb.GlobalNamespace.GetMembers("Runtime").Single() as NamespaceSymbol; //ns = comp.GetCompilationNamespace(ns: nsSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); //var modSmbol = moduleSmb as Symbol; //ns1 = comp.GetCompilationNamespace(ns: modSmbol as NamespaceSymbol); //Assert.Equal(ns1.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns1.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // Get Compilation Namespace //nsSmb = comp.GlobalNamespace; //ns = comp.GetCompilationNamespace(ns: nsSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // GetCompilationNamespace Not implemented(Derived Class MergedNamespaceSymbol) //NamespaceSymbol merged = MergedNamespaceSymbol.Create(new NamespaceExtent(new MockAssemblySymbol("Merged")), null, null); //ns = comp.GetCompilationNamespace(ns: merged); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // GetCompilationNamespace Not implemented(Derived Class RetargetingNamespaceSymbol) //Retargeting.RetargetingNamespaceSymbol retargetSmb = nsSmb as Retargeting.RetargetingNamespaceSymbol; //ns = comp.GetCompilationNamespace(ns: retargetSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // GetCompilationNamespace Not implemented(Derived Class PENamespaceSymbol) //Symbols.Metadata.PE.PENamespaceSymbol pensSmb = nsSmb as Symbols.Metadata.PE.PENamespaceSymbol; //ns = comp.GetCompilationNamespace(ns: pensSmb); //Assert.Equal(ns.Kind, SymbolKind.Namespace); //Assert.True(String.Equals(ns.Name, "Compilation", StringComparison.OrdinalIgnoreCase)); // Replace Module file reference with compilation reference comp = comp.RemoveReferences(compRef1).ReplaceReference(modRef1, compRef1); Assert.Equal(3, comp.ExternalReferences.Length); // Check the reference order after replace Assert.True(comp.ExternalReferences[2] is CSharpCompilationReference, "Expected compilation reference"); Assert.Equal(compRef1, comp.ExternalReferences[2]); // Replace compilation Module file reference with Module file reference comp = comp.ReplaceReference(compRef1, modRef1); // Check the reference order after replace Assert.Equal(3, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Module, comp.ExternalReferences[2].Properties.Kind); Assert.Equal(modRef1, comp.ExternalReferences[2]); // Add VB compilation ref Assert.Throws<ArgumentException>(() => comp.AddReferences(compRef)); foreach (var item in comp.References) { comp = comp.RemoveReferences(item); } Assert.Equal(0, comp.ExternalReferences.Length); // Not Implemented // var asmByteRef = MetadataReference.CreateFromImage(new byte[5], embedInteropTypes: true); //var asmObjectRef = new AssemblyObjectReference(assembly: System.Reflection.Assembly.GetAssembly(typeof(object)),embedInteropTypes :true); //comp =comp.AddReferences(asmByteRef, asmObjectRef); //Assert.Equal(2, comp.References.Count); //Assert.Equal(ReferenceKind.AssemblyBytes, comp.References[0].Kind); //Assert.Equal(ReferenceKind.AssemblyObject , comp.References[1].Kind); //Assert.Equal(asmByteRef, comp.References[0]); //Assert.Equal(asmObjectRef, comp.References[1]); //Assert.True(comp.References[0].EmbedInteropTypes); //Assert.True(comp.References[1].EmbedInteropTypes); } [Fact] public void NegGetCompilationNamespace() { var comp = CSharpCompilation.Create("Compilation"); // Throw exception when the parameter of GetCompilationNamespace is null Assert.Throws<NullReferenceException>( delegate { comp.GetCompilationNamespace(namespaceSymbol: (INamespaceSymbol)null); }); Assert.Throws<NullReferenceException>( delegate { comp.GetCompilationNamespace(namespaceSymbol: (NamespaceSymbol)null); }); } [WorkItem(537623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537623")] [Fact] public void NegCreateCompilation() { Assert.Throws<ArgumentNullException>(() => CSharpCompilation.Create("goo", syntaxTrees: new SyntaxTree[] { null })); Assert.Throws<ArgumentNullException>(() => CSharpCompilation.Create("goo", references: new MetadataReference[] { null })); } [WorkItem(537637, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537637")] [Fact] public void NegGetSymbol() { // Create Compilation with miss mid args var comp = CSharpCompilation.Create("Compilation"); Assert.Null(comp.GetReferencedAssemblySymbol(reference: MscorlibRef)); var modRef1 = TestReferences.MetadataTests.NetModule01.ModuleCS00; // Get not exist Referenced Module Symbol Assert.Null(comp.GetReferencedModuleSymbol(modRef1)); // Throw exception when the parameter of GetReferencedAssemblySymbol is null Assert.Throws<ArgumentNullException>( delegate { comp.GetReferencedAssemblySymbol(null); }); // Throw exception when the parameter of GetReferencedModuleSymbol is null Assert.Throws<ArgumentNullException>( delegate { var modSmb1 = comp.GetReferencedModuleSymbol(null); }); } [WorkItem(537778, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537778")] // Throw exception when the parameter of the parameter type of GetReferencedAssemblySymbol is VB.CompilationReference [Fact] public void NegGetSymbol1() { var opt = TestOptions.ReleaseDll; var comp = CSharpCompilation.Create("Compilation"); var vbComp = VB.VisualBasicCompilation.Create("CompilationVB"); vbComp = vbComp.AddReferences(SystemRef); var compRef = vbComp.ToMetadataReference(); Assert.Throws<ArgumentException>(() => comp.AddReferences(compRef)); // Throw exception when the parameter of GetBinding is null Assert.Throws<ArgumentNullException>( delegate { comp.GetSemanticModel(null); }); // Throw exception when the parameter of GetTypeByNameAndArity is NULL //Assert.Throws<Exception>( //delegate //{ // comp.GetTypeByNameAndArity(fullName: null, arity: 1); //}); // Throw exception when the parameter of GetTypeByNameAndArity is less than 0 //Assert.Throws<Exception>( //delegate //{ // comp.GetTypeByNameAndArity(string.Empty, -4); //}); } // Add already existing item [Fact, WorkItem(537574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537574")] public void NegReference2() { var ref1 = Net451.mscorlib; var ref2 = Net451.System; var ref3 = Net451.SystemData; var ref4 = Net451.SystemXml; var comp = CSharpCompilation.Create("Compilation"); comp = comp.AddReferences(ref1, ref1); Assert.Equal(1, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Assembly, comp.ExternalReferences[0].Properties.Kind); Assert.Equal(ref1, comp.ExternalReferences[0]); var listRef = new List<MetadataReference> { ref1, ref2, ref3, ref4 }; // Chained operation count > 3 // ReplaceReference throws if the reference to be replaced is not found. comp = comp.AddReferences(listRef).AddReferences(ref2).RemoveReferences(ref1, ref3, ref4).ReplaceReference(ref2, ref2); Assert.Equal(1, comp.ExternalReferences.Length); Assert.Equal(MetadataImageKind.Assembly, comp.ExternalReferences[0].Properties.Kind); Assert.Equal(ref2, comp.ExternalReferences[0]); Assert.Throws<ArgumentException>(() => comp.AddReferences(listRef).AddReferences(ref2).RemoveReferences(ref1, ref2, ref3, ref4).ReplaceReference(ref2, ref2)); } // Add a new invalid item [Fact, WorkItem(537575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537575")] public void NegReference3() { var ref1 = InvalidRef; var comp = CSharpCompilation.Create("Compilation"); // Remove non-existing item Assert.Throws<ArgumentException>(() => comp = comp.RemoveReferences(ref1)); // Add a new invalid item comp = comp.AddReferences(ref1); Assert.Equal(1, comp.ExternalReferences.Length); // Replace a non-existing item with another invalid item Assert.Throws<ArgumentException>(() => comp = comp.ReplaceReference(MscorlibRef, ref1)); Assert.Equal(1, comp.ExternalReferences.Length); } // Replace a non-existing item with null [Fact, WorkItem(537567, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537567")] public void NegReference4() { var ref1 = Net451.mscorlib; var comp = CSharpCompilation.Create("Compilation"); Assert.Throws<ArgumentException>( delegate { comp = comp.ReplaceReference(ref1, null); }); // Replace null and the arg order of replace is vise Assert.Throws<ArgumentNullException>( delegate { comp = comp.ReplaceReference(newReference: ref1, oldReference: null); }); } // Replace a non-existing item with another valid item [Fact, WorkItem(537566, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537566")] public void NegReference5() { var ref1 = Net451.mscorlib; var ref2 = Net451.SystemXml; var comp = CSharpCompilation.Create("Compilation"); Assert.Throws<ArgumentException>( delegate { comp = comp.ReplaceReference(ref1, ref2); }); SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree("Using System;"); // Replace a non-existing item with another valid item and disorder the args Assert.Throws<ArgumentException>( delegate { comp.ReplaceReference(newReference: Net451.System, oldReference: ref2); }); Assert.Equal(0, comp.SyntaxTrees.Length); Assert.Throws<ArgumentException>(() => comp.ReplaceSyntaxTree(newTree: SyntaxFactory.ParseSyntaxTree("Using System;"), oldTree: t1)); Assert.Equal(0, comp.SyntaxTrees.Length); } [WorkItem(527256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527256")] // Throw exception when the parameter of SyntaxTrees.Contains is null [Fact] public void NegSyntaxTreesContains() { var comp = CSharpCompilation.Create("Compilation"); Assert.False(comp.SyntaxTrees.Contains(null)); } [WorkItem(537784, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537784")] // Throw exception when the parameter of GetSpecialType() is out of range [Fact] public void NegGetSpecialType() { var comp = CSharpCompilation.Create("Compilation"); // Throw exception when the parameter of GetBinding is out of range Assert.Throws<ArgumentOutOfRangeException>( delegate { comp.GetSpecialType((SpecialType)100); }); Assert.Throws<ArgumentOutOfRangeException>( delegate { comp.GetSpecialType(SpecialType.None); }); Assert.Throws<ArgumentOutOfRangeException>( delegate { comp.GetSpecialType((SpecialType)000); }); Assert.Throws<ArgumentOutOfRangeException>( delegate { comp.GetSpecialType(default(SpecialType)); }); } [WorkItem(538168, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538168")] // Replace a non-existing item with another valid item and disorder the args [Fact] public void NegTree2() { var comp = CSharpCompilation.Create("API"); SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree("Using System;"); Assert.Throws<ArgumentException>( delegate { comp = comp.ReplaceSyntaxTree(newTree: SyntaxFactory.ParseSyntaxTree("Using System;"), oldTree: t1); }); } [WorkItem(537576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537576")] // Add already existing item [Fact] public void NegSynTree1() { var comp = CSharpCompilation.Create("Compilation"); SyntaxTree t1 = SyntaxFactory.ParseSyntaxTree("Using System;"); Assert.Throws<ArgumentException>(() => (comp.AddSyntaxTrees(t1, t1))); Assert.Equal(0, comp.SyntaxTrees.Length); } [Fact] public void NegSynTree() { var comp = CSharpCompilation.Create("Compilation"); SyntaxTree syntaxTree = SyntaxFactory.ParseSyntaxTree("Using Goo;"); // Throw exception when add null SyntaxTree Assert.Throws<ArgumentNullException>( delegate { comp.AddSyntaxTrees(null); }); // Throw exception when Remove null SyntaxTree Assert.Throws<ArgumentNullException>( delegate { comp.RemoveSyntaxTrees(null); }); // No exception when replacing a SyntaxTree with null var compP = comp.AddSyntaxTrees(syntaxTree); comp = compP.ReplaceSyntaxTree(syntaxTree, null); Assert.Equal(0, comp.SyntaxTrees.Length); // Throw exception when remove null SyntaxTree Assert.Throws<ArgumentNullException>( delegate { comp = comp.ReplaceSyntaxTree(null, syntaxTree); }); var s1 = "Imports System.Text"; SyntaxTree t1 = VB.VisualBasicSyntaxTree.ParseText(s1); SyntaxTree t2 = t1; var t3 = t2; var vbComp = VB.VisualBasicCompilation.Create("CompilationVB"); vbComp = vbComp.AddSyntaxTrees(t1, VB.VisualBasicSyntaxTree.ParseText("Using Goo;")); // Throw exception when cast SyntaxTree foreach (var item in vbComp.SyntaxTrees) { t3 = item; Exception invalidCastSynTreeEx = Assert.Throws<InvalidCastException>( delegate { comp = comp.AddSyntaxTrees(t3); }); invalidCastSynTreeEx = Assert.Throws<InvalidCastException>( delegate { comp = comp.RemoveSyntaxTrees(t3); }); invalidCastSynTreeEx = Assert.Throws<InvalidCastException>( delegate { comp = comp.ReplaceSyntaxTree(t3, t3); }); } // Get Binding with tree is not exist SyntaxTree t4 = SyntaxFactory.ParseSyntaxTree(s1); Assert.Throws<ArgumentException>( delegate { comp.RemoveSyntaxTrees(new SyntaxTree[] { t4 }).GetSemanticModel(t4); }); } [Fact] public void GetEntryPoint_Exe() { var source = @" class A { static void Main() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); compilation.VerifyDiagnostics(); var mainMethod = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetMember<MethodSymbol>("Main"); Assert.Equal(mainMethod, compilation.GetEntryPoint(default(CancellationToken))); var entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(mainMethod, entryPointAndDiagnostics.MethodSymbol); entryPointAndDiagnostics.Diagnostics.Verify(); } [Fact] public void GetEntryPoint_Dll() { var source = @" class A { static void Main() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); Assert.Null(compilation.GetEntryPoint(default(CancellationToken))); Assert.Same(CSharpCompilation.EntryPoint.None, compilation.GetEntryPointAndDiagnostics(default(CancellationToken))); } [Fact] public void GetEntryPoint_Module() { var source = @" class A { static void Main() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseModule); compilation.VerifyDiagnostics(); Assert.Null(compilation.GetEntryPoint(default(CancellationToken))); Assert.Same(CSharpCompilation.EntryPoint.None, compilation.GetEntryPointAndDiagnostics(default(CancellationToken))); } [Fact] public void CreateCompilationForModule() { var source = @" class A { static void Main() { } } "; // equivalent of csc with no /moduleassemblyname specified: var compilation = CSharpCompilation.Create(assemblyName: null, options: TestOptions.ReleaseModule, syntaxTrees: new[] { Parse(source) }, references: new[] { MscorlibRef }); compilation.VerifyEmitDiagnostics(); Assert.Null(compilation.AssemblyName); Assert.Equal("?", compilation.Assembly.Name); Assert.Equal("?", compilation.Assembly.Identity.Name); // no name is allowed for assembly as well, although it isn't useful: compilation = CSharpCompilation.Create(assemblyName: null, options: TestOptions.ReleaseDll, syntaxTrees: new[] { Parse(source) }, references: new[] { MscorlibRef }); compilation.VerifyEmitDiagnostics(); Assert.Null(compilation.AssemblyName); Assert.Equal("?", compilation.Assembly.Name); Assert.Equal("?", compilation.Assembly.Identity.Name); // equivalent of csc with /moduleassemblyname specified: compilation = CSharpCompilation.Create(assemblyName: "ModuleAssemblyName", options: TestOptions.ReleaseModule, syntaxTrees: new[] { Parse(source) }, references: new[] { MscorlibRef }); compilation.VerifyDiagnostics(); Assert.Equal("ModuleAssemblyName", compilation.AssemblyName); Assert.Equal("ModuleAssemblyName", compilation.Assembly.Name); Assert.Equal("ModuleAssemblyName", compilation.Assembly.Identity.Name); } [WorkItem(8506, "https://github.com/dotnet/roslyn/issues/8506")] [WorkItem(17403, "https://github.com/dotnet/roslyn/issues/17403")] [Fact] public void CrossCorlibSystemObjectReturnType_Script() { // MinAsyncCorlibRef corlib is used since it provides just enough corlib type definitions // and Task APIs necessary for script hosting are provided by MinAsyncRef. This ensures that // `System.Object, mscorlib, Version=4.0.0.0` will not be provided (since it's unversioned). // // In the original bug, Xamarin iOS, Android, and Mac Mobile profile corlibs were // realistic cross-compilation targets. void AssertCompilationCorlib(CSharpCompilation compilation) { Assert.True(compilation.IsSubmission); var taskOfT = compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T); var taskOfObject = taskOfT.Construct(compilation.ObjectType); var entryPoint = compilation.GetEntryPoint(default(CancellationToken)); Assert.Same(compilation.ObjectType.ContainingAssembly, taskOfT.ContainingAssembly); Assert.Same(compilation.ObjectType.ContainingAssembly, taskOfObject.ContainingAssembly); Assert.Equal(taskOfObject, entryPoint.ReturnType); } var firstCompilation = CSharpCompilation.CreateScriptCompilation( "submission-assembly-1", references: new[] { MinAsyncCorlibRef }, syntaxTree: Parse("true", options: TestOptions.Script) ).VerifyDiagnostics(); AssertCompilationCorlib(firstCompilation); var secondCompilation = CSharpCompilation.CreateScriptCompilation( "submission-assembly-2", previousScriptCompilation: firstCompilation, syntaxTree: Parse("false", options: TestOptions.Script)) .WithScriptCompilationInfo(new CSharpScriptCompilationInfo(firstCompilation, null, null)) .VerifyDiagnostics(); AssertCompilationCorlib(secondCompilation); Assert.Same(firstCompilation.ObjectType, secondCompilation.ObjectType); Assert.Null(new CSharpScriptCompilationInfo(null, null, null) .WithPreviousScriptCompilation(firstCompilation) .ReturnTypeOpt); } [WorkItem(3719, "https://github.com/dotnet/roslyn/issues/3719")] [Fact] public void GetEntryPoint_Script() { var source = @"System.Console.WriteLine(1);"; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Script); compilation.VerifyDiagnostics(); var scriptMethod = compilation.GetMember<MethodSymbol>("Script.<Main>"); Assert.NotNull(scriptMethod); var method = compilation.GetEntryPoint(default(CancellationToken)); Assert.Equal(method, scriptMethod); var entryPoint = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(entryPoint.MethodSymbol, scriptMethod); } [Fact] public void GetEntryPoint_Script_MainIgnored() { var source = @" class A { static void Main() { } } "; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script); compilation.VerifyDiagnostics( // (4,17): warning CS7022: The entry point of the program is global script code; ignoring 'A.Main()' entry point. // static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("A.Main()").WithLocation(4, 17)); var scriptMethod = compilation.GetMember<MethodSymbol>("Script.<Main>"); Assert.NotNull(scriptMethod); var entryPoint = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(entryPoint.MethodSymbol, scriptMethod); entryPoint.Diagnostics.Verify( // (4,17): warning CS7022: The entry point of the program is global script code; ignoring 'A.Main()' entry point. // static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("A.Main()").WithLocation(4, 17)); } [Fact] public void GetEntryPoint_Submission() { var source = @"1 + 1"; var compilation = CSharpCompilation.CreateScriptCompilation("sub", references: new[] { MscorlibRef }, syntaxTree: Parse(source, options: TestOptions.Script)); compilation.VerifyDiagnostics(); var scriptMethod = compilation.GetMember<MethodSymbol>("Script.<Factory>"); Assert.NotNull(scriptMethod); var method = compilation.GetEntryPoint(default(CancellationToken)); Assert.Equal(method, scriptMethod); var entryPoint = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(entryPoint.MethodSymbol, scriptMethod); entryPoint.Diagnostics.Verify(); } [Fact] public void GetEntryPoint_Submission_MainIgnored() { var source = @" class A { static void Main() { } } "; var compilation = CSharpCompilation.CreateScriptCompilation("sub", references: new[] { MscorlibRef }, syntaxTree: Parse(source, options: TestOptions.Script)); compilation.VerifyDiagnostics( // (4,17): warning CS7022: The entry point of the program is global script code; ignoring 'A.Main()' entry point. // static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("A.Main()").WithLocation(4, 17)); Assert.True(compilation.IsSubmission); var scriptMethod = compilation.GetMember<MethodSymbol>("Script.<Factory>"); Assert.NotNull(scriptMethod); var entryPoint = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(entryPoint.MethodSymbol, scriptMethod); entryPoint.Diagnostics.Verify( // (4,17): warning CS7022: The entry point of the program is global script code; ignoring 'A.Main()' entry point. // static void Main() { } Diagnostic(ErrorCode.WRN_MainIgnored, "Main").WithArguments("A.Main()").WithLocation(4, 17)); } [Fact] public void GetEntryPoint_MainType() { var source = @" class A { static void Main() { } } class B { static void Main() { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithMainTypeName("B")); compilation.VerifyDiagnostics(); var mainMethod = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("B").GetMember<MethodSymbol>("Main"); Assert.Equal(mainMethod, compilation.GetEntryPoint(default(CancellationToken))); var entryPointAndDiagnostics = compilation.GetEntryPointAndDiagnostics(default(CancellationToken)); Assert.Equal(mainMethod, entryPointAndDiagnostics.MethodSymbol); entryPointAndDiagnostics.Diagnostics.Verify(); } [Fact] public void CanReadAndWriteDefaultWin32Res() { var comp = CSharpCompilation.Create("Compilation"); var mft = new MemoryStream(new byte[] { 0, 1, 2, 3, }); var res = comp.CreateDefaultWin32Resources(true, false, mft, null); var list = comp.MakeWin32ResourceList(res, new DiagnosticBag()); Assert.Equal(2, list.Count); } [Fact, WorkItem(750437, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/750437")] public void ConflictingAliases() { var alias = Net451.System.WithAliases(new[] { "alias" }); var text = @"extern alias alias; using alias=alias; class myClass : alias::Uri { }"; var comp = CreateEmptyCompilation(text, references: new[] { MscorlibRef, alias }); Assert.Equal(2, comp.References.Count()); Assert.Equal("alias", comp.References.Last().Properties.Aliases.Single()); comp.VerifyDiagnostics( // (2,1): error CS1537: The using alias 'alias' appeared previously in this namespace // using alias=alias; Diagnostic(ErrorCode.ERR_DuplicateAlias, "using alias=alias;").WithArguments("alias"), // (3,17): error CS0104: 'alias' is an ambiguous reference between '<global namespace>' and '<global namespace>' // class myClass : alias::Uri Diagnostic(ErrorCode.ERR_AmbigContext, "alias").WithArguments("alias", "<global namespace>", "<global namespace>")); } [WorkItem(546088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546088")] [Fact] public void CompilationDiagsIncorrectResult() { string source1 = @" using SysAttribute = System.Attribute; using MyAttribute = MyAttribute2Attribute; public class MyAttributeAttribute : SysAttribute {} public class MyAttribute2Attribute : SysAttribute {} [MyAttribute] public class TestClass { } "; string source2 = @""; // Ask for model diagnostics first. { var compilation = CreateCompilation(source: new string[] { source1, source2 }); var tree2 = compilation.SyntaxTrees[1]; //tree for empty file var model2 = compilation.GetSemanticModel(tree2); model2.GetDiagnostics().Verify(); // None, since the file is empty. compilation.GetDiagnostics().Verify( // (8,2): error CS1614: 'MyAttribute' is ambiguous between 'MyAttribute2Attribute' and 'MyAttributeAttribute'; use either '@MyAttribute' or 'MyAttributeAttribute' // [MyAttribute] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "MyAttribute").WithArguments("MyAttribute", "MyAttribute2Attribute", "MyAttributeAttribute")); } // Ask for compilation diagnostics first. { var compilation = CreateCompilation(source: new string[] { source1, source2 }); var tree2 = compilation.SyntaxTrees[1]; //tree for empty file var model2 = compilation.GetSemanticModel(tree2); compilation.GetDiagnostics().Verify( // (10,2): error CS1614: 'MyAttribute' is ambiguous between 'MyAttribute2Attribute' and 'MyAttributeAttribute'; use either '@MyAttribute' or 'MyAttributeAttribute' // [MyAttribute] Diagnostic(ErrorCode.ERR_AmbiguousAttribute, "MyAttribute").WithArguments("MyAttribute", "MyAttribute2Attribute", "MyAttributeAttribute")); model2.GetDiagnostics().Verify(); // None, since the file is empty. } } [Fact] public void ReferenceManagerReuse_WithOptions() { var c1 = CSharpCompilation.Create("c", options: TestOptions.ReleaseDll); var c2 = c1.WithOptions(TestOptions.ReleaseExe); Assert.True(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsApplication)); Assert.True(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.ReleaseDll); Assert.True(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.ReleaseDll.WithOutputKind(OutputKind.NetModule)); Assert.False(c1.ReferenceManagerEquals(c2)); c1 = CSharpCompilation.Create("c", options: TestOptions.ReleaseModule); c2 = c1.WithOptions(TestOptions.ReleaseExe); Assert.False(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.ReleaseDll); Assert.False(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.CreateTestOptions(OutputKind.WindowsApplication, OptimizationLevel.Debug)); Assert.False(c1.ReferenceManagerEquals(c2)); c2 = c1.WithOptions(TestOptions.DebugModule.WithAllowUnsafe(true)); Assert.True(c1.ReferenceManagerEquals(c2)); } [Fact] public void ReferenceManagerReuse_WithMetadataReferenceResolver() { var c1 = CSharpCompilation.Create("c", options: TestOptions.ReleaseDll); var c2 = c1.WithOptions(TestOptions.ReleaseDll.WithMetadataReferenceResolver(new TestMetadataReferenceResolver())); Assert.False(c1.ReferenceManagerEquals(c2)); var c3 = c1.WithOptions(TestOptions.ReleaseDll.WithMetadataReferenceResolver(c1.Options.MetadataReferenceResolver)); Assert.True(c1.ReferenceManagerEquals(c3)); } [Fact] public void ReferenceManagerReuse_WithXmlFileResolver() { var c1 = CSharpCompilation.Create("c", options: TestOptions.ReleaseDll); var c2 = c1.WithOptions(TestOptions.ReleaseDll.WithXmlReferenceResolver(new XmlFileResolver(null))); Assert.False(c1.ReferenceManagerEquals(c2)); var c3 = c1.WithOptions(TestOptions.ReleaseDll.WithXmlReferenceResolver(c1.Options.XmlReferenceResolver)); Assert.True(c1.ReferenceManagerEquals(c3)); } [Fact] public void ReferenceManagerReuse_WithName() { var c1 = CSharpCompilation.Create("c1"); var c2 = c1.WithAssemblyName("c2"); Assert.False(c1.ReferenceManagerEquals(c2)); var c3 = c1.WithAssemblyName("c1"); Assert.True(c1.ReferenceManagerEquals(c3)); var c4 = c1.WithAssemblyName(null); Assert.False(c1.ReferenceManagerEquals(c4)); var c5 = c4.WithAssemblyName(null); Assert.True(c4.ReferenceManagerEquals(c5)); } [Fact] public void ReferenceManagerReuse_WithReferences() { var c1 = CSharpCompilation.Create("c1"); var c2 = c1.WithReferences(new[] { MscorlibRef }); Assert.False(c1.ReferenceManagerEquals(c2)); var c3 = c2.WithReferences(new[] { MscorlibRef, SystemCoreRef }); Assert.False(c3.ReferenceManagerEquals(c2)); c3 = c2.AddReferences(SystemCoreRef); Assert.False(c3.ReferenceManagerEquals(c2)); c3 = c2.RemoveAllReferences(); Assert.False(c3.ReferenceManagerEquals(c2)); c3 = c2.ReplaceReference(MscorlibRef, SystemCoreRef); Assert.False(c3.ReferenceManagerEquals(c2)); c3 = c2.RemoveReferences(MscorlibRef); Assert.False(c3.ReferenceManagerEquals(c2)); } [Fact] public void ReferenceManagerReuse_WithSyntaxTrees() { var ta = Parse("class C { }", options: TestOptions.Regular10); var tb = Parse(@" class C { }", options: TestOptions.Script); var tc = Parse(@" #r ""bar"" // error: #r in regular code class D { }", options: TestOptions.Regular10); var tr = Parse(@" #r ""goo"" class C { }", options: TestOptions.Script); var ts = Parse(@" #r ""bar"" class C { }", options: TestOptions.Script); var a = CSharpCompilation.Create("c", syntaxTrees: new[] { ta }); // add: var ab = a.AddSyntaxTrees(tb); Assert.True(a.ReferenceManagerEquals(ab)); var ac = a.AddSyntaxTrees(tc); Assert.True(a.ReferenceManagerEquals(ac)); var ar = a.AddSyntaxTrees(tr); Assert.False(a.ReferenceManagerEquals(ar)); var arc = ar.AddSyntaxTrees(tc); Assert.True(ar.ReferenceManagerEquals(arc)); // remove: var ar2 = arc.RemoveSyntaxTrees(tc); Assert.True(arc.ReferenceManagerEquals(ar2)); var c = arc.RemoveSyntaxTrees(ta, tr); Assert.False(arc.ReferenceManagerEquals(c)); var none1 = c.RemoveSyntaxTrees(tc); Assert.True(c.ReferenceManagerEquals(none1)); var none2 = arc.RemoveAllSyntaxTrees(); Assert.False(arc.ReferenceManagerEquals(none2)); var none3 = ac.RemoveAllSyntaxTrees(); Assert.True(ac.ReferenceManagerEquals(none3)); // replace: var asc = arc.ReplaceSyntaxTree(tr, ts); Assert.False(arc.ReferenceManagerEquals(asc)); var brc = arc.ReplaceSyntaxTree(ta, tb); Assert.True(arc.ReferenceManagerEquals(brc)); var abc = arc.ReplaceSyntaxTree(tr, tb); Assert.False(arc.ReferenceManagerEquals(abc)); var ars = arc.ReplaceSyntaxTree(tc, ts); Assert.False(arc.ReferenceManagerEquals(ars)); } [Fact] public void ReferenceManagerReuse_WithScriptCompilationInfo() { // Note: The following results would change if we optimized sharing more: https://github.com/dotnet/roslyn/issues/43397 var c1 = CSharpCompilation.CreateScriptCompilation("c1"); Assert.NotNull(c1.ScriptCompilationInfo); Assert.Null(c1.ScriptCompilationInfo.PreviousScriptCompilation); var c2 = c1.WithScriptCompilationInfo(null); Assert.Null(c2.ScriptCompilationInfo); Assert.True(c2.ReferenceManagerEquals(c1)); var c3 = c2.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: null, returnType: typeof(int), globalsType: null)); Assert.NotNull(c3.ScriptCompilationInfo); Assert.Null(c3.ScriptCompilationInfo.PreviousScriptCompilation); Assert.True(c3.ReferenceManagerEquals(c2)); var c4 = c3.WithScriptCompilationInfo(null); Assert.Null(c4.ScriptCompilationInfo); Assert.True(c4.ReferenceManagerEquals(c3)); var c5 = c4.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: c1, returnType: typeof(int), globalsType: null)); Assert.False(c5.ReferenceManagerEquals(c4)); var c6 = c5.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: c1, returnType: typeof(bool), globalsType: null)); Assert.True(c6.ReferenceManagerEquals(c5)); var c7 = c6.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: c2, returnType: typeof(bool), globalsType: null)); Assert.False(c7.ReferenceManagerEquals(c6)); var c8 = c7.WithScriptCompilationInfo(new CSharpScriptCompilationInfo(previousCompilationOpt: null, returnType: typeof(bool), globalsType: null)); Assert.False(c8.ReferenceManagerEquals(c7)); var c9 = c8.WithScriptCompilationInfo(null); Assert.True(c9.ReferenceManagerEquals(c8)); } private sealed class EvolvingTestReference : PortableExecutableReference { private readonly IEnumerator<Metadata> _metadataSequence; public int QueryCount; public EvolvingTestReference(IEnumerable<Metadata> metadataSequence) : base(MetadataReferenceProperties.Assembly) { _metadataSequence = metadataSequence.GetEnumerator(); } protected override DocumentationProvider CreateDocumentationProvider() { return DocumentationProvider.Default; } protected override Metadata GetMetadataImpl() { QueryCount++; _metadataSequence.MoveNext(); return _metadataSequence.Current; } protected override PortableExecutableReference WithPropertiesImpl(MetadataReferenceProperties properties) { throw new NotImplementedException(); } } [ConditionalFact(typeof(NoUsedAssembliesValidation), typeof(NoIOperationValidation), Reason = "IOperation skip: Compilation changes over time, adds new errors")] public void MetadataConsistencyWhileEvolvingCompilation() { var md1 = AssemblyMetadata.CreateFromImage(CreateCompilation("public class C { }").EmitToArray()); var md2 = AssemblyMetadata.CreateFromImage(CreateCompilation("public class D { }").EmitToArray()); var reference = new EvolvingTestReference(new[] { md1, md2 }); var c1 = CreateEmptyCompilation("public class Main { public static C C; }", new[] { MscorlibRef, reference, reference }); var c2 = c1.WithAssemblyName("c2"); var c3 = c2.AddSyntaxTrees(Parse("public class Main2 { public static int a; }")); var c4 = c3.WithOptions(TestOptions.DebugModule); var c5 = c4.WithReferences(new[] { MscorlibRef, reference }); c3.VerifyDiagnostics(); c1.VerifyDiagnostics(); c4.VerifyDiagnostics(); c2.VerifyDiagnostics(); Assert.Equal(1, reference.QueryCount); c5.VerifyDiagnostics( // (1,36): error CS0246: The type or namespace name 'C' could not be found (are you missing a using directive or an assembly reference?) // public class Main2 { public static C C; } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "C").WithArguments("C")); Assert.Equal(2, reference.QueryCount); } [Fact] public unsafe void LinkedNetmoduleMetadataMustProvideFullPEImage() { var netModule = TestResources.MetadataTests.NetModule01.ModuleCS00; PEHeaders h = new PEHeaders(new MemoryStream(netModule)); fixed (byte* ptr = &netModule[h.MetadataStartOffset]) { using (var mdModule = ModuleMetadata.CreateFromMetadata((IntPtr)ptr, h.MetadataSize)) { var c = CSharpCompilation.Create("Goo", references: new[] { MscorlibRef, mdModule.GetReference(display: "ModuleCS00") }, options: TestOptions.ReleaseDll); c.VerifyDiagnostics( // error CS7098: Linked netmodule metadata must provide a full PE image: 'ModuleCS00'. Diagnostic(ErrorCode.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage).WithArguments("ModuleCS00").WithLocation(1, 1)); } } } [Fact] public void AppConfig1() { var references = new MetadataReference[] { Net451.mscorlib, Net451.System, TestReferences.NetFx.silverlight_v5_0_5_0.System }; var compilation = CreateEmptyCompilation( new[] { Parse("") }, references, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); compilation.VerifyDiagnostics( // error CS1703: Multiple assemblies with equivalent identity have been imported: 'System.dll' and 'System.v5.0.5.0_silverlight.dll'. Remove one of the duplicate references. Diagnostic(ErrorCode.ERR_DuplicateImport).WithArguments("System.dll (net451)", "System.v5.0.5.0_silverlight.dll")); var appConfig = new MemoryStream(Encoding.UTF8.GetBytes( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/> </assemblyBinding> </runtime> </configuration>")); var comparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfig); compilation = CreateEmptyCompilation( new[] { Parse("") }, references, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(comparer)); compilation.VerifyDiagnostics(); } [Fact] public void AppConfig2() { // Create a dll with a reference to .NET system string libSource = @" using System.Runtime.Versioning; public class C { public static FrameworkName Goo() { return null; }}"; var libComp = CreateEmptyCompilation( libSource, references: new[] { MscorlibRef, Net451.System }, options: TestOptions.ReleaseDll); libComp.VerifyDiagnostics(); var refData = libComp.EmitToArray(); var mdRef = MetadataReference.CreateFromImage(refData); var references = new[] { Net451.mscorlib, Net451.System, TestReferences.NetFx.silverlight_v5_0_5_0.System, mdRef }; // Source references the type in the dll string src1 = @"class A { public static void Main(string[] args) { C.Goo(); } }"; var c1 = CreateEmptyCompilation( new[] { Parse(src1) }, references, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default)); c1.VerifyDiagnostics( // error CS1703: Multiple assemblies with equivalent identity have been imported: 'System.dll' and 'System.v5.0.5.0_silverlight.dll'. Remove one of the duplicate references. Diagnostic(ErrorCode.ERR_DuplicateImport).WithArguments("System.dll (net451)", "System.v5.0.5.0_silverlight.dll"), // error CS7069: Reference to type 'System.Runtime.Versioning.FrameworkName' claims it is defined in 'System', but it could not be found Diagnostic(ErrorCode.ERR_MissingTypeInAssembly, "C.Goo").WithArguments( "System.Runtime.Versioning.FrameworkName", "System")); var appConfig = new MemoryStream(Encoding.UTF8.GetBytes( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <configuration> <runtime> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <supportPortability PKT=""7cec85d7bea7798e"" enable=""false""/> </assemblyBinding> </runtime> </configuration>")); var comparer = DesktopAssemblyIdentityComparer.LoadFromXml(appConfig); var src2 = @"class A { public static void Main(string[] args) { C.Goo(); } }"; var c2 = CreateEmptyCompilation( new[] { Parse(src2) }, references, options: TestOptions.ReleaseDll.WithAssemblyIdentityComparer(comparer)); c2.VerifyDiagnostics(); } [Fact] [WorkItem(797640, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797640")] public void GetMetadataReferenceAPITest() { var comp = CSharpCompilation.Create("Compilation"); var metadata = Net451.mscorlib; comp = comp.AddReferences(metadata); var assemblySmb = comp.GetReferencedAssemblySymbol(metadata); var reference = comp.GetMetadataReference(assemblySmb); Assert.NotNull(reference); var comp2 = CSharpCompilation.Create("Compilation"); comp2 = comp2.AddReferences(metadata); var reference2 = comp2.GetMetadataReference(assemblySmb); Assert.NotNull(reference2); } [Fact] [WorkItem(40466, "https://github.com/dotnet/roslyn/issues/40466")] public void GetMetadataReference_VisualBasicSymbols() { var comp = CreateCompilation(""); var vbComp = CreateVisualBasicCompilation("", referencedAssemblies: TargetFrameworkUtil.GetReferences(TargetFramework.Standard)); var assembly = (IAssemblySymbol)vbComp.GetBoundReferenceManager().GetReferencedAssemblies().First().Value; Assert.Null(comp.GetMetadataReference(assembly)); Assert.Null(comp.GetMetadataReference(vbComp.Assembly)); Assert.Null(comp.GetMetadataReference((IAssemblySymbol)null)); } [Fact] public void ConsistentParseOptions() { var tree1 = SyntaxFactory.ParseSyntaxTree("", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); var tree2 = SyntaxFactory.ParseSyntaxTree("", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); var tree3 = SyntaxFactory.ParseSyntaxTree("", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)); var assemblyName = GetUniqueName(); var compilationOptions = TestOptions.DebugDll; CSharpCompilation.Create(assemblyName, new[] { tree1, tree2 }, new[] { MscorlibRef }, compilationOptions); Assert.Throws<ArgumentException>(() => { CSharpCompilation.Create(assemblyName, new[] { tree1, tree3 }, new[] { MscorlibRef }, compilationOptions); }); } [Fact] public void SubmissionCompilation_Errors() { var genericParameter = typeof(List<>).GetGenericArguments()[0]; var open = typeof(Dictionary<,>).MakeGenericType(typeof(int), genericParameter); var ptr = typeof(int).MakePointerType(); var byref = typeof(int).MakeByRefType(); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", returnType: genericParameter)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", returnType: open)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", returnType: typeof(void))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", returnType: byref)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: genericParameter)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: open)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: typeof(void))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: typeof(int))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: ptr)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", globalsType: byref)); var s0 = CSharpCompilation.CreateScriptCompilation("a0", globalsType: typeof(List<int>)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a1", previousScriptCompilation: s0, globalsType: typeof(List<bool>))); // invalid options: Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseExe)); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.NetModule))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeMetadata))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsRuntimeApplication))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.WindowsApplication))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithCryptoKeyContainer("goo"))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithCryptoKeyFile("goo.snk"))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithDelaySign(true))); Assert.Throws<ArgumentException>(() => CSharpCompilation.CreateScriptCompilation("a", options: TestOptions.ReleaseDll.WithDelaySign(false))); } [Fact] public void HasSubmissionResult() { Assert.False(CSharpCompilation.CreateScriptCompilation("sub").HasSubmissionResult()); Assert.True(CreateSubmission("1", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("1;", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("void goo() { }", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("using System;", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("int i;", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("System.Console.WriteLine();", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.False(CreateSubmission("System.Console.WriteLine()", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.True(CreateSubmission("null", parseOptions: TestOptions.Script).HasSubmissionResult()); Assert.True(CreateSubmission("System.Console.WriteLine", parseOptions: TestOptions.Script).HasSubmissionResult()); } /// <summary> /// Previous submission has to have no errors. /// </summary> [Fact] public void PreviousSubmissionWithError() { var s0 = CreateSubmission("int a = \"x\";"); s0.VerifyDiagnostics( // (1,9): error CS0029: Cannot implicitly convert type 'string' to 'int' Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""x""").WithArguments("string", "int")); Assert.Throws<InvalidOperationException>(() => CreateSubmission("a + 1", previous: s0)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateArrayType_DefaultArgs() { var comp = (Compilation)CSharpCompilation.Create(""); var elementType = comp.GetSpecialType(SpecialType.System_Object); var arrayType = comp.CreateArrayTypeSymbol(elementType); Assert.Equal(1, arrayType.Rank); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementType.NullableAnnotation); Assert.Throws<ArgumentException>(() => comp.CreateArrayTypeSymbol(elementType, default)); Assert.Throws<ArgumentException>(() => comp.CreateArrayTypeSymbol(elementType, 0)); arrayType = comp.CreateArrayTypeSymbol(elementType, 1, default); Assert.Equal(1, arrayType.Rank); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementType.NullableAnnotation); Assert.Throws<ArgumentException>(() => comp.CreateArrayTypeSymbol(elementType, rank: default)); Assert.Throws<ArgumentException>(() => comp.CreateArrayTypeSymbol(elementType, rank: 0)); arrayType = comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: default); Assert.Equal(1, arrayType.Rank); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, arrayType.ElementType.NullableAnnotation); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateArrayType_ElementNullableAnnotation() { var comp = (Compilation)CSharpCompilation.Create(""); var elementType = comp.GetSpecialType(SpecialType.System_Object); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType).ElementType.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.None).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.None).ElementType.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.None).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.None).ElementType.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.NotAnnotated).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.NotAnnotated).ElementType.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.Annotated).ElementNullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, comp.CreateArrayTypeSymbol(elementType, elementNullableAnnotation: CodeAnalysis.NullableAnnotation.Annotated).ElementType.NullableAnnotation); } [Fact] public void CreateAnonymousType_IncorrectLengths() { var compilation = CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)null), ImmutableArray.Create("m1", "m2"))); } [Fact] public void CreateAnonymousType_IncorrectLengths_IsReadOnly() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32), (ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), ImmutableArray.Create(true))); } [Fact] public void CreateAnonymousType_IncorrectLengths_Locations() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32), (ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), memberLocations: ImmutableArray.Create(Location.None))); } [Fact] public void CreateAnonymousType_WritableProperty() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32), (ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), ImmutableArray.Create(false, false))); } [Fact] public void CreateAnonymousType_NullLocations() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32), (ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), memberLocations: ImmutableArray.Create(Location.None, null))); } [Fact] public void CreateAnonymousType_NullArgument1() { var compilation = CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( default(ImmutableArray<ITypeSymbol>), ImmutableArray.Create("m1"))); } [Fact] public void CreateAnonymousType_NullArgument2() { var compilation = CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)null), default(ImmutableArray<string>))); } [Fact] public void CreateAnonymousType_NullArgument3() { var compilation = CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)null), ImmutableArray.Create("m1"))); } [Fact] public void CreateAnonymousType_NullArgument4() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); Assert.Throws<ArgumentNullException>(() => compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create((ITypeSymbol)compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create((string)null))); } [Fact] public void CreateAnonymousType1() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); var type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create<ITypeSymbol>(compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1")); Assert.True(type.IsAnonymousType); Assert.Equal(1, type.GetMembers().OfType<IPropertySymbol>().Count()); Assert.Equal("<anonymous type: int m1>", type.ToDisplayString()); Assert.All(type.GetMembers().OfType<IPropertySymbol>().Select(p => p.Locations.FirstOrDefault()), loc => Assert.Equal(loc, Location.None)); } [Fact] public void CreateAnonymousType_Locations() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); var tree = CSharpSyntaxTree.ParseText("class C { }"); var loc1 = Location.Create(tree, new TextSpan(0, 1)); var loc2 = Location.Create(tree, new TextSpan(1, 1)); var type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create<ITypeSymbol>(compilation.GetSpecialType(SpecialType.System_Int32), compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray.Create("m1", "m2"), memberLocations: ImmutableArray.Create(loc1, loc2)); Assert.True(type.IsAnonymousType); Assert.Equal(2, type.GetMembers().OfType<IPropertySymbol>().Count()); Assert.Equal(loc1, type.GetMembers("m1").Single().Locations.Single()); Assert.Equal(loc2, type.GetMembers("m2").Single().Locations.Single()); Assert.Equal("<anonymous type: int m1, int m2>", type.ToDisplayString()); } [Fact] public void CreateAnonymousType2() { var compilation = (Compilation)CSharpCompilation.Create("HelloWorld"); var type = compilation.CreateAnonymousTypeSymbol( ImmutableArray.Create<ITypeSymbol>(compilation.GetSpecialType(SpecialType.System_Int32), compilation.GetSpecialType(SpecialType.System_Boolean)), ImmutableArray.Create("m1", "m2")); Assert.True(type.IsAnonymousType); Assert.Equal(2, type.GetMembers().OfType<IPropertySymbol>().Count()); Assert.Equal("<anonymous type: int m1, bool m2>", type.ToDisplayString()); Assert.All(type.GetMembers().OfType<IPropertySymbol>().Select(p => p.Locations.FirstOrDefault()), loc => Assert.Equal(loc, Location.None)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateAnonymousType_DefaultArgs() { var comp = (Compilation)CSharpCompilation.Create(""); var memberTypes = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); var memberNames = ImmutableArray.Create("P", "Q"); var type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, default, default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, default, default, default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberIsReadOnly: default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberLocations: default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberNullableAnnotations: default); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateAnonymousType_MemberNullableAnnotations_Empty() { var comp = (Compilation)CSharpCompilation.Create(""); var type = comp.CreateAnonymousTypeSymbol(ImmutableArray<ITypeSymbol>.Empty, ImmutableArray<string>.Empty, memberNullableAnnotations: ImmutableArray<CodeAnalysis.NullableAnnotation>.Empty); Assert.Equal("<empty anonymous type>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(Array.Empty<CodeAnalysis.NullableAnnotation>(), GetAnonymousTypeNullableAnnotations(type)); } [Fact] [WorkItem(36047, "https://github.com/dotnet/roslyn/issues/36047")] public void CreateAnonymousType_MemberNullableAnnotations() { var comp = (Compilation)CSharpCompilation.Create(""); var memberTypes = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); var memberNames = ImmutableArray.Create("P", "Q"); var type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames); Assert.Equal("<anonymous type: System.Object P, System.String Q>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, GetAnonymousTypeNullableAnnotations(type)); Assert.Throws<ArgumentException>(() => comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated))); type = comp.CreateAnonymousTypeSymbol(memberTypes, memberNames, memberNullableAnnotations: ImmutableArray.Create(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated)); Assert.Equal("<anonymous type: System.Object! P, System.String? Q>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableAnnotation.Annotated }, GetAnonymousTypeNullableAnnotations(type)); } private static ImmutableArray<CodeAnalysis.NullableAnnotation> GetAnonymousTypeNullableAnnotations(ITypeSymbol type) { return type.GetMembers().OfType<IPropertySymbol>().SelectAsArray(p => { var result = p.Type.NullableAnnotation; Assert.Equal(result, p.NullableAnnotation); return result; }); } [Fact] [WorkItem(36046, "https://github.com/dotnet/roslyn/issues/36046")] public void ConstructTypeWithNullability() { var source = @"class Pair<T, U> { }"; var comp = (Compilation)CreateCompilation(source); var genericType = (INamedTypeSymbol)comp.GetMember("Pair"); var typeArguments = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); Assert.Throws<ArgumentException>(() => genericType.Construct(default(ImmutableArray<ITypeSymbol>), default(ImmutableArray<CodeAnalysis.NullableAnnotation>))); Assert.Throws<ArgumentException>(() => genericType.Construct(typeArguments: default, typeArgumentNullableAnnotations: default)); var type = genericType.Construct(typeArguments, default); Assert.Equal("Pair<System.Object, System.String>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, type.TypeArgumentNullableAnnotations); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, type.TypeArgumentNullableAnnotations()); Assert.Throws<ArgumentException>(() => genericType.Construct(typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation>.Empty)); Assert.Throws<ArgumentException>(() => genericType.Construct(ImmutableArray.Create<ITypeSymbol>(null, null), default)); type = genericType.Construct(typeArguments, ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated)); Assert.Equal("Pair<System.Object?, System.String!>", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated }, type.TypeArgumentNullableAnnotations); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated }, type.TypeArgumentNullableAnnotations()); // Type arguments from VB. comp = CreateVisualBasicCompilation(""); typeArguments = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); Assert.Throws<ArgumentException>(() => genericType.Construct(typeArguments, default)); } [Fact] [WorkItem(37310, "https://github.com/dotnet/roslyn/issues/37310")] public void ConstructMethodWithNullability() { var source = @"class Program { static void M<T, U>() { } }"; var comp = (Compilation)CreateCompilation(source); var genericMethod = (IMethodSymbol)comp.GetMember("Program.M"); var typeArguments = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); Assert.Throws<ArgumentException>(() => genericMethod.Construct(default(ImmutableArray<ITypeSymbol>), default(ImmutableArray<CodeAnalysis.NullableAnnotation>))); Assert.Throws<ArgumentException>(() => genericMethod.Construct(typeArguments: default, typeArgumentNullableAnnotations: default)); var type = genericMethod.Construct(typeArguments, default); Assert.Equal("void Program.M<System.Object, System.String>()", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, type.TypeArgumentNullableAnnotations); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.None, CodeAnalysis.NullableAnnotation.None }, type.TypeArgumentNullableAnnotations()); Assert.Throws<ArgumentException>(() => genericMethod.Construct(typeArguments, ImmutableArray<CodeAnalysis.NullableAnnotation>.Empty)); Assert.Throws<ArgumentException>(() => genericMethod.Construct(ImmutableArray.Create<ITypeSymbol>(null, null), default)); type = genericMethod.Construct(typeArguments, ImmutableArray.Create(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated)); Assert.Equal("void Program.M<System.Object?, System.String!>()", type.ToTestDisplayString(includeNonNullable: true)); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated }, type.TypeArgumentNullableAnnotations); AssertEx.Equal(new[] { CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableAnnotation.NotAnnotated }, type.TypeArgumentNullableAnnotations()); // Type arguments from VB. comp = CreateVisualBasicCompilation(""); typeArguments = ImmutableArray.Create<ITypeSymbol>(comp.GetSpecialType(SpecialType.System_Object), comp.GetSpecialType(SpecialType.System_String)); Assert.Throws<ArgumentException>(() => genericMethod.Construct(typeArguments, default)); } #region Script return values [ConditionalFact(typeof(DesktopOnly))] public void ReturnNullAsObject() { var script = CreateSubmission("return null;", returnType: typeof(object)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnStringAsObject() { var script = CreateSubmission("return \"¡Hola!\";", returnType: typeof(object)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnIntAsObject() { var script = CreateSubmission("return 42;", returnType: typeof(object)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void TrailingReturnVoidAsObject() { var script = CreateSubmission("return", returnType: typeof(object)); script.VerifyDiagnostics( // (1,7): error CS1733: Expected expression // return Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 7), // (1,7): error CS1002: ; expected // return Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 7)); Assert.False(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnIntAsInt() { var script = CreateSubmission("return 42;", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnNullResultType() { // test that passing null is the same as passing typeof(object) var script = CreateSubmission("return 42;", returnType: null); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnNoSemicolon() { var script = CreateSubmission("return 42", returnType: typeof(uint)); script.VerifyDiagnostics( // (1,10): error CS1002: ; expected // return 42 Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(1, 10)); Assert.False(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnAwait() { var script = CreateSubmission("return await System.Threading.Tasks.Task.FromResult(42);", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); script = CreateSubmission("return await System.Threading.Tasks.Task.FromResult(42);", returnType: typeof(Task<int>)); script.VerifyDiagnostics( // (1,8): error CS0029: Cannot implicitly convert type 'int' to 'System.Threading.Tasks.Task<int>' // return await System.Threading.Tasks.Task.FromResult(42); Diagnostic(ErrorCode.ERR_NoImplicitConv, "await System.Threading.Tasks.Task.FromResult(42)").WithArguments("int", "System.Threading.Tasks.Task<int>").WithLocation(1, 8)); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnTaskNoAwait() { var script = CreateSubmission("return System.Threading.Tasks.Task.FromResult(42);", returnType: typeof(int)); script.VerifyDiagnostics( // (1,8): error CS4016: Since this is an async method, the return expression must be of type 'int' rather than 'Task<int>' // return System.Threading.Tasks.Task.FromResult(42); Diagnostic(ErrorCode.ERR_BadAsyncReturnExpression, "System.Threading.Tasks.Task.FromResult(42)").WithArguments("int").WithLocation(1, 8)); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedScopes() { var script = CreateSubmission(@" bool condition = false; if (condition) { return 1; } else { return -1; }", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedScopeWithTrailingExpression() { var script = CreateSubmission(@" if (true) { return 1; } System.Console.WriteLine();", returnType: typeof(object)); script.VerifyDiagnostics( // (6,1): warning CS0162: Unreachable code detected // System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(6, 1)); Assert.True(script.HasSubmissionResult()); script = CreateSubmission(@" if (true) { return 1; } System.Console.WriteLine()", returnType: typeof(object)); script.VerifyDiagnostics( // (6,1): warning CS0162: Unreachable code detected // System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_UnreachableCode, "System").WithLocation(6, 1)); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedScopeNoTrailingExpression() { var script = CreateSubmission(@" bool condition = false; if (condition) { return 1; } System.Console.WriteLine();", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedMethod() { var script = CreateSubmission(@" int TopMethod() { return 42; }", returnType: typeof(string)); script.VerifyDiagnostics(); Assert.False(script.HasSubmissionResult()); script = CreateSubmission(@" object TopMethod() { return new System.Exception(); } TopMethod().ToString()", returnType: typeof(string)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedLambda() { var script = CreateSubmission(@" System.Func<object> f = () => { return new System.Exception(); }; 42", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); script = CreateSubmission(@" System.Func<object> f = () => new System.Exception(); 42", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnInNestedAnonymousMethod() { var script = CreateSubmission(@" System.Func<object> f = delegate () { return new System.Exception(); }; 42", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void LoadedFileWithWrongReturnType() { var resolver = TestSourceReferenceResolver.Create( KeyValuePairUtil.Create("a.csx", "return \"Who returns a string?\";")); var script = CreateSubmission(@" #load ""a.csx"" 42", returnType: typeof(int), options: TestOptions.DebugDll.WithSourceReferenceResolver(resolver)); script.VerifyDiagnostics( // a.csx(1,8): error CS0029: Cannot implicitly convert type 'string' to 'int' // return "Who returns a string?" Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""Who returns a string?""").WithArguments("string", "int").WithLocation(1, 8), // (3,1): warning CS0162: Unreachable code detected // 42 Diagnostic(ErrorCode.WRN_UnreachableCode, "42").WithLocation(3, 1)); Assert.True(script.HasSubmissionResult()); } [ConditionalFact(typeof(DesktopOnly))] public void ReturnVoidInNestedMethodOrLambda() { var script = CreateSubmission(@" void M1() { return; } System.Action a = () => { return; }; 42", returnType: typeof(int)); script.VerifyDiagnostics(); Assert.True(script.HasSubmissionResult()); var compilation = CreateCompilationWithMscorlib45(@" void M1() { return; } System.Action a = () => { return; }; 42", parseOptions: TestOptions.Script); compilation.VerifyDiagnostics(); } #endregion } }
1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Portable/Declarations/DeclarationTreeBuilder.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class DeclarationTreeBuilder Inherits VisualBasicSyntaxVisitor(Of SingleNamespaceOrTypeDeclaration) ' The root namespace, expressing as an array of strings, one for each component. Private ReadOnly _rootNamespace As ImmutableArray(Of String) Private ReadOnly _scriptClassName As String Private ReadOnly _isSubmission As Boolean Private ReadOnly _syntaxTree As SyntaxTree Public Shared Function ForTree(tree As SyntaxTree, rootNamespace As ImmutableArray(Of String), scriptClassName As String, isSubmission As Boolean) As RootSingleNamespaceDeclaration Dim builder = New DeclarationTreeBuilder(tree, rootNamespace, scriptClassName, isSubmission) Dim decl = DirectCast(builder.ForDeclaration(tree.GetRoot()), RootSingleNamespaceDeclaration) Return decl End Function Private Sub New(syntaxTree As SyntaxTree, rootNamespace As ImmutableArray(Of String), scriptClassName As String, isSubmission As Boolean) _syntaxTree = syntaxTree _rootNamespace = rootNamespace _scriptClassName = scriptClassName _isSubmission = isSubmission End Sub Private Function ForDeclaration(node As SyntaxNode) As SingleNamespaceOrTypeDeclaration Return Visit(node) End Function Private Function VisitNamespaceChildren(node As VisualBasicSyntaxNode, members As SyntaxList(Of StatementSyntax)) As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) Dim implicitClass As SingleNamespaceOrTypeDeclaration = Nothing Dim childrenBuilder = VisitNamespaceChildren(node, members, implicitClass) If implicitClass IsNot Nothing Then childrenBuilder.Add(implicitClass) End If Return childrenBuilder.ToImmutableAndFree() End Function Private Function VisitNamespaceChildren(node As VisualBasicSyntaxNode, members As SyntaxList(Of StatementSyntax), <Out()> ByRef implicitClass As SingleNamespaceOrTypeDeclaration) As ArrayBuilder(Of SingleNamespaceOrTypeDeclaration) Dim children = ArrayBuilder(Of SingleNamespaceOrTypeDeclaration).GetInstance() Dim implicitClassTypeChildren = ArrayBuilder(Of SingleTypeDeclaration).GetInstance() ' We look for any members that are not allowed in namespace. ' If there are any we create an implicit class to wrap them. Dim requiresImplicitClass = False For Each member In members Dim namespaceOrType As SingleNamespaceOrTypeDeclaration = Visit(member) If namespaceOrType IsNot Nothing Then If namespaceOrType.Kind = DeclarationKind.EventSyntheticDelegate Then ' broken code scenario. Event declared in namespace created a delegate declaration which should go into the ' implicit class implicitClassTypeChildren.Add(DirectCast(namespaceOrType, SingleTypeDeclaration)) requiresImplicitClass = True Else children.Add(namespaceOrType) End If ElseIf Not requiresImplicitClass Then requiresImplicitClass = member.Kind <> SyntaxKind.IncompleteMember AndAlso member.Kind <> SyntaxKind.EmptyStatement End If Next If requiresImplicitClass Then ' The implicit class is not static and has no extensions Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = SingleTypeDeclaration.TypeDeclarationFlags.None Dim memberNames = GetNonTypeMemberNames(members, declFlags) implicitClass = CreateImplicitClass( node, memberNames, implicitClassTypeChildren.ToImmutable, declFlags) Else implicitClass = Nothing End If implicitClassTypeChildren.Free() Return children End Function Private Shared Function GetReferenceDirectives(compilationUnit As CompilationUnitSyntax) As ImmutableArray(Of ReferenceDirective) Dim directiveNodes = compilationUnit.GetReferenceDirectives( Function(d) Not d.File.ContainsDiagnostics AndAlso Not String.IsNullOrEmpty(d.File.ValueText)) If directiveNodes.Count = 0 Then Return ImmutableArray(Of ReferenceDirective).Empty End If Dim directives = ArrayBuilder(Of ReferenceDirective).GetInstance(directiveNodes.Count) For Each directiveNode In directiveNodes directives.Add(New ReferenceDirective(directiveNode.File.ValueText, New SourceLocation(directiveNode))) Next Return directives.ToImmutableAndFree() End Function Private Function CreateImplicitClass(parent As VisualBasicSyntaxNode, memberNames As ImmutableHashSet(Of String), children As ImmutableArray(Of SingleTypeDeclaration), declFlags As SingleTypeDeclaration.TypeDeclarationFlags) As SingleNamespaceOrTypeDeclaration Dim parentReference = _syntaxTree.GetReference(parent) Return New SingleTypeDeclaration( kind:=DeclarationKind.ImplicitClass, name:=TypeSymbol.ImplicitTypeName, arity:=0, modifiers:=DeclarationModifiers.Friend Or DeclarationModifiers.Partial Or DeclarationModifiers.NotInheritable, declFlags:=declFlags, syntaxReference:=parentReference, nameLocation:=parentReference.GetLocation(), memberNames:=memberNames, children:=children) End Function Private Function CreateScriptClass(parent As VisualBasicSyntaxNode, children As ImmutableArray(Of SingleTypeDeclaration), memberNames As ImmutableHashSet(Of String), declFlags As SingleTypeDeclaration.TypeDeclarationFlags) As SingleNamespaceOrTypeDeclaration Debug.Assert(parent.Kind = SyntaxKind.CompilationUnit AndAlso _syntaxTree.Options.Kind <> SourceCodeKind.Regular) ' script class is represented by the parent node: Dim parentReference = _syntaxTree.GetReference(parent) Dim fullName = _scriptClassName.Split("."c) ' Note: The symbol representing the merged declarations uses parentReference to enumerate non-type members. Dim decl As SingleNamespaceOrTypeDeclaration = New SingleTypeDeclaration( kind:=If(_isSubmission, DeclarationKind.Submission, DeclarationKind.Script), name:=fullName.Last(), arity:=0, modifiers:=DeclarationModifiers.Friend Or DeclarationModifiers.Partial Or DeclarationModifiers.NotInheritable, declFlags:=declFlags, syntaxReference:=parentReference, nameLocation:=parentReference.GetLocation(), memberNames:=memberNames, children:=children) For i = fullName.Length - 2 To 0 Step -1 decl = New SingleNamespaceDeclaration( name:=fullName(i), hasImports:=False, syntaxReference:=parentReference, nameLocation:=parentReference.GetLocation(), children:=ImmutableArray.Create(Of SingleNamespaceOrTypeDeclaration)(decl)) Next Return decl End Function Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As SingleNamespaceOrTypeDeclaration Dim children As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) Dim globalChildren As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) = Nothing Dim nonGlobal As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) = Nothing Dim syntaxRef = _syntaxTree.GetReference(node) Dim implicitClass As SingleNamespaceOrTypeDeclaration = Nothing Dim referenceDirectives As ImmutableArray(Of ReferenceDirective) If _syntaxTree.Options.Kind <> SourceCodeKind.Regular Then Dim childrenBuilder = ArrayBuilder(Of SingleNamespaceOrTypeDeclaration).GetInstance() Dim scriptChildren = ArrayBuilder(Of SingleTypeDeclaration).GetInstance() For Each member In node.Members Dim decl = Visit(member) If decl IsNot Nothing Then ' Although namespaces are not allowed in script code process them ' here as if they were to improve error reporting. If decl.Kind = DeclarationKind.Namespace Then childrenBuilder.Add(decl) Else scriptChildren.Add(DirectCast(decl, SingleTypeDeclaration)) End If End If Next 'Script class is not static and contains no extensions. Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = SingleTypeDeclaration.TypeDeclarationFlags.None Dim memberNames = GetNonTypeMemberNames(node.Members, declFlags) implicitClass = CreateScriptClass(node, scriptChildren.ToImmutableAndFree(), memberNames, declFlags) children = childrenBuilder.ToImmutableAndFree() referenceDirectives = GetReferenceDirectives(node) Else children = VisitNamespaceChildren(node, node.Members, implicitClass).ToImmutableAndFree() referenceDirectives = ImmutableArray(Of ReferenceDirective).Empty End If ' Find children within NamespaceGlobal separately FindGlobalDeclarations(children, implicitClass, globalChildren, nonGlobal) If _rootNamespace.Length = 0 Then ' No project-level root namespace specified. Both global and nested children within the root. Return New RootSingleNamespaceDeclaration( hasImports:=True, treeNode:=_syntaxTree.GetReference(node), children:=globalChildren.Concat(nonGlobal), referenceDirectives:=referenceDirectives, hasAssemblyAttributes:=node.Attributes.Any) Else ' Project-level root namespace. All children without explicit global are children ' of the project-level root namespace. The root declaration has the project level namespace ' and global children within it. ' Note that we need to built the project level namespace even if it has no children [Bug 4879[ Dim projectNs = BuildRootNamespace(node, nonGlobal) globalChildren = globalChildren.Add(projectNs) Dim newChildren = globalChildren.OfType(Of SingleNamespaceOrTypeDeclaration).AsImmutable() Return New RootSingleNamespaceDeclaration( hasImports:=True, treeNode:=_syntaxTree.GetReference(node), children:=newChildren, referenceDirectives:=referenceDirectives, hasAssemblyAttributes:=node.Attributes.Any) End If End Function ' Given a set of single declarations, get the sets of global and non-global declarations. ' A regular declaration is put into "non-global declarations". ' A "Namespace Global" is not put in either place, but all its direct children are put into "global declarations". Private Sub FindGlobalDeclarations(declarations As ImmutableArray(Of SingleNamespaceOrTypeDeclaration), implicitClass As SingleNamespaceOrTypeDeclaration, ByRef globalDeclarations As ImmutableArray(Of SingleNamespaceOrTypeDeclaration), ByRef nonGlobal As ImmutableArray(Of SingleNamespaceOrTypeDeclaration)) Dim globalBuilder = ArrayBuilder(Of SingleNamespaceOrTypeDeclaration).GetInstance() Dim nonGlobalBuilder = ArrayBuilder(Of SingleNamespaceOrTypeDeclaration).GetInstance() If implicitClass IsNot Nothing Then nonGlobalBuilder.Add(implicitClass) End If For Each decl In declarations Dim nsDecl As SingleNamespaceDeclaration = TryCast(decl, SingleNamespaceDeclaration) If nsDecl IsNot Nothing AndAlso nsDecl.IsGlobalNamespace Then ' Namespace Global. globalBuilder.AddRange(nsDecl.Children) Else ' regular declaration nonGlobalBuilder.Add(decl) End If Next globalDeclarations = globalBuilder.ToImmutableAndFree() nonGlobal = nonGlobalBuilder.ToImmutableAndFree() End Sub Private Function UnescapeIdentifier(identifier As String) As String If identifier(0) = "[" Then Debug.Assert(identifier(identifier.Length - 1) = "]") Return identifier.Substring(1, identifier.Length - 2) Else Return identifier End If End Function ' Build the declaration for the root (project-level) namespace. Private Function BuildRootNamespace(node As CompilationUnitSyntax, children As ImmutableArray(Of SingleNamespaceOrTypeDeclaration)) As SingleNamespaceDeclaration Debug.Assert(_rootNamespace.Length > 0) Dim ns As SingleNamespaceDeclaration = Nothing ' The compilation node will count as a location for the innermost project level ' namespace. i.e. if the project level namespace is "Goo.Bar", then each compilation unit ' is a location for "Goo.Bar". "Goo" still has no syntax location though. ' ' By doing this we ensure that top level type and namespace declarations will have ' symbols whose parent namespace symbol points to the parent container CompilationUnit. ' This ensures parity with the case where their is no 'project-level' namespace and the ' global namespaces point to the compilation unit syntax. Dim syntaxReference = _syntaxTree.GetReference(node) Dim nameLocation = syntaxReference.GetLocation() ' traverse components from right to left For i = _rootNamespace.Length - 1 To 0 Step -1 ' treat all root namespace parts as implicitly escaped. ' a root namespace with a name "global" will actually create "Global.[global]" ns = New SingleNamespaceDeclaration( name:=UnescapeIdentifier(_rootNamespace(i)), hasImports:=True, syntaxReference:=syntaxReference, nameLocation:=nameLocation, children:=children, isPartOfRootNamespace:=True) ' Only the innermost namespace will point at compilation unit. All other outer ' namespaces will have no location. syntaxReference = Nothing nameLocation = Nothing ' This namespace is the child of the namespace to the left. children = ImmutableArray.Create(Of SingleNamespaceOrTypeDeclaration)(ns) Next Return ns End Function Public Overrides Function VisitNamespaceBlock(nsBlockSyntax As NamespaceBlockSyntax) As SingleNamespaceOrTypeDeclaration Dim nsDeclSyntax As NamespaceStatementSyntax = nsBlockSyntax.NamespaceStatement Dim children = VisitNamespaceChildren(nsBlockSyntax, nsBlockSyntax.Members) Dim name As NameSyntax = nsDeclSyntax.Name While TypeOf name Is QualifiedNameSyntax Dim dotted = DirectCast(name, QualifiedNameSyntax) Dim ns = New SingleNamespaceDeclaration( name:=dotted.Right.Identifier.ValueText, hasImports:=True, syntaxReference:=_syntaxTree.GetReference(dotted), nameLocation:=_syntaxTree.GetLocation(dotted.Right.Span), children:=children) children = {ns}.OfType(Of SingleNamespaceOrTypeDeclaration).AsImmutable() name = dotted.Left End While ' This is either the global namespace, or a regular namespace. Represent the global namespace ' with the empty string. If name.Kind = SyntaxKind.GlobalName Then If nsBlockSyntax.Parent.Kind = SyntaxKind.CompilationUnit Then ' Namespace Global only allowed as direct child of compilation. Return New GlobalNamespaceDeclaration( hasImports:=True, syntaxReference:=_syntaxTree.GetReference(name), nameLocation:=_syntaxTree.GetLocation(name.Span), children:=children) Else ' Error for this will be diagnosed later. Create a namespace named "Global" for error recovery. (see corresponding code in BinderFactory) Return New SingleNamespaceDeclaration( name:="Global", hasImports:=True, syntaxReference:=_syntaxTree.GetReference(name), nameLocation:=_syntaxTree.GetLocation(name.Span), children:=children) End If Else Return New SingleNamespaceDeclaration( name:=DirectCast(name, IdentifierNameSyntax).Identifier.ValueText, hasImports:=True, syntaxReference:=_syntaxTree.GetReference(name), nameLocation:=_syntaxTree.GetLocation(name.Span), children:=children) End If End Function Private Structure TypeBlockInfo Public ReadOnly TypeBlockSyntax As TypeBlockSyntax Public ReadOnly TypeDeclaration As SingleTypeDeclaration Public ReadOnly NestedTypes As ArrayBuilder(Of Integer) Public Sub New(typeBlockSyntax As TypeBlockSyntax) MyClass.New(typeBlockSyntax, Nothing, Nothing) End Sub Private Sub New(typeBlockSyntax As TypeBlockSyntax, declaration As SingleTypeDeclaration, nestedTypes As ArrayBuilder(Of Integer)) Me.TypeBlockSyntax = typeBlockSyntax Me.TypeDeclaration = declaration Me.NestedTypes = nestedTypes End Sub Public Function WithNestedTypes(nested As ArrayBuilder(Of Integer)) As TypeBlockInfo Debug.Assert(Me.TypeDeclaration Is Nothing) Debug.Assert(Me.NestedTypes Is Nothing) Debug.Assert(nested IsNot Nothing) Return New TypeBlockInfo(Me.TypeBlockSyntax, Nothing, nested) End Function Public Function WithDeclaration(declaration As SingleTypeDeclaration) As TypeBlockInfo Debug.Assert(Me.TypeDeclaration Is Nothing) Debug.Assert(declaration IsNot Nothing) Return New TypeBlockInfo(Me.TypeBlockSyntax, declaration, Me.NestedTypes) End Function End Structure Private Function VisitTypeBlockNew(topTypeBlockSyntax As TypeBlockSyntax) As SingleNamespaceOrTypeDeclaration Dim typeStack = ArrayBuilder(Of TypeBlockInfo).GetInstance typeStack.Add(New TypeBlockInfo(topTypeBlockSyntax)) ' Fill the chain with types Dim index As Integer = 0 While index < typeStack.Count Dim typeEntry As TypeBlockInfo = typeStack(index) Dim members As SyntaxList(Of StatementSyntax) = typeEntry.TypeBlockSyntax.Members If members.Count > 0 Then Dim nestedTypeIndices As ArrayBuilder(Of Integer) = Nothing For Each member In members Select Case member.Kind Case SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock If nestedTypeIndices Is Nothing Then nestedTypeIndices = ArrayBuilder(Of Integer).GetInstance() End If nestedTypeIndices.Add(typeStack.Count) typeStack.Add(New TypeBlockInfo(DirectCast(member, TypeBlockSyntax))) End Select Next If nestedTypeIndices IsNot Nothing Then typeStack(index) = typeEntry.WithNestedTypes(nestedTypeIndices) End If End If index += 1 End While ' Process types Debug.Assert(index = typeStack.Count) Dim childrenBuilder = ArrayBuilder(Of SingleTypeDeclaration).GetInstance() While index > 0 index -= 1 Dim typeEntry As TypeBlockInfo = typeStack(index) Dim children = ImmutableArray(Of SingleTypeDeclaration).Empty Dim members As SyntaxList(Of StatementSyntax) = typeEntry.TypeBlockSyntax.Members If members.Count > 0 Then childrenBuilder.Clear() For Each member In members Select Case member.Kind Case SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock ' should be processed already Case Else Dim typeDecl = TryCast(Visit(member), SingleTypeDeclaration) If typeDecl IsNot Nothing Then childrenBuilder.Add(typeDecl) End If End Select Next Dim nestedTypes As ArrayBuilder(Of Integer) = typeEntry.NestedTypes If nestedTypes IsNot Nothing Then For i = 0 To nestedTypes.Count - 1 childrenBuilder.Add(typeStack(nestedTypes(i)).TypeDeclaration) Next nestedTypes.Free() End If children = childrenBuilder.ToImmutable() End If Dim typeBlockSyntax As TypeBlockSyntax = typeEntry.TypeBlockSyntax Dim declarationSyntax As TypeStatementSyntax = typeBlockSyntax.BlockStatement ' Get the arity for things that can have arity. Dim typeArity As Integer = 0 Select Case typeBlockSyntax.Kind Case SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock typeArity = GetArity(declarationSyntax.TypeParameterList) End Select Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = If(declarationSyntax.AttributeLists.Any(), SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes, SingleTypeDeclaration.TypeDeclarationFlags.None) If (typeBlockSyntax.Inherits.Any) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations End If Dim memberNames = GetNonTypeMemberNames(typeBlockSyntax.Members, declFlags) typeStack(index) = typeEntry.WithDeclaration( New SingleTypeDeclaration( kind:=GetKind(declarationSyntax.Kind), name:=declarationSyntax.Identifier.ValueText, arity:=typeArity, modifiers:=GetModifiers(declarationSyntax.Modifiers), declFlags:=declFlags, syntaxReference:=_syntaxTree.GetReference(typeBlockSyntax), nameLocation:=_syntaxTree.GetLocation(typeBlockSyntax.BlockStatement.Identifier.Span), memberNames:=memberNames, children:=children)) End While childrenBuilder.Free() Dim result As SingleNamespaceOrTypeDeclaration = typeStack(0).TypeDeclaration typeStack.Free() Return result End Function Public Overrides Function VisitModuleBlock(ByVal moduleBlockSyntax As ModuleBlockSyntax) As SingleNamespaceOrTypeDeclaration Return VisitTypeBlockNew(moduleBlockSyntax) End Function Public Overrides Function VisitClassBlock(ByVal classBlockSyntax As ClassBlockSyntax) As SingleNamespaceOrTypeDeclaration Return VisitTypeBlockNew(classBlockSyntax) End Function Public Overrides Function VisitStructureBlock(ByVal structureBlockSyntax As StructureBlockSyntax) As SingleNamespaceOrTypeDeclaration Return VisitTypeBlockNew(structureBlockSyntax) End Function Public Overrides Function VisitInterfaceBlock(ByVal interfaceBlockSyntax As InterfaceBlockSyntax) As SingleNamespaceOrTypeDeclaration Return VisitTypeBlockNew(interfaceBlockSyntax) End Function Public Overrides Function VisitEnumBlock(enumBlockSyntax As EnumBlockSyntax) As SingleNamespaceOrTypeDeclaration Dim declarationSyntax As EnumStatementSyntax = enumBlockSyntax.EnumStatement Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = If(declarationSyntax.AttributeLists.Any(), SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes, SingleTypeDeclaration.TypeDeclarationFlags.None) If (declarationSyntax.UnderlyingType IsNot Nothing) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations End If Dim memberNames = GetMemberNames(enumBlockSyntax, declFlags) Return New SingleTypeDeclaration( kind:=GetKind(declarationSyntax.Kind), name:=declarationSyntax.Identifier.ValueText, arity:=0, modifiers:=GetModifiers(declarationSyntax.Modifiers), declFlags:=declFlags, syntaxReference:=_syntaxTree.GetReference(enumBlockSyntax), nameLocation:=_syntaxTree.GetLocation(enumBlockSyntax.EnumStatement.Identifier.Span), memberNames:=memberNames, children:=VisitTypeChildren(enumBlockSyntax.Members)) End Function Private Function VisitTypeChildren(members As SyntaxList(Of StatementSyntax)) As ImmutableArray(Of SingleTypeDeclaration) If members.Count = 0 Then Return ImmutableArray(Of SingleTypeDeclaration).Empty End If Dim children = ArrayBuilder(Of SingleTypeDeclaration).GetInstance() For Each member In members Dim typeDecl = TryCast(Visit(member), SingleTypeDeclaration) If typeDecl IsNot Nothing Then children.Add(typeDecl) End If Next Return children.ToImmutableAndFree() End Function ''' <summary> ''' Pool of builders used to create our member name sets. Importantly, these use ''' <see cref="CaseInsensitiveComparison.Comparer"/> so that name lookup happens in an ''' appropriate manner for VB identifiers. This allows fast member name O(log(n)) even if ''' the casing doesn't match. ''' </summary> Private Shared ReadOnly s_memberNameBuilderPool As New ObjectPool(Of ImmutableHashSet(Of String).Builder)( Function() ImmutableHashSet.CreateBuilder(IdentifierComparison.Comparer)) Private Shared Function ToImmutableAndFree(builder As ImmutableHashSet(Of String).Builder) As ImmutableHashSet(Of String) Dim result = builder.ToImmutable() builder.Clear() s_memberNameBuilderPool.Free(builder) Return result End Function Private Function GetNonTypeMemberNames(members As SyntaxList(Of StatementSyntax), ByRef declFlags As SingleTypeDeclaration.TypeDeclarationFlags) As ImmutableHashSet(Of String) Dim anyMethodHadExtensionSyntax = False Dim anyMemberHasAttributes = False Dim anyNonTypeMembers = False Dim results = s_memberNameBuilderPool.Allocate() For Each statement In members Select Case statement.Kind Case SyntaxKind.FieldDeclaration anyNonTypeMembers = True Dim field = DirectCast(statement, FieldDeclarationSyntax) If field.AttributeLists.Any Then anyMemberHasAttributes = True End If For Each decl In field.Declarators For Each name In decl.Names results.Add(name.Identifier.ValueText) Next Next Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock anyNonTypeMembers = True Dim methodDecl = DirectCast(statement, MethodBlockBaseSyntax).BlockStatement If methodDecl.AttributeLists.Any Then anyMemberHasAttributes = True End If AddMemberNames(methodDecl, results) Case SyntaxKind.PropertyBlock anyNonTypeMembers = True Dim propertyDecl = DirectCast(statement, PropertyBlockSyntax) If propertyDecl.PropertyStatement.AttributeLists.Any Then anyMemberHasAttributes = True Else For Each a In propertyDecl.Accessors If a.BlockStatement.AttributeLists.Any Then anyMemberHasAttributes = True End If Next End If AddMemberNames(propertyDecl.PropertyStatement, results) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.SubNewStatement, SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement, SyntaxKind.OperatorStatement, SyntaxKind.PropertyStatement anyNonTypeMembers = True Dim methodDecl = DirectCast(statement, MethodBaseSyntax) If methodDecl.AttributeLists.Any Then anyMemberHasAttributes = True End If AddMemberNames(methodDecl, results) Case SyntaxKind.EventBlock anyNonTypeMembers = True Dim eventDecl = DirectCast(statement, EventBlockSyntax) If eventDecl.EventStatement.AttributeLists.Any Then anyMemberHasAttributes = True Else For Each a In eventDecl.Accessors If a.BlockStatement.AttributeLists.Any Then anyMemberHasAttributes = True End If Next End If Dim name = eventDecl.EventStatement.Identifier.ValueText results.Add(name) Case SyntaxKind.EventStatement anyNonTypeMembers = True Dim eventDecl = DirectCast(statement, EventStatementSyntax) If eventDecl.AttributeLists.Any Then anyMemberHasAttributes = True End If Dim name = eventDecl.Identifier.ValueText results.Add(name) End Select Next If (anyMemberHasAttributes) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes End If If (anyNonTypeMembers) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers End If Return ToImmutableAndFree(results) End Function Private Function GetMemberNames(enumBlockSyntax As EnumBlockSyntax, ByRef declFlags As SingleTypeDeclaration.TypeDeclarationFlags) As ImmutableHashSet(Of String) Dim members = enumBlockSyntax.Members If (members.Count <> 0) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers End If Dim results = s_memberNameBuilderPool.Allocate() Dim anyMemberHasAttributes As Boolean = False For Each member In enumBlockSyntax.Members ' skip empty statements that represent invalid syntax in the Enum: If member.Kind = SyntaxKind.EnumMemberDeclaration Then Dim enumMember = DirectCast(member, EnumMemberDeclarationSyntax) results.Add(enumMember.Identifier.ValueText) If Not anyMemberHasAttributes AndAlso enumMember.AttributeLists.Any Then anyMemberHasAttributes = True End If End If Next If (anyMemberHasAttributes) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes End If Return ToImmutableAndFree(results) End Function Private Sub AddMemberNames(methodDecl As MethodBaseSyntax, results As ImmutableHashSet(Of String).Builder) Dim name = SourceMethodSymbol.GetMemberNameFromSyntax(methodDecl) results.Add(name) End Sub Public Overrides Function VisitDelegateStatement(node As DelegateStatementSyntax) As SingleNamespaceOrTypeDeclaration Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = If(node.AttributeLists.Any(), SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes, SingleTypeDeclaration.TypeDeclarationFlags.None) declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers Return New SingleTypeDeclaration( kind:=DeclarationKind.Delegate, name:=node.Identifier.ValueText, arity:=GetArity(node.TypeParameterList), modifiers:=GetModifiers(node.Modifiers), declFlags:=declFlags, syntaxReference:=_syntaxTree.GetReference(node), nameLocation:=_syntaxTree.GetLocation(node.Identifier.Span), memberNames:=ImmutableHashSet(Of String).Empty, children:=ImmutableArray(Of SingleTypeDeclaration).Empty) End Function Public Overrides Function VisitEventStatement(node As EventStatementSyntax) As SingleNamespaceOrTypeDeclaration If node.AsClause IsNot Nothing OrElse node.ImplementsClause IsNot Nothing Then ' this event will not need a type Return Nothing End If Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = If(node.AttributeLists.Any(), SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes, SingleTypeDeclaration.TypeDeclarationFlags.None) declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers Return New SingleTypeDeclaration( kind:=DeclarationKind.EventSyntheticDelegate, name:=node.Identifier.ValueText, arity:=0, modifiers:=GetModifiers(node.Modifiers), declFlags:=declFlags, syntaxReference:=_syntaxTree.GetReference(node), nameLocation:=_syntaxTree.GetLocation(node.Identifier.Span), memberNames:=ImmutableHashSet(Of String).Empty, children:=ImmutableArray(Of SingleTypeDeclaration).Empty) End Function ' Public because BinderCache uses it also. Public Shared Function GetKind(kind As SyntaxKind) As DeclarationKind Select Case kind Case SyntaxKind.ClassStatement : Return DeclarationKind.Class Case SyntaxKind.InterfaceStatement : Return DeclarationKind.Interface Case SyntaxKind.StructureStatement : Return DeclarationKind.Structure Case SyntaxKind.NamespaceStatement : Return DeclarationKind.Namespace Case SyntaxKind.ModuleStatement : Return DeclarationKind.Module Case SyntaxKind.EnumStatement : Return DeclarationKind.Enum Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement : Return DeclarationKind.Delegate Case Else Throw ExceptionUtilities.UnexpectedValue(kind) End Select End Function ' Public because BinderCache uses it also. Public Shared Function GetArity(typeParamsSyntax As TypeParameterListSyntax) As Integer If typeParamsSyntax Is Nothing Then Return 0 Else Return typeParamsSyntax.Parameters.Count End If End Function Private Shared Function GetModifiers(modifiers As SyntaxTokenList) As DeclarationModifiers Dim result As DeclarationModifiers = DeclarationModifiers.None For Each modifier In modifiers Dim bit As DeclarationModifiers = 0 Select Case modifier.Kind Case SyntaxKind.MustInheritKeyword : bit = DeclarationModifiers.MustInherit Case SyntaxKind.NotInheritableKeyword : bit = DeclarationModifiers.NotInheritable Case SyntaxKind.PartialKeyword : bit = DeclarationModifiers.Partial Case SyntaxKind.ShadowsKeyword : bit = DeclarationModifiers.Shadows Case SyntaxKind.PublicKeyword : bit = DeclarationModifiers.Public Case SyntaxKind.ProtectedKeyword : bit = DeclarationModifiers.Protected Case SyntaxKind.FriendKeyword : bit = DeclarationModifiers.Friend Case SyntaxKind.PrivateKeyword : bit = DeclarationModifiers.Private Case SyntaxKind.ShadowsKeyword : bit = DeclarationModifiers.Shadows Case SyntaxKind.MustInheritKeyword : bit = DeclarationModifiers.MustInherit Case SyntaxKind.NotInheritableKeyword : bit = DeclarationModifiers.NotInheritable Case SyntaxKind.PartialKeyword : bit = DeclarationModifiers.Partial Case SyntaxKind.SharedKeyword : bit = DeclarationModifiers.Shared Case SyntaxKind.ReadOnlyKeyword : bit = DeclarationModifiers.ReadOnly Case SyntaxKind.WriteOnlyKeyword : bit = DeclarationModifiers.WriteOnly Case SyntaxKind.OverridesKeyword : bit = DeclarationModifiers.Overrides Case SyntaxKind.OverridableKeyword : bit = DeclarationModifiers.Overridable Case SyntaxKind.MustOverrideKeyword : bit = DeclarationModifiers.MustOverride Case SyntaxKind.NotOverridableKeyword : bit = DeclarationModifiers.NotOverridable Case SyntaxKind.OverloadsKeyword : bit = DeclarationModifiers.Overloads Case SyntaxKind.WithEventsKeyword : bit = DeclarationModifiers.WithEvents Case SyntaxKind.DimKeyword : bit = DeclarationModifiers.Dim Case SyntaxKind.ConstKeyword : bit = DeclarationModifiers.Const Case SyntaxKind.DefaultKeyword : bit = DeclarationModifiers.Default Case SyntaxKind.StaticKeyword : bit = DeclarationModifiers.Static Case SyntaxKind.WideningKeyword : bit = DeclarationModifiers.Widening Case SyntaxKind.NarrowingKeyword : bit = DeclarationModifiers.Narrowing Case SyntaxKind.AsyncKeyword : bit = DeclarationModifiers.Async Case SyntaxKind.IteratorKeyword : bit = DeclarationModifiers.Iterator Case Else ' It is possible to run into other tokens here, but only in error conditions. ' We are going to ignore them here. If Not modifier.GetDiagnostics().Any(Function(d) d.Severity = DiagnosticSeverity.Error) Then Throw ExceptionUtilities.UnexpectedValue(modifier.Kind) End If End Select result = result Or bit Next Return result End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend NotInheritable Class DeclarationTreeBuilder Inherits VisualBasicSyntaxVisitor(Of SingleNamespaceOrTypeDeclaration) ' The root namespace, expressing as an array of strings, one for each component. Private ReadOnly _rootNamespace As ImmutableArray(Of String) Private ReadOnly _scriptClassName As String Private ReadOnly _isSubmission As Boolean Private ReadOnly _syntaxTree As SyntaxTree ' <summary> ' Any special attributes we may be referencing through a using alias in the file. ' For example <c>imports X = System.Runtime.CompilerServices.TypeForwardedToAttribute</c>. ' </summary> Private _aliasedQuickAttributes As QuickAttributes Public Shared Function ForTree(tree As SyntaxTree, rootNamespace As ImmutableArray(Of String), scriptClassName As String, isSubmission As Boolean) As RootSingleNamespaceDeclaration Dim builder = New DeclarationTreeBuilder(tree, rootNamespace, scriptClassName, isSubmission) Dim decl = DirectCast(builder.ForDeclaration(tree.GetRoot()), RootSingleNamespaceDeclaration) Return decl End Function Private Sub New(syntaxTree As SyntaxTree, rootNamespace As ImmutableArray(Of String), scriptClassName As String, isSubmission As Boolean) _syntaxTree = syntaxTree _rootNamespace = rootNamespace _scriptClassName = scriptClassName _isSubmission = isSubmission End Sub Private Function ForDeclaration(node As SyntaxNode) As SingleNamespaceOrTypeDeclaration Return Visit(node) End Function Private Function VisitNamespaceChildren(node As VisualBasicSyntaxNode, members As SyntaxList(Of StatementSyntax)) As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) Dim implicitClass As SingleNamespaceOrTypeDeclaration = Nothing Dim childrenBuilder = VisitNamespaceChildren(node, members, implicitClass) If implicitClass IsNot Nothing Then childrenBuilder.Add(implicitClass) End If Return childrenBuilder.ToImmutableAndFree() End Function Private Function VisitNamespaceChildren(node As VisualBasicSyntaxNode, members As SyntaxList(Of StatementSyntax), <Out()> ByRef implicitClass As SingleNamespaceOrTypeDeclaration) As ArrayBuilder(Of SingleNamespaceOrTypeDeclaration) Dim children = ArrayBuilder(Of SingleNamespaceOrTypeDeclaration).GetInstance() Dim implicitClassTypeChildren = ArrayBuilder(Of SingleTypeDeclaration).GetInstance() ' We look for any members that are not allowed in namespace. ' If there are any we create an implicit class to wrap them. Dim requiresImplicitClass = False For Each member In members Dim namespaceOrType As SingleNamespaceOrTypeDeclaration = Visit(member) If namespaceOrType IsNot Nothing Then If namespaceOrType.Kind = DeclarationKind.EventSyntheticDelegate Then ' broken code scenario. Event declared in namespace created a delegate declaration which should go into the ' implicit class implicitClassTypeChildren.Add(DirectCast(namespaceOrType, SingleTypeDeclaration)) requiresImplicitClass = True Else children.Add(namespaceOrType) End If ElseIf Not requiresImplicitClass Then requiresImplicitClass = member.Kind <> SyntaxKind.IncompleteMember AndAlso member.Kind <> SyntaxKind.EmptyStatement End If Next If requiresImplicitClass Then ' The implicit class is not static and has no extensions Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = SingleTypeDeclaration.TypeDeclarationFlags.None Dim memberNames = GetNonTypeMemberNames(members, declFlags) implicitClass = CreateImplicitClass( node, memberNames, implicitClassTypeChildren.ToImmutable, declFlags) Else implicitClass = Nothing End If implicitClassTypeChildren.Free() Return children End Function Private Shared Function GetReferenceDirectives(compilationUnit As CompilationUnitSyntax) As ImmutableArray(Of ReferenceDirective) Dim directiveNodes = compilationUnit.GetReferenceDirectives( Function(d) Not d.File.ContainsDiagnostics AndAlso Not String.IsNullOrEmpty(d.File.ValueText)) If directiveNodes.Count = 0 Then Return ImmutableArray(Of ReferenceDirective).Empty End If Dim directives = ArrayBuilder(Of ReferenceDirective).GetInstance(directiveNodes.Count) For Each directiveNode In directiveNodes directives.Add(New ReferenceDirective(directiveNode.File.ValueText, New SourceLocation(directiveNode))) Next Return directives.ToImmutableAndFree() End Function Private Function CreateImplicitClass(parent As VisualBasicSyntaxNode, memberNames As ImmutableHashSet(Of String), children As ImmutableArray(Of SingleTypeDeclaration), declFlags As SingleTypeDeclaration.TypeDeclarationFlags) As SingleNamespaceOrTypeDeclaration Dim parentReference = _syntaxTree.GetReference(parent) Return New SingleTypeDeclaration( kind:=DeclarationKind.ImplicitClass, name:=TypeSymbol.ImplicitTypeName, arity:=0, modifiers:=DeclarationModifiers.Friend Or DeclarationModifiers.Partial Or DeclarationModifiers.NotInheritable, declFlags:=declFlags, syntaxReference:=parentReference, nameLocation:=parentReference.GetLocation(), memberNames:=memberNames, children:=children, quickAttributes:=QuickAttributes.None) End Function Private Function CreateScriptClass(parent As VisualBasicSyntaxNode, children As ImmutableArray(Of SingleTypeDeclaration), memberNames As ImmutableHashSet(Of String), declFlags As SingleTypeDeclaration.TypeDeclarationFlags) As SingleNamespaceOrTypeDeclaration Debug.Assert(parent.Kind = SyntaxKind.CompilationUnit AndAlso _syntaxTree.Options.Kind <> SourceCodeKind.Regular) ' script class is represented by the parent node: Dim parentReference = _syntaxTree.GetReference(parent) Dim fullName = _scriptClassName.Split("."c) ' Note: The symbol representing the merged declarations uses parentReference to enumerate non-type members. Dim decl As SingleNamespaceOrTypeDeclaration = New SingleTypeDeclaration( kind:=If(_isSubmission, DeclarationKind.Submission, DeclarationKind.Script), name:=fullName.Last(), arity:=0, modifiers:=DeclarationModifiers.Friend Or DeclarationModifiers.Partial Or DeclarationModifiers.NotInheritable, declFlags:=declFlags, syntaxReference:=parentReference, nameLocation:=parentReference.GetLocation(), memberNames:=memberNames, children:=children, quickAttributes:=QuickAttributes.None) For i = fullName.Length - 2 To 0 Step -1 decl = New SingleNamespaceDeclaration( name:=fullName(i), hasImports:=False, syntaxReference:=parentReference, nameLocation:=parentReference.GetLocation(), children:=ImmutableArray.Create(Of SingleNamespaceOrTypeDeclaration)(decl)) Next Return decl End Function Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As SingleNamespaceOrTypeDeclaration Dim children As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) Dim globalChildren As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) = Nothing Dim nonGlobal As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) = Nothing Dim syntaxRef = _syntaxTree.GetReference(node) Dim implicitClass As SingleNamespaceOrTypeDeclaration = Nothing _aliasedQuickAttributes = GetAliasedQuickAttributes(node) Dim referenceDirectives As ImmutableArray(Of ReferenceDirective) If _syntaxTree.Options.Kind <> SourceCodeKind.Regular Then Dim childrenBuilder = ArrayBuilder(Of SingleNamespaceOrTypeDeclaration).GetInstance() Dim scriptChildren = ArrayBuilder(Of SingleTypeDeclaration).GetInstance() For Each member In node.Members Dim decl = Visit(member) If decl IsNot Nothing Then ' Although namespaces are not allowed in script code process them ' here as if they were to improve error reporting. If decl.Kind = DeclarationKind.Namespace Then childrenBuilder.Add(decl) Else scriptChildren.Add(DirectCast(decl, SingleTypeDeclaration)) End If End If Next 'Script class is not static and contains no extensions. Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = SingleTypeDeclaration.TypeDeclarationFlags.None Dim memberNames = GetNonTypeMemberNames(node.Members, declFlags) implicitClass = CreateScriptClass(node, scriptChildren.ToImmutableAndFree(), memberNames, declFlags) children = childrenBuilder.ToImmutableAndFree() referenceDirectives = GetReferenceDirectives(node) Else children = VisitNamespaceChildren(node, node.Members, implicitClass).ToImmutableAndFree() referenceDirectives = ImmutableArray(Of ReferenceDirective).Empty End If ' Find children within NamespaceGlobal separately FindGlobalDeclarations(children, implicitClass, globalChildren, nonGlobal) If _rootNamespace.Length = 0 Then ' No project-level root namespace specified. Both global and nested children within the root. Return New RootSingleNamespaceDeclaration( hasImports:=True, treeNode:=_syntaxTree.GetReference(node), children:=globalChildren.Concat(nonGlobal), referenceDirectives:=referenceDirectives, hasAssemblyAttributes:=node.Attributes.Any) Else ' Project-level root namespace. All children without explicit global are children ' of the project-level root namespace. The root declaration has the project level namespace ' and global children within it. ' Note that we need to built the project level namespace even if it has no children [Bug 4879[ Dim projectNs = BuildRootNamespace(node, nonGlobal) globalChildren = globalChildren.Add(projectNs) Dim newChildren = globalChildren.OfType(Of SingleNamespaceOrTypeDeclaration).AsImmutable() Return New RootSingleNamespaceDeclaration( hasImports:=True, treeNode:=_syntaxTree.GetReference(node), children:=newChildren, referenceDirectives:=referenceDirectives, hasAssemblyAttributes:=node.Attributes.Any) End If End Function Private Shared Function GetAliasedQuickAttributes(compilationUnit As CompilationUnitSyntax) As QuickAttributes Dim result = QuickAttributes.None For Each directive In compilationUnit.Imports For Each clause In directive.ImportsClauses If clause.Kind <> SyntaxKind.SimpleImportsClause Then Continue For End If Dim simpleImportsClause = DirectCast(clause, SimpleImportsClauseSyntax) If simpleImportsClause.Alias Is Nothing Then Continue For End If result = result Or QuickAttributeHelpers.GetQuickAttributes(QuickAttributeChecker.GetFinalName(simpleImportsClause.Name), inAttribute:=False) Next Next Return result End Function ' Given a set of single declarations, get the sets of global and non-global declarations. ' A regular declaration is put into "non-global declarations". ' A "Namespace Global" is not put in either place, but all its direct children are put into "global declarations". Private Sub FindGlobalDeclarations(declarations As ImmutableArray(Of SingleNamespaceOrTypeDeclaration), implicitClass As SingleNamespaceOrTypeDeclaration, ByRef globalDeclarations As ImmutableArray(Of SingleNamespaceOrTypeDeclaration), ByRef nonGlobal As ImmutableArray(Of SingleNamespaceOrTypeDeclaration)) Dim globalBuilder = ArrayBuilder(Of SingleNamespaceOrTypeDeclaration).GetInstance() Dim nonGlobalBuilder = ArrayBuilder(Of SingleNamespaceOrTypeDeclaration).GetInstance() If implicitClass IsNot Nothing Then nonGlobalBuilder.Add(implicitClass) End If For Each decl In declarations Dim nsDecl As SingleNamespaceDeclaration = TryCast(decl, SingleNamespaceDeclaration) If nsDecl IsNot Nothing AndAlso nsDecl.IsGlobalNamespace Then ' Namespace Global. globalBuilder.AddRange(nsDecl.Children) Else ' regular declaration nonGlobalBuilder.Add(decl) End If Next globalDeclarations = globalBuilder.ToImmutableAndFree() nonGlobal = nonGlobalBuilder.ToImmutableAndFree() End Sub Private Function UnescapeIdentifier(identifier As String) As String If identifier(0) = "[" Then Debug.Assert(identifier(identifier.Length - 1) = "]") Return identifier.Substring(1, identifier.Length - 2) Else Return identifier End If End Function ' Build the declaration for the root (project-level) namespace. Private Function BuildRootNamespace(node As CompilationUnitSyntax, children As ImmutableArray(Of SingleNamespaceOrTypeDeclaration)) As SingleNamespaceDeclaration Debug.Assert(_rootNamespace.Length > 0) Dim ns As SingleNamespaceDeclaration = Nothing ' The compilation node will count as a location for the innermost project level ' namespace. i.e. if the project level namespace is "Goo.Bar", then each compilation unit ' is a location for "Goo.Bar". "Goo" still has no syntax location though. ' ' By doing this we ensure that top level type and namespace declarations will have ' symbols whose parent namespace symbol points to the parent container CompilationUnit. ' This ensures parity with the case where their is no 'project-level' namespace and the ' global namespaces point to the compilation unit syntax. Dim syntaxReference = _syntaxTree.GetReference(node) Dim nameLocation = syntaxReference.GetLocation() ' traverse components from right to left For i = _rootNamespace.Length - 1 To 0 Step -1 ' treat all root namespace parts as implicitly escaped. ' a root namespace with a name "global" will actually create "Global.[global]" ns = New SingleNamespaceDeclaration( name:=UnescapeIdentifier(_rootNamespace(i)), hasImports:=True, syntaxReference:=syntaxReference, nameLocation:=nameLocation, children:=children, isPartOfRootNamespace:=True) ' Only the innermost namespace will point at compilation unit. All other outer ' namespaces will have no location. syntaxReference = Nothing nameLocation = Nothing ' This namespace is the child of the namespace to the left. children = ImmutableArray.Create(Of SingleNamespaceOrTypeDeclaration)(ns) Next Return ns End Function Public Overrides Function VisitNamespaceBlock(nsBlockSyntax As NamespaceBlockSyntax) As SingleNamespaceOrTypeDeclaration Dim nsDeclSyntax As NamespaceStatementSyntax = nsBlockSyntax.NamespaceStatement Dim children = VisitNamespaceChildren(nsBlockSyntax, nsBlockSyntax.Members) Dim name As NameSyntax = nsDeclSyntax.Name While TypeOf name Is QualifiedNameSyntax Dim dotted = DirectCast(name, QualifiedNameSyntax) Dim ns = New SingleNamespaceDeclaration( name:=dotted.Right.Identifier.ValueText, hasImports:=True, syntaxReference:=_syntaxTree.GetReference(dotted), nameLocation:=_syntaxTree.GetLocation(dotted.Right.Span), children:=children) children = {ns}.OfType(Of SingleNamespaceOrTypeDeclaration).AsImmutable() name = dotted.Left End While ' This is either the global namespace, or a regular namespace. Represent the global namespace ' with the empty string. If name.Kind = SyntaxKind.GlobalName Then If nsBlockSyntax.Parent.Kind = SyntaxKind.CompilationUnit Then ' Namespace Global only allowed as direct child of compilation. Return New GlobalNamespaceDeclaration( hasImports:=True, syntaxReference:=_syntaxTree.GetReference(name), nameLocation:=_syntaxTree.GetLocation(name.Span), children:=children) Else ' Error for this will be diagnosed later. Create a namespace named "Global" for error recovery. (see corresponding code in BinderFactory) Return New SingleNamespaceDeclaration( name:="Global", hasImports:=True, syntaxReference:=_syntaxTree.GetReference(name), nameLocation:=_syntaxTree.GetLocation(name.Span), children:=children) End If Else Return New SingleNamespaceDeclaration( name:=DirectCast(name, IdentifierNameSyntax).Identifier.ValueText, hasImports:=True, syntaxReference:=_syntaxTree.GetReference(name), nameLocation:=_syntaxTree.GetLocation(name.Span), children:=children) End If End Function Private Structure TypeBlockInfo Public ReadOnly TypeBlockSyntax As TypeBlockSyntax Public ReadOnly TypeDeclaration As SingleTypeDeclaration Public ReadOnly NestedTypes As ArrayBuilder(Of Integer) Public Sub New(typeBlockSyntax As TypeBlockSyntax) MyClass.New(typeBlockSyntax, Nothing, Nothing) End Sub Private Sub New(typeBlockSyntax As TypeBlockSyntax, declaration As SingleTypeDeclaration, nestedTypes As ArrayBuilder(Of Integer)) Me.TypeBlockSyntax = typeBlockSyntax Me.TypeDeclaration = declaration Me.NestedTypes = nestedTypes End Sub Public Function WithNestedTypes(nested As ArrayBuilder(Of Integer)) As TypeBlockInfo Debug.Assert(Me.TypeDeclaration Is Nothing) Debug.Assert(Me.NestedTypes Is Nothing) Debug.Assert(nested IsNot Nothing) Return New TypeBlockInfo(Me.TypeBlockSyntax, Nothing, nested) End Function Public Function WithDeclaration(declaration As SingleTypeDeclaration) As TypeBlockInfo Debug.Assert(Me.TypeDeclaration Is Nothing) Debug.Assert(declaration IsNot Nothing) Return New TypeBlockInfo(Me.TypeBlockSyntax, declaration, Me.NestedTypes) End Function End Structure Private Function VisitTypeBlockNew(topTypeBlockSyntax As TypeBlockSyntax) As SingleNamespaceOrTypeDeclaration Dim typeStack = ArrayBuilder(Of TypeBlockInfo).GetInstance typeStack.Add(New TypeBlockInfo(topTypeBlockSyntax)) ' Fill the chain with types Dim index As Integer = 0 While index < typeStack.Count Dim typeEntry As TypeBlockInfo = typeStack(index) Dim members As SyntaxList(Of StatementSyntax) = typeEntry.TypeBlockSyntax.Members If members.Count > 0 Then Dim nestedTypeIndices As ArrayBuilder(Of Integer) = Nothing For Each member In members Select Case member.Kind Case SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock If nestedTypeIndices Is Nothing Then nestedTypeIndices = ArrayBuilder(Of Integer).GetInstance() End If nestedTypeIndices.Add(typeStack.Count) typeStack.Add(New TypeBlockInfo(DirectCast(member, TypeBlockSyntax))) End Select Next If nestedTypeIndices IsNot Nothing Then typeStack(index) = typeEntry.WithNestedTypes(nestedTypeIndices) End If End If index += 1 End While ' Process types Debug.Assert(index = typeStack.Count) Dim childrenBuilder = ArrayBuilder(Of SingleTypeDeclaration).GetInstance() While index > 0 index -= 1 Dim typeEntry As TypeBlockInfo = typeStack(index) Dim children = ImmutableArray(Of SingleTypeDeclaration).Empty Dim members As SyntaxList(Of StatementSyntax) = typeEntry.TypeBlockSyntax.Members If members.Count > 0 Then childrenBuilder.Clear() For Each member In members Select Case member.Kind Case SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock ' should be processed already Case Else Dim typeDecl = TryCast(Visit(member), SingleTypeDeclaration) If typeDecl IsNot Nothing Then childrenBuilder.Add(typeDecl) End If End Select Next Dim nestedTypes As ArrayBuilder(Of Integer) = typeEntry.NestedTypes If nestedTypes IsNot Nothing Then For i = 0 To nestedTypes.Count - 1 childrenBuilder.Add(typeStack(nestedTypes(i)).TypeDeclaration) Next nestedTypes.Free() End If children = childrenBuilder.ToImmutable() End If Dim typeBlockSyntax As TypeBlockSyntax = typeEntry.TypeBlockSyntax Dim declarationSyntax As TypeStatementSyntax = typeBlockSyntax.BlockStatement ' Get the arity for things that can have arity. Dim typeArity As Integer = 0 Select Case typeBlockSyntax.Kind Case SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock typeArity = GetArity(declarationSyntax.TypeParameterList) End Select Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = If(declarationSyntax.AttributeLists.Any(), SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes, SingleTypeDeclaration.TypeDeclarationFlags.None) If (typeBlockSyntax.Inherits.Any) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations End If Dim memberNames = GetNonTypeMemberNames(typeBlockSyntax.Members, declFlags) Dim quickAttributes = GetQuickAttributes(typeBlockSyntax.BlockStatement.AttributeLists) typeStack(index) = typeEntry.WithDeclaration( New SingleTypeDeclaration( kind:=GetKind(declarationSyntax.Kind), name:=declarationSyntax.Identifier.ValueText, arity:=typeArity, modifiers:=GetModifiers(declarationSyntax.Modifiers), declFlags:=declFlags, syntaxReference:=_syntaxTree.GetReference(typeBlockSyntax), nameLocation:=_syntaxTree.GetLocation(typeBlockSyntax.BlockStatement.Identifier.Span), memberNames:=memberNames, children:=children, quickAttributes:=quickAttributes Or _aliasedQuickAttributes)) End While childrenBuilder.Free() Dim result As SingleNamespaceOrTypeDeclaration = typeStack(0).TypeDeclaration typeStack.Free() Return result End Function Public Overrides Function VisitModuleBlock(ByVal moduleBlockSyntax As ModuleBlockSyntax) As SingleNamespaceOrTypeDeclaration Return VisitTypeBlockNew(moduleBlockSyntax) End Function Public Overrides Function VisitClassBlock(ByVal classBlockSyntax As ClassBlockSyntax) As SingleNamespaceOrTypeDeclaration Return VisitTypeBlockNew(classBlockSyntax) End Function Public Overrides Function VisitStructureBlock(ByVal structureBlockSyntax As StructureBlockSyntax) As SingleNamespaceOrTypeDeclaration Return VisitTypeBlockNew(structureBlockSyntax) End Function Public Overrides Function VisitInterfaceBlock(ByVal interfaceBlockSyntax As InterfaceBlockSyntax) As SingleNamespaceOrTypeDeclaration Return VisitTypeBlockNew(interfaceBlockSyntax) End Function Public Overrides Function VisitEnumBlock(enumBlockSyntax As EnumBlockSyntax) As SingleNamespaceOrTypeDeclaration Dim declarationSyntax As EnumStatementSyntax = enumBlockSyntax.EnumStatement Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = If(declarationSyntax.AttributeLists.Any(), SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes, SingleTypeDeclaration.TypeDeclarationFlags.None) If (declarationSyntax.UnderlyingType IsNot Nothing) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasBaseDeclarations End If Dim memberNames = GetMemberNames(enumBlockSyntax, declFlags) Dim quickAttributes = GetQuickAttributes(enumBlockSyntax.EnumStatement.AttributeLists) Return New SingleTypeDeclaration( kind:=GetKind(declarationSyntax.Kind), name:=declarationSyntax.Identifier.ValueText, arity:=0, modifiers:=GetModifiers(declarationSyntax.Modifiers), declFlags:=declFlags, syntaxReference:=_syntaxTree.GetReference(enumBlockSyntax), nameLocation:=_syntaxTree.GetLocation(enumBlockSyntax.EnumStatement.Identifier.Span), memberNames:=memberNames, children:=VisitTypeChildren(enumBlockSyntax.Members), quickAttributes:=quickAttributes Or _aliasedQuickAttributes) End Function Private Shared Function GetQuickAttributes(attributeLists As SyntaxList(Of AttributeListSyntax)) As QuickAttributes Dim result = QuickAttributes.None For Each attributeList In attributeLists For Each attribute In attributeList.Attributes result = result Or QuickAttributeHelpers.GetQuickAttributes(QuickAttributeChecker.GetFinalName(attribute.Name), inAttribute:=True) Next Next Return result End Function Private Function VisitTypeChildren(members As SyntaxList(Of StatementSyntax)) As ImmutableArray(Of SingleTypeDeclaration) If members.Count = 0 Then Return ImmutableArray(Of SingleTypeDeclaration).Empty End If Dim children = ArrayBuilder(Of SingleTypeDeclaration).GetInstance() For Each member In members Dim typeDecl = TryCast(Visit(member), SingleTypeDeclaration) If typeDecl IsNot Nothing Then children.Add(typeDecl) End If Next Return children.ToImmutableAndFree() End Function ''' <summary> ''' Pool of builders used to create our member name sets. Importantly, these use ''' <see cref="CaseInsensitiveComparison.Comparer"/> so that name lookup happens in an ''' appropriate manner for VB identifiers. This allows fast member name O(log(n)) even if ''' the casing doesn't match. ''' </summary> Private Shared ReadOnly s_memberNameBuilderPool As New ObjectPool(Of ImmutableHashSet(Of String).Builder)( Function() ImmutableHashSet.CreateBuilder(IdentifierComparison.Comparer)) Private Shared Function ToImmutableAndFree(builder As ImmutableHashSet(Of String).Builder) As ImmutableHashSet(Of String) Dim result = builder.ToImmutable() builder.Clear() s_memberNameBuilderPool.Free(builder) Return result End Function Private Function GetNonTypeMemberNames(members As SyntaxList(Of StatementSyntax), ByRef declFlags As SingleTypeDeclaration.TypeDeclarationFlags) As ImmutableHashSet(Of String) Dim anyMethodHadExtensionSyntax = False Dim anyMemberHasAttributes = False Dim anyNonTypeMembers = False Dim results = s_memberNameBuilderPool.Allocate() For Each statement In members Select Case statement.Kind Case SyntaxKind.FieldDeclaration anyNonTypeMembers = True Dim field = DirectCast(statement, FieldDeclarationSyntax) If field.AttributeLists.Any Then anyMemberHasAttributes = True End If For Each decl In field.Declarators For Each name In decl.Names results.Add(name.Identifier.ValueText) Next Next Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock anyNonTypeMembers = True Dim methodDecl = DirectCast(statement, MethodBlockBaseSyntax).BlockStatement If methodDecl.AttributeLists.Any Then anyMemberHasAttributes = True End If AddMemberNames(methodDecl, results) Case SyntaxKind.PropertyBlock anyNonTypeMembers = True Dim propertyDecl = DirectCast(statement, PropertyBlockSyntax) If propertyDecl.PropertyStatement.AttributeLists.Any Then anyMemberHasAttributes = True Else For Each a In propertyDecl.Accessors If a.BlockStatement.AttributeLists.Any Then anyMemberHasAttributes = True End If Next End If AddMemberNames(propertyDecl.PropertyStatement, results) Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.SubNewStatement, SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement, SyntaxKind.OperatorStatement, SyntaxKind.PropertyStatement anyNonTypeMembers = True Dim methodDecl = DirectCast(statement, MethodBaseSyntax) If methodDecl.AttributeLists.Any Then anyMemberHasAttributes = True End If AddMemberNames(methodDecl, results) Case SyntaxKind.EventBlock anyNonTypeMembers = True Dim eventDecl = DirectCast(statement, EventBlockSyntax) If eventDecl.EventStatement.AttributeLists.Any Then anyMemberHasAttributes = True Else For Each a In eventDecl.Accessors If a.BlockStatement.AttributeLists.Any Then anyMemberHasAttributes = True End If Next End If Dim name = eventDecl.EventStatement.Identifier.ValueText results.Add(name) Case SyntaxKind.EventStatement anyNonTypeMembers = True Dim eventDecl = DirectCast(statement, EventStatementSyntax) If eventDecl.AttributeLists.Any Then anyMemberHasAttributes = True End If Dim name = eventDecl.Identifier.ValueText results.Add(name) End Select Next If (anyMemberHasAttributes) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes End If If (anyNonTypeMembers) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers End If Return ToImmutableAndFree(results) End Function Private Function GetMemberNames(enumBlockSyntax As EnumBlockSyntax, ByRef declFlags As SingleTypeDeclaration.TypeDeclarationFlags) As ImmutableHashSet(Of String) Dim members = enumBlockSyntax.Members If (members.Count <> 0) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers End If Dim results = s_memberNameBuilderPool.Allocate() Dim anyMemberHasAttributes As Boolean = False For Each member In enumBlockSyntax.Members ' skip empty statements that represent invalid syntax in the Enum: If member.Kind = SyntaxKind.EnumMemberDeclaration Then Dim enumMember = DirectCast(member, EnumMemberDeclarationSyntax) results.Add(enumMember.Identifier.ValueText) If Not anyMemberHasAttributes AndAlso enumMember.AttributeLists.Any Then anyMemberHasAttributes = True End If End If Next If (anyMemberHasAttributes) Then declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes End If Return ToImmutableAndFree(results) End Function Private Sub AddMemberNames(methodDecl As MethodBaseSyntax, results As ImmutableHashSet(Of String).Builder) Dim name = SourceMethodSymbol.GetMemberNameFromSyntax(methodDecl) results.Add(name) End Sub Public Overrides Function VisitDelegateStatement(node As DelegateStatementSyntax) As SingleNamespaceOrTypeDeclaration Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = If(node.AttributeLists.Any(), SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes, SingleTypeDeclaration.TypeDeclarationFlags.None) declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers Dim quickAttributes = GetQuickAttributes(node.AttributeLists) Return New SingleTypeDeclaration( kind:=DeclarationKind.Delegate, name:=node.Identifier.ValueText, arity:=GetArity(node.TypeParameterList), modifiers:=GetModifiers(node.Modifiers), declFlags:=declFlags, syntaxReference:=_syntaxTree.GetReference(node), nameLocation:=_syntaxTree.GetLocation(node.Identifier.Span), memberNames:=ImmutableHashSet(Of String).Empty, children:=ImmutableArray(Of SingleTypeDeclaration).Empty, quickAttributes:=quickAttributes Or _aliasedQuickAttributes) End Function Public Overrides Function VisitEventStatement(node As EventStatementSyntax) As SingleNamespaceOrTypeDeclaration If node.AsClause IsNot Nothing OrElse node.ImplementsClause IsNot Nothing Then ' this event will not need a type Return Nothing End If Dim declFlags As SingleTypeDeclaration.TypeDeclarationFlags = If(node.AttributeLists.Any(), SingleTypeDeclaration.TypeDeclarationFlags.HasAnyAttributes, SingleTypeDeclaration.TypeDeclarationFlags.None) declFlags = declFlags Or SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers Dim quickAttributes = GetQuickAttributes(node.AttributeLists) Return New SingleTypeDeclaration( kind:=DeclarationKind.EventSyntheticDelegate, name:=node.Identifier.ValueText, arity:=0, modifiers:=GetModifiers(node.Modifiers), declFlags:=declFlags, syntaxReference:=_syntaxTree.GetReference(node), nameLocation:=_syntaxTree.GetLocation(node.Identifier.Span), memberNames:=ImmutableHashSet(Of String).Empty, children:=ImmutableArray(Of SingleTypeDeclaration).Empty, quickAttributes:=quickAttributes Or _aliasedQuickAttributes) End Function ' Public because BinderCache uses it also. Public Shared Function GetKind(kind As SyntaxKind) As DeclarationKind Select Case kind Case SyntaxKind.ClassStatement : Return DeclarationKind.Class Case SyntaxKind.InterfaceStatement : Return DeclarationKind.Interface Case SyntaxKind.StructureStatement : Return DeclarationKind.Structure Case SyntaxKind.NamespaceStatement : Return DeclarationKind.Namespace Case SyntaxKind.ModuleStatement : Return DeclarationKind.Module Case SyntaxKind.EnumStatement : Return DeclarationKind.Enum Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement : Return DeclarationKind.Delegate Case Else Throw ExceptionUtilities.UnexpectedValue(kind) End Select End Function ' Public because BinderCache uses it also. Public Shared Function GetArity(typeParamsSyntax As TypeParameterListSyntax) As Integer If typeParamsSyntax Is Nothing Then Return 0 Else Return typeParamsSyntax.Parameters.Count End If End Function Private Shared Function GetModifiers(modifiers As SyntaxTokenList) As DeclarationModifiers Dim result As DeclarationModifiers = DeclarationModifiers.None For Each modifier In modifiers Dim bit As DeclarationModifiers = 0 Select Case modifier.Kind Case SyntaxKind.MustInheritKeyword : bit = DeclarationModifiers.MustInherit Case SyntaxKind.NotInheritableKeyword : bit = DeclarationModifiers.NotInheritable Case SyntaxKind.PartialKeyword : bit = DeclarationModifiers.Partial Case SyntaxKind.ShadowsKeyword : bit = DeclarationModifiers.Shadows Case SyntaxKind.PublicKeyword : bit = DeclarationModifiers.Public Case SyntaxKind.ProtectedKeyword : bit = DeclarationModifiers.Protected Case SyntaxKind.FriendKeyword : bit = DeclarationModifiers.Friend Case SyntaxKind.PrivateKeyword : bit = DeclarationModifiers.Private Case SyntaxKind.ShadowsKeyword : bit = DeclarationModifiers.Shadows Case SyntaxKind.MustInheritKeyword : bit = DeclarationModifiers.MustInherit Case SyntaxKind.NotInheritableKeyword : bit = DeclarationModifiers.NotInheritable Case SyntaxKind.PartialKeyword : bit = DeclarationModifiers.Partial Case SyntaxKind.SharedKeyword : bit = DeclarationModifiers.Shared Case SyntaxKind.ReadOnlyKeyword : bit = DeclarationModifiers.ReadOnly Case SyntaxKind.WriteOnlyKeyword : bit = DeclarationModifiers.WriteOnly Case SyntaxKind.OverridesKeyword : bit = DeclarationModifiers.Overrides Case SyntaxKind.OverridableKeyword : bit = DeclarationModifiers.Overridable Case SyntaxKind.MustOverrideKeyword : bit = DeclarationModifiers.MustOverride Case SyntaxKind.NotOverridableKeyword : bit = DeclarationModifiers.NotOverridable Case SyntaxKind.OverloadsKeyword : bit = DeclarationModifiers.Overloads Case SyntaxKind.WithEventsKeyword : bit = DeclarationModifiers.WithEvents Case SyntaxKind.DimKeyword : bit = DeclarationModifiers.Dim Case SyntaxKind.ConstKeyword : bit = DeclarationModifiers.Const Case SyntaxKind.DefaultKeyword : bit = DeclarationModifiers.Default Case SyntaxKind.StaticKeyword : bit = DeclarationModifiers.Static Case SyntaxKind.WideningKeyword : bit = DeclarationModifiers.Widening Case SyntaxKind.NarrowingKeyword : bit = DeclarationModifiers.Narrowing Case SyntaxKind.AsyncKeyword : bit = DeclarationModifiers.Async Case SyntaxKind.IteratorKeyword : bit = DeclarationModifiers.Iterator Case Else ' It is possible to run into other tokens here, but only in error conditions. ' We are going to ignore them here. If Not modifier.GetDiagnostics().Any(Function(d) d.Severity = DiagnosticSeverity.Error) Then Throw ExceptionUtilities.UnexpectedValue(modifier.Kind) End If End Select result = result Or bit Next Return result End Function End Class End Namespace
1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Portable/Declarations/MergedTypeDeclaration.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Linq Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ' An invariant of a merged type declaration is that all of its children are also merged ' declarations. Friend NotInheritable Class MergedTypeDeclaration Inherits MergedNamespaceOrTypeDeclaration Private _declarations As ImmutableArray(Of SingleTypeDeclaration) Private _children As MergedTypeDeclaration() Private _memberNames As ICollection(Of String) Public Property Declarations As ImmutableArray(Of SingleTypeDeclaration) Get Return _declarations End Get Private Set(value As ImmutableArray(Of SingleTypeDeclaration)) _declarations = value End Set End Property Friend Sub New(declarations As ImmutableArray(Of SingleTypeDeclaration)) MyBase.New(SingleNamespaceOrTypeDeclaration.BestName(Of SingleTypeDeclaration)(declarations)) Me.Declarations = declarations End Sub Public ReadOnly Property SyntaxReferences As ImmutableArray(Of SyntaxReference) Get Dim builder = ArrayBuilder(Of SyntaxReference).GetInstance() For Each decl In Declarations Dim syn = decl.SyntaxReference builder.Add(syn) Next Return builder.ToImmutableAndFree() End Get End Property Public Overrides ReadOnly Property Kind As DeclarationKind Get Return Me.Declarations(0).Kind End Get End Property Public ReadOnly Property Arity As Integer Get Return Me.Declarations(0).Arity End Get End Property Public Function GetAttributeDeclarations() As ImmutableArray(Of SyntaxList(Of AttributeListSyntax)) Dim attributeSyntaxBuilder = ArrayBuilder(Of SyntaxList(Of AttributeListSyntax)).GetInstance() For Each decl In Declarations If Not decl.HasAnyAttributes Then Continue For End If Dim syntaxRef = decl.SyntaxReference Dim node = syntaxRef.GetSyntax() Dim attributeSyntaxList As SyntaxList(Of AttributeListSyntax) Select Case node.Kind Case SyntaxKind.ClassBlock, SyntaxKind.ModuleBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock attributeSyntaxList = DirectCast(node, TypeBlockSyntax).BlockStatement.AttributeLists Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement attributeSyntaxList = DirectCast(node, DelegateStatementSyntax).AttributeLists Case SyntaxKind.EnumBlock attributeSyntaxList = DirectCast(node, EnumBlockSyntax).EnumStatement.AttributeLists Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select attributeSyntaxBuilder.Add(attributeSyntaxList) Next Return attributeSyntaxBuilder.ToImmutableAndFree() End Function Public Function GetLexicalSortKey(compilation As VisualBasicCompilation) As LexicalSortKey ' Return first sort key from all declarations. Dim sortKey As LexicalSortKey = New LexicalSortKey(_declarations(0).NameLocation, compilation) For i = 1 To _declarations.Length - 1 sortKey = LexicalSortKey.First(sortKey, New LexicalSortKey(_declarations(i).NameLocation, compilation)) Next Return sortKey End Function Public ReadOnly Property NameLocations As ImmutableArray(Of Location) Get If Declarations.Length = 1 Then Return ImmutableArray.Create(Declarations(0).NameLocation) End If Dim builder = ArrayBuilder(Of Location).GetInstance() For Each decl In Declarations Dim loc = decl.NameLocation If loc IsNot Nothing Then builder.Add(loc) End If Next Return builder.ToImmutableAndFree() End Get End Property Private Shared ReadOnly s_identityFunc As Func(Of SingleTypeDeclaration, SingleTypeDeclaration) = Function(t) t Private Shared ReadOnly s_mergeFunc As Func(Of IEnumerable(Of SingleTypeDeclaration), MergedTypeDeclaration) = Function(g) New MergedTypeDeclaration(ImmutableArray.CreateRange(Of SingleTypeDeclaration)(g)) Private Function MakeChildren() As MergedTypeDeclaration() Dim allSingleTypeDecls As IEnumerable(Of SingleTypeDeclaration) If Declarations.Length = 1 Then allSingleTypeDecls = Declarations(0).Children.OfType(Of SingleTypeDeclaration)() Else allSingleTypeDecls = Declarations.SelectMany(Function(d) d.Children.OfType(Of SingleTypeDeclaration)()) End If Return MakeMergedTypes(allSingleTypeDecls).ToArray() End Function Friend Shared Function MakeMergedTypes(types As IEnumerable(Of SingleTypeDeclaration)) As IEnumerable(Of MergedTypeDeclaration) Return types. GroupBy(s_identityFunc, SingleTypeDeclaration.EqualityComparer). Select(s_mergeFunc) End Function Public Overloads ReadOnly Property Children As ImmutableArray(Of MergedTypeDeclaration) Get If Me._children Is Nothing Then Interlocked.CompareExchange(Me._children, MakeChildren(), Nothing) End If Return Me._children.AsImmutableOrNull() End Get End Property Protected Overrides Function GetDeclarationChildren() As ImmutableArray(Of Declaration) Return StaticCast(Of Declaration).From(Me.Children) End Function Public ReadOnly Property MemberNames As ICollection(Of String) Get If _memberNames Is Nothing Then Dim names = UnionCollection(Of String).Create(Me.Declarations, Function(d) d.MemberNames) Interlocked.CompareExchange(_memberNames, names, Nothing) End If Return _memberNames End Get End Property Public ReadOnly Property AnyMemberHasAttributes As Boolean Get For Each decl In Me.Declarations If decl.AnyMemberHasAttributes Then Return True End If Next Return False End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Diagnostics Imports System.Linq Imports System.Threading Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ' An invariant of a merged type declaration is that all of its children are also merged ' declarations. Friend NotInheritable Class MergedTypeDeclaration Inherits MergedNamespaceOrTypeDeclaration Private _declarations As ImmutableArray(Of SingleTypeDeclaration) Private _children As MergedTypeDeclaration() Private _memberNames As ICollection(Of String) Public Property Declarations As ImmutableArray(Of SingleTypeDeclaration) Get Return _declarations End Get Private Set(value As ImmutableArray(Of SingleTypeDeclaration)) _declarations = value End Set End Property Friend Sub New(declarations As ImmutableArray(Of SingleTypeDeclaration)) MyBase.New(SingleNamespaceOrTypeDeclaration.BestName(Of SingleTypeDeclaration)(declarations)) Me.Declarations = declarations End Sub Public ReadOnly Property SyntaxReferences As ImmutableArray(Of SyntaxReference) Get Dim builder = ArrayBuilder(Of SyntaxReference).GetInstance() For Each decl In Declarations Dim syn = decl.SyntaxReference builder.Add(syn) Next Return builder.ToImmutableAndFree() End Get End Property Public Overrides ReadOnly Property Kind As DeclarationKind Get Return Me.Declarations(0).Kind End Get End Property Public ReadOnly Property Arity As Integer Get Return Me.Declarations(0).Arity End Get End Property Public Function GetAttributeDeclarations(Optional quickAttributes As QuickAttributes? = Nothing) As ImmutableArray(Of SyntaxList(Of AttributeListSyntax)) Dim attributeSyntaxBuilder = ArrayBuilder(Of SyntaxList(Of AttributeListSyntax)).GetInstance() For Each decl In Declarations If Not decl.HasAnyAttributes Then Continue For End If ' if caller is asking for particular quick attributes, don't bother going to syntax ' unless the type actually could expose that attribute. If quickAttributes IsNot Nothing AndAlso (decl.QuickAttributes And quickAttributes.Value) <> 0 Then Continue For End If Dim syntaxRef = decl.SyntaxReference Dim node = syntaxRef.GetSyntax() Dim attributeSyntaxList As SyntaxList(Of AttributeListSyntax) Select Case node.Kind Case SyntaxKind.ClassBlock, SyntaxKind.ModuleBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock attributeSyntaxList = DirectCast(node, TypeBlockSyntax).BlockStatement.AttributeLists Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement attributeSyntaxList = DirectCast(node, DelegateStatementSyntax).AttributeLists Case SyntaxKind.EnumBlock attributeSyntaxList = DirectCast(node, EnumBlockSyntax).EnumStatement.AttributeLists Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select attributeSyntaxBuilder.Add(attributeSyntaxList) Next Return attributeSyntaxBuilder.ToImmutableAndFree() End Function Public Function GetLexicalSortKey(compilation As VisualBasicCompilation) As LexicalSortKey ' Return first sort key from all declarations. Dim sortKey As LexicalSortKey = New LexicalSortKey(_declarations(0).NameLocation, compilation) For i = 1 To _declarations.Length - 1 sortKey = LexicalSortKey.First(sortKey, New LexicalSortKey(_declarations(i).NameLocation, compilation)) Next Return sortKey End Function Public ReadOnly Property NameLocations As ImmutableArray(Of Location) Get If Declarations.Length = 1 Then Return ImmutableArray.Create(Declarations(0).NameLocation) End If Dim builder = ArrayBuilder(Of Location).GetInstance() For Each decl In Declarations Dim loc = decl.NameLocation If loc IsNot Nothing Then builder.Add(loc) End If Next Return builder.ToImmutableAndFree() End Get End Property Private Shared ReadOnly s_identityFunc As Func(Of SingleTypeDeclaration, SingleTypeDeclaration) = Function(t) t Private Shared ReadOnly s_mergeFunc As Func(Of IEnumerable(Of SingleTypeDeclaration), MergedTypeDeclaration) = Function(g) New MergedTypeDeclaration(ImmutableArray.CreateRange(Of SingleTypeDeclaration)(g)) Private Function MakeChildren() As MergedTypeDeclaration() Dim allSingleTypeDecls As IEnumerable(Of SingleTypeDeclaration) If Declarations.Length = 1 Then allSingleTypeDecls = Declarations(0).Children.OfType(Of SingleTypeDeclaration)() Else allSingleTypeDecls = Declarations.SelectMany(Function(d) d.Children.OfType(Of SingleTypeDeclaration)()) End If Return MakeMergedTypes(allSingleTypeDecls).ToArray() End Function Friend Shared Function MakeMergedTypes(types As IEnumerable(Of SingleTypeDeclaration)) As IEnumerable(Of MergedTypeDeclaration) Return types. GroupBy(s_identityFunc, SingleTypeDeclaration.EqualityComparer). Select(s_mergeFunc) End Function Public Overloads ReadOnly Property Children As ImmutableArray(Of MergedTypeDeclaration) Get If Me._children Is Nothing Then Interlocked.CompareExchange(Me._children, MakeChildren(), Nothing) End If Return Me._children.AsImmutableOrNull() End Get End Property Protected Overrides Function GetDeclarationChildren() As ImmutableArray(Of Declaration) Return StaticCast(Of Declaration).From(Me.Children) End Function Public ReadOnly Property MemberNames As ICollection(Of String) Get If _memberNames Is Nothing Then Dim names = UnionCollection(Of String).Create(Me.Declarations, Function(d) d.MemberNames) Interlocked.CompareExchange(_memberNames, names, Nothing) End If Return _memberNames End Get End Property Public ReadOnly Property AnyMemberHasAttributes As Boolean Get For Each decl In Me.Declarations If decl.AnyMemberHasAttributes Then Return True End If Next Return False End Get End Property End Class End Namespace
1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Portable/Declarations/SingleTypeDeclaration.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Class SingleTypeDeclaration Inherits SingleNamespaceOrTypeDeclaration Private ReadOnly _children As ImmutableArray(Of SingleTypeDeclaration) ' CONSIDER: It may be possible to merge the flags and arity into a single ' 32-bit quantity if space is needed. Private ReadOnly _kind As DeclarationKind Private ReadOnly _flags As TypeDeclarationFlags Private ReadOnly _arity As UShort Private ReadOnly _modifiers As DeclarationModifiers Friend Enum TypeDeclarationFlags As Byte None = 0 HasAnyAttributes = 1 << 1 HasBaseDeclarations = 1 << 2 AnyMemberHasAttributes = 1 << 3 HasAnyNontypeMembers = 1 << 4 End Enum Public Sub New(kind As DeclarationKind, name As String, arity As Integer, modifiers As DeclarationModifiers, declFlags As TypeDeclarationFlags, syntaxReference As SyntaxReference, nameLocation As Location, memberNames As ImmutableHashSet(Of String), children As ImmutableArray(Of SingleTypeDeclaration)) MyBase.New(name, syntaxReference, nameLocation) Debug.Assert(kind <> DeclarationKind.Namespace) Me._kind = kind Me._arity = CUShort(arity) Me._flags = declFlags Me._modifiers = modifiers Me.MemberNames = memberNames Me._children = children End Sub Public Overrides ReadOnly Property Kind As DeclarationKind Get Return Me._kind End Get End Property Public ReadOnly Property Arity As Integer Get Return _arity End Get End Property Public ReadOnly Property HasAnyAttributes As Boolean Get Return (_flags And TypeDeclarationFlags.HasAnyAttributes) <> 0 End Get End Property Public ReadOnly Property HasBaseDeclarations As Boolean Get Return (_flags And TypeDeclarationFlags.HasBaseDeclarations) <> 0 End Get End Property Public ReadOnly Property HasAnyNontypeMembers As Boolean Get Return (_flags And TypeDeclarationFlags.HasAnyNontypeMembers) <> 0 End Get End Property Public ReadOnly Property AnyMemberHasAttributes As Boolean Get Return (_flags And TypeDeclarationFlags.AnyMemberHasAttributes) <> 0 End Get End Property Public Overloads ReadOnly Property Children As ImmutableArray(Of SingleTypeDeclaration) Get Return _children End Get End Property Public ReadOnly Property Modifiers As DeclarationModifiers Get Return Me._modifiers End Get End Property Public ReadOnly Property MemberNames As ImmutableHashSet(Of String) Protected Overrides Function GetNamespaceOrTypeDeclarationChildren() As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) Return StaticCast(Of SingleNamespaceOrTypeDeclaration).From(_children) End Function Private Function GetEmbeddedSymbolKind() As EmbeddedSymbolKind Return SyntaxReference.SyntaxTree.GetEmbeddedKind() End Function Private NotInheritable Class Comparer Implements IEqualityComparer(Of SingleTypeDeclaration) Private Shadows Function Equals(decl1 As SingleTypeDeclaration, decl2 As SingleTypeDeclaration) As Boolean Implements IEqualityComparer(Of SingleTypeDeclaration).Equals ' We should not merge types across embedded code / user code boundary. Return IdentifierComparison.Equals(decl1.Name, decl2.Name) _ AndAlso decl1.Kind = decl2.Kind _ AndAlso decl1.Kind <> DeclarationKind.Enum _ AndAlso decl1.Arity = decl2.Arity _ AndAlso decl1.GetEmbeddedSymbolKind() = decl2.GetEmbeddedSymbolKind() End Function Private Shadows Function GetHashCode(decl1 As SingleTypeDeclaration) As Integer Implements IEqualityComparer(Of SingleTypeDeclaration).GetHashCode Return Hash.Combine(IdentifierComparison.GetHashCode(decl1.Name), Hash.Combine(decl1.Arity.GetHashCode(), CType(decl1.Kind, Integer))) End Function End Class Public Shared ReadOnly EqualityComparer As IEqualityComparer(Of SingleTypeDeclaration) = New Comparer() End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols Friend Class SingleTypeDeclaration Inherits SingleNamespaceOrTypeDeclaration Private ReadOnly _children As ImmutableArray(Of SingleTypeDeclaration) ' CONSIDER: It may be possible to merge the flags and arity into a single ' 32-bit quantity if space is needed. Private ReadOnly _kind As DeclarationKind Private ReadOnly _flags As TypeDeclarationFlags Private ReadOnly _arity As UShort Private ReadOnly _modifiers As DeclarationModifiers Public ReadOnly QuickAttributes As QuickAttributes Friend Enum TypeDeclarationFlags As Byte None = 0 HasAnyAttributes = 1 << 1 HasBaseDeclarations = 1 << 2 AnyMemberHasAttributes = 1 << 3 HasAnyNontypeMembers = 1 << 4 End Enum Public Sub New(kind As DeclarationKind, name As String, arity As Integer, modifiers As DeclarationModifiers, declFlags As TypeDeclarationFlags, syntaxReference As SyntaxReference, nameLocation As Location, memberNames As ImmutableHashSet(Of String), children As ImmutableArray(Of SingleTypeDeclaration), quickAttributes As QuickAttributes) MyBase.New(name, syntaxReference, nameLocation) Debug.Assert(kind <> DeclarationKind.Namespace) Me._kind = kind Me._arity = CUShort(arity) Me._flags = declFlags Me._modifiers = modifiers Me.MemberNames = memberNames Me._children = children Me.QuickAttributes = quickAttributes End Sub Public Overrides ReadOnly Property Kind As DeclarationKind Get Return Me._kind End Get End Property Public ReadOnly Property Arity As Integer Get Return _arity End Get End Property Public ReadOnly Property HasAnyAttributes As Boolean Get Return (_flags And TypeDeclarationFlags.HasAnyAttributes) <> 0 End Get End Property Public ReadOnly Property HasBaseDeclarations As Boolean Get Return (_flags And TypeDeclarationFlags.HasBaseDeclarations) <> 0 End Get End Property Public ReadOnly Property HasAnyNontypeMembers As Boolean Get Return (_flags And TypeDeclarationFlags.HasAnyNontypeMembers) <> 0 End Get End Property Public ReadOnly Property AnyMemberHasAttributes As Boolean Get Return (_flags And TypeDeclarationFlags.AnyMemberHasAttributes) <> 0 End Get End Property Public Overloads ReadOnly Property Children As ImmutableArray(Of SingleTypeDeclaration) Get Return _children End Get End Property Public ReadOnly Property Modifiers As DeclarationModifiers Get Return Me._modifiers End Get End Property Public ReadOnly Property MemberNames As ImmutableHashSet(Of String) Protected Overrides Function GetNamespaceOrTypeDeclarationChildren() As ImmutableArray(Of SingleNamespaceOrTypeDeclaration) Return StaticCast(Of SingleNamespaceOrTypeDeclaration).From(_children) End Function Private Function GetEmbeddedSymbolKind() As EmbeddedSymbolKind Return SyntaxReference.SyntaxTree.GetEmbeddedKind() End Function Private NotInheritable Class Comparer Implements IEqualityComparer(Of SingleTypeDeclaration) Private Shadows Function Equals(decl1 As SingleTypeDeclaration, decl2 As SingleTypeDeclaration) As Boolean Implements IEqualityComparer(Of SingleTypeDeclaration).Equals ' We should not merge types across embedded code / user code boundary. Return IdentifierComparison.Equals(decl1.Name, decl2.Name) _ AndAlso decl1.Kind = decl2.Kind _ AndAlso decl1.Kind <> DeclarationKind.Enum _ AndAlso decl1.Arity = decl2.Arity _ AndAlso decl1.GetEmbeddedSymbolKind() = decl2.GetEmbeddedSymbolKind() End Function Private Shadows Function GetHashCode(decl1 As SingleTypeDeclaration) As Integer Implements IEqualityComparer(Of SingleTypeDeclaration).GetHashCode Return Hash.Combine(IdentifierComparison.GetHashCode(decl1.Name), Hash.Combine(decl1.Arity.GetHashCode(), CType(decl1.Kind, Integer))) End Function End Class Public Shared ReadOnly EqualityComparer As IEqualityComparer(Of SingleTypeDeclaration) = New Comparer() End Class End Namespace
1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Portable/Symbols/Source/QuickAttributeChecker.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' The QuickAttributeChecker applies a simple fast heuristic for determining probable ''' attributes without binding attribute types, just by looking at the final syntax of an ''' attribute usage. It is accessed via the QuickAttributeChecker property on Binder. ''' </summary> ''' <remarks> ''' It works by maintaining a dictionary of all possible simple names that might map to a particular ''' attribute. ''' </remarks> Friend Class QuickAttributeChecker ' Dictionary mapping a name to quick attribute(s) Private ReadOnly _nameToAttributeMap As Dictionary(Of String, QuickAttributes) ' If true, can no longer add new names. Private _sealed As Boolean Public Sub New() _nameToAttributeMap = New Dictionary(Of String, QuickAttributes)(IdentifierComparison.Comparer) End Sub Public Sub New(other As QuickAttributeChecker) _nameToAttributeMap = New Dictionary(Of String, QuickAttributes)(other._nameToAttributeMap, IdentifierComparison.Comparer) End Sub ''' <summary> ''' Add a mapping from name to some attributes. ''' </summary> Public Sub AddName(name As String, newAttributes As QuickAttributes) Debug.Assert(Not _sealed) Dim current = QuickAttributes.None _nameToAttributeMap.TryGetValue(name, current) _nameToAttributeMap(name) = newAttributes Or current ' We allow "Goo" to bind to "GooAttribute". If name.EndsWith("Attribute", StringComparison.OrdinalIgnoreCase) Then _nameToAttributeMap(name.Substring(0, name.Length - "Attribute".Length)) = newAttributes Or current End If End Sub ''' <summary> ''' Process an alias clause and any imported mappings from it. ''' E.g., If you have an alias Ex=Blah.Extension, add any mapping for Extension to those for Ex. ''' Note that although, in VB, an alias cannot reference another alias, this code doesn't not attempt ''' to distinguish between aliases and regular names, as that would add complexity to the data structure ''' and would be unlikely to matter. This entire class is probabilistic anyone and is only used for quick ''' checks. ''' </summary> Public Sub AddAlias(aliasSyntax As SimpleImportsClauseSyntax) Debug.Assert(Not _sealed) Debug.Assert(aliasSyntax.Alias IsNot Nothing) Dim finalName = GetFinalName(aliasSyntax.Name) If finalName IsNot Nothing Then Dim current As QuickAttributes = QuickAttributes.None If _nameToAttributeMap.TryGetValue(finalName, current) Then AddName(aliasSyntax.Alias.Identifier.ValueText, current) End If End If End Sub Public Sub Seal() _sealed = True End Sub ''' <summary> ''' Check attribute lists quickly to see what attributes might be referenced. ''' </summary> Public Function CheckAttributes(attributeLists As SyntaxList(Of AttributeListSyntax)) As QuickAttributes Debug.Assert(_sealed) Dim quickAttrs As QuickAttributes = QuickAttributes.None If attributeLists.Count > 0 Then For Each attrList In attributeLists For Each attr In attrList.Attributes quickAttrs = quickAttrs Or CheckAttribute(attr) Next Next End If Return quickAttrs End Function Public Function CheckAttribute(attr As AttributeSyntax) As QuickAttributes Dim attrTypeSyntax = attr.Name Dim finalName = GetFinalName(attrTypeSyntax) If finalName IsNot Nothing Then Dim quickAttributes As QuickAttributes If _nameToAttributeMap.TryGetValue(finalName, quickAttributes) Then Return quickAttributes End If End If Return QuickAttributes.None End Function ' Return the last name in a TypeSyntax, or Nothing if there isn't one. Private Function GetFinalName(typeSyntax As TypeSyntax) As String Dim node As VisualBasicSyntaxNode = typeSyntax Do Select Case node.Kind Case SyntaxKind.IdentifierName Return DirectCast(node, IdentifierNameSyntax).Identifier.ValueText Case SyntaxKind.QualifiedName node = DirectCast(node, QualifiedNameSyntax).Right Case Else Return Nothing End Select Loop End Function End Class ''' <summary> ''' Indicate which attributes might be present. Could be extended to other attributes ''' if desired. ''' </summary> <Flags> Friend Enum QuickAttributes As Byte None = 0 Extension = 1 << 0 Obsolete = 1 << 1 MyGroupCollection = 1 << 2 TypeIdentifier = 1 << 3 End Enum End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Generic Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' The QuickAttributeChecker applies a simple fast heuristic for determining probable ''' attributes without binding attribute types, just by looking at the final syntax of an ''' attribute usage. It is accessed via the QuickAttributeChecker property on Binder. ''' </summary> ''' <remarks> ''' It works by maintaining a dictionary of all possible simple names that might map to a particular ''' attribute. ''' </remarks> Friend Class QuickAttributeChecker ' Dictionary mapping a name to quick attribute(s) Private ReadOnly _nameToAttributeMap As Dictionary(Of String, QuickAttributes) ' If true, can no longer add new names. Private _sealed As Boolean Public Sub New() _nameToAttributeMap = New Dictionary(Of String, QuickAttributes)(IdentifierComparison.Comparer) End Sub Public Sub New(other As QuickAttributeChecker) _nameToAttributeMap = New Dictionary(Of String, QuickAttributes)(other._nameToAttributeMap, IdentifierComparison.Comparer) End Sub ''' <summary> ''' Add a mapping from name to some attributes. ''' </summary> Public Sub AddName(name As String, newAttributes As QuickAttributes) Debug.Assert(Not _sealed) Dim current = QuickAttributes.None _nameToAttributeMap.TryGetValue(name, current) _nameToAttributeMap(name) = newAttributes Or current ' We allow "Goo" to bind to "GooAttribute". If name.EndsWith("Attribute", StringComparison.OrdinalIgnoreCase) Then _nameToAttributeMap(name.Substring(0, name.Length - "Attribute".Length)) = newAttributes Or current End If End Sub ''' <summary> ''' Process an alias clause and any imported mappings from it. ''' E.g., If you have an alias Ex=Blah.Extension, add any mapping for Extension to those for Ex. ''' Note that although, in VB, an alias cannot reference another alias, this code doesn't not attempt ''' to distinguish between aliases and regular names, as that would add complexity to the data structure ''' and would be unlikely to matter. This entire class is probabilistic anyone and is only used for quick ''' checks. ''' </summary> Public Sub AddAlias(aliasSyntax As SimpleImportsClauseSyntax) Debug.Assert(Not _sealed) Debug.Assert(aliasSyntax.Alias IsNot Nothing) Dim finalName = GetFinalName(aliasSyntax.Name) If finalName IsNot Nothing Then Dim current As QuickAttributes = QuickAttributes.None If _nameToAttributeMap.TryGetValue(finalName, current) Then AddName(aliasSyntax.Alias.Identifier.ValueText, current) End If End If End Sub Public Sub Seal() _sealed = True End Sub ''' <summary> ''' Check attribute lists quickly to see what attributes might be referenced. ''' </summary> Public Function CheckAttributes(attributeLists As SyntaxList(Of AttributeListSyntax)) As QuickAttributes Debug.Assert(_sealed) Dim quickAttrs As QuickAttributes = QuickAttributes.None If attributeLists.Count > 0 Then For Each attrList In attributeLists For Each attr In attrList.Attributes quickAttrs = quickAttrs Or CheckAttribute(attr) Next Next End If Return quickAttrs End Function Public Function CheckAttribute(attr As AttributeSyntax) As QuickAttributes Dim attrTypeSyntax = attr.Name Dim finalName = GetFinalName(attrTypeSyntax) If finalName IsNot Nothing Then Dim quickAttributes As QuickAttributes If _nameToAttributeMap.TryGetValue(finalName, quickAttributes) Then Return quickAttributes End If End If Return QuickAttributes.None End Function ' Return the last name in a TypeSyntax, or Nothing if there isn't one. Public Shared Function GetFinalName(typeSyntax As TypeSyntax) As String Dim node As VisualBasicSyntaxNode = typeSyntax Do Select Case node.Kind Case SyntaxKind.IdentifierName Return DirectCast(node, IdentifierNameSyntax).Identifier.ValueText Case SyntaxKind.QualifiedName node = DirectCast(node, QualifiedNameSyntax).Right Case Else Return Nothing End Select Loop End Function End Class ''' <summary> ''' Indicate which attributes might be present. Could be extended to other attributes ''' if desired. ''' </summary> <Flags> Friend Enum QuickAttributes As Byte None = 0 Extension = 1 << 0 Obsolete = 1 << 1 MyGroupCollection = 1 << 2 TypeIdentifier = 1 << 3 Last = TypeIdentifier End Enum Friend Class QuickAttributeHelpers ''' <summary> ''' Returns the <see cref="QuickAttributes"/> that corresponds to the particular type ''' <paramref name="name"/> passed in. If <paramref name="inAttribute"/> Is <see langword="true"/> ''' then the name will be checked both as-Is as well as with the 'Attribute' suffix. ''' </summary> Public Shared Function GetQuickAttributes(name As String, inAttribute As Boolean) As QuickAttributes ' Update this code if we add New quick attributes. Debug.Assert(QuickAttributes.Last = QuickAttributes.TypeIdentifier) Dim result = QuickAttributes.None If Matches(name, inAttribute, AttributeDescription.CaseInsensitiveExtensionAttribute) Then result = result Or QuickAttributes.Extension ElseIf Matches(name, inAttribute, AttributeDescription.ObsoleteAttribute) Then result = result Or QuickAttributes.Obsolete ElseIf Matches(name, inAttribute, AttributeDescription.DeprecatedAttribute) Then result = result Or QuickAttributes.Obsolete ElseIf Matches(name, inAttribute, AttributeDescription.ExperimentalAttribute) Then result = result Or QuickAttributes.Obsolete ElseIf Matches(name, inAttribute, AttributeDescription.MyGroupCollectionAttribute) Then result = result Or QuickAttributes.TypeIdentifier ElseIf Matches(name, inAttribute, AttributeDescription.TypeIdentifierAttribute) Then result = result Or QuickAttributes.MyGroupCollection End If Return result End Function Private Shared Function Matches(name As String, inAttribute As Boolean, description As AttributeDescription) As Boolean Debug.Assert(description.Name.EndsWith(NameOf(System.Attribute))) If IdentifierComparison.Comparer.Equals(name, description.Name) Then Return True End If ' In an attribute context the name might be referenced as the full name (Like 'TypeForwardedToAttribute') ' Or the short name (Like 'TypeForwardedTo'). If inAttribute AndAlso (name.Length + NameOf(Attribute).Length) = description.Name.Length AndAlso description.Name.StartsWith(name, StringComparison.OrdinalIgnoreCase) Then Return True End If Return False End Function End Class End Namespace
1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Portable/Symbols/Source/SourceNamedTypeSymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a type or module declared in source. ''' Could be a class, structure, interface, delegate, enum, or module. ''' </summary> Partial Friend Class SourceNamedTypeSymbol Inherits SourceMemberContainerTypeSymbol Implements IAttributeTargetSymbol ' Type parameters (Nothing if not created yet) Private _lazyTypeParameters As ImmutableArray(Of TypeParameterSymbol) ' Attributes on type. Set once after construction. IsNull means not set. Protected m_lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) Private ReadOnly _corTypeId As SpecialType Private _lazyDocComment As String Private _lazyExpandedDocComment As String Private _lazyEnumUnderlyingType As NamedTypeSymbol ' Stores symbols for overriding WithEvents properties if we have such ' Overriding properties are created when a methods "Handles" is bound and can happen concurrently. ' We need this table to ensure that we create each override just once. Private _lazyWithEventsOverrides As ConcurrentDictionary(Of PropertySymbol, SynthesizedOverridingWithEventsProperty) Private _withEventsOverridesAreFrozen As Boolean ' method flags for the synthesized delegate methods Friend Const DelegateConstructorMethodFlags As SourceMemberFlags = SourceMemberFlags.MethodKindConstructor Friend Const DelegateCommonMethodFlags As SourceMemberFlags = SourceMemberFlags.Overridable Private _lazyLexicalSortKey As LexicalSortKey = LexicalSortKey.NotInitialized Private _lazyIsExtensibleInterface As ThreeState = ThreeState.Unknown Private _lazyIsExplicitDefinitionOfNoPiaLocalType As ThreeState = ThreeState.Unknown ''' <summary> ''' Information for ComClass specific analysis and metadata generation, created ''' once ComClassAttribute is encountered. ''' </summary> Private _comClassData As ComClassData ''' <summary> ''' Lazy CoClass type if the attribute is specified. Nothing if not. ''' </summary> Private _lazyCoClassType As TypeSymbol = ErrorTypeSymbol.UnknownResultType ''' <summary> ''' In case a cyclic dependency was detected during base type resolution ''' this field stores the diagnostic. ''' </summary> Protected m_baseCycleDiagnosticInfo As DiagnosticInfo = Nothing ' Create the type symbol and associated type parameter symbols. Most information ' is deferred until later. Friend Sub New(declaration As MergedTypeDeclaration, containingSymbol As NamespaceOrTypeSymbol, containingModule As SourceModuleSymbol) MyBase.New(declaration, containingSymbol, containingModule) ' check if this is one of the COR library types If containingSymbol.Kind = SymbolKind.Namespace AndAlso containingSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes AndAlso Me.DeclaredAccessibility = Accessibility.Public Then Dim emittedName As String = If(Me.GetEmittedNamespaceName(), Me.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)) Debug.Assert((Arity <> 0) = MangleName) emittedName = MetadataHelpers.BuildQualifiedName(emittedName, MetadataName) _corTypeId = SpecialTypes.GetTypeFromMetadataName(emittedName) Else _corTypeId = SpecialType.None End If If containingSymbol.Kind = SymbolKind.NamedType Then ' Nested types are never unified. _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.False End If End Sub Public Overrides ReadOnly Property SpecialType As SpecialType Get Return _corTypeId End Get End Property #Region "Completion" Protected Overrides Sub GenerateAllDeclarationErrorsImpl(cancellationToken As CancellationToken) #If DEBUG Then EnsureAllHandlesAreBound() #End If MyBase.GenerateAllDeclarationErrorsImpl(cancellationToken) _withEventsOverridesAreFrozen = True cancellationToken.ThrowIfCancellationRequested() PerformComClassAnalysis() cancellationToken.ThrowIfCancellationRequested() CheckBaseConstraints() cancellationToken.ThrowIfCancellationRequested() CheckInterfacesConstraints() End Sub #End Region #Region "Syntax" Friend Function GetTypeIdentifierToken(node As VisualBasicSyntaxNode) As SyntaxToken Select Case node.Kind Case SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock Return DirectCast(node, TypeBlockSyntax).BlockStatement.Identifier Case SyntaxKind.EnumBlock Return DirectCast(node, EnumBlockSyntax).EnumStatement.Identifier Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(node, DelegateStatementSyntax).Identifier Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String If expandIncludes Then Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyExpandedDocComment, cancellationToken) Else Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyDocComment, cancellationToken) End If End Function ' Create a LocationSpecificBinder for the type. This is a binder that wraps the ' default binder for the type in a binder that will avoid checking constraints, ' for cases where constraint checking may result in a recursive binding attempt. Private Function CreateLocationSpecificBinderForType(tree As SyntaxTree, location As BindingLocation) As Binder Debug.Assert(location <> BindingLocation.None) Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, tree, Me) Return New LocationSpecificBinder(location, binder) End Function #End Region #Region "Members" Protected Overrides Sub AddDeclaredNonTypeMembers(membersBuilder As SourceMemberContainerTypeSymbol.MembersAndInitializersBuilder, diagnostics As BindingDiagnosticBag) Dim accessModifiers As DeclarationModifiers = Nothing Dim foundModifiers As DeclarationModifiers Dim foundPartial As Boolean = False Dim nodeNameIsAlreadyDefined As Boolean = False Dim firstNode As VisualBasicSyntaxNode = Nothing Dim countMissingPartial = 0 For Each syntaxRef In SyntaxReferences Dim node = syntaxRef.GetVisualBasicSyntax() ' Set up a binder for this part of the type. Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, syntaxRef.SyntaxTree, Me) ' Script and implicit classes are syntactically represented by CompilationUnitSyntax or NamespaceBlockSyntax nodes. Dim staticInitializers As ArrayBuilder(Of FieldOrPropertyInitializer) = Nothing Dim instanceInitializers As ArrayBuilder(Of FieldOrPropertyInitializer) = Nothing foundModifiers = AddMembersInPart(binder, node, diagnostics, accessModifiers, membersBuilder, staticInitializers, instanceInitializers, nodeNameIsAlreadyDefined) If accessModifiers = Nothing Then accessModifiers = foundModifiers And DeclarationModifiers.AllAccessibilityModifiers End If If (foundModifiers And DeclarationModifiers.Partial) <> 0 Then If Not foundPartial Then firstNode = node foundPartial = True End If Else countMissingPartial += 1 If firstNode Is Nothing Then firstNode = node End If End If ' add the collected initializers for this (partial) type to the collections ' and free the array builders AddInitializers(membersBuilder.StaticInitializers, staticInitializers) AddInitializers(membersBuilder.InstanceInitializers, instanceInitializers) Next If Not nodeNameIsAlreadyDefined AndAlso countMissingPartial >= 2 Then ' Only check partials if no duplicate symbols were found and at least two class declarations are missing the partial keyword. For Each syntaxRef In SyntaxReferences ' Report a warning or error for all classes missing the partial modifier CheckDeclarationPart(syntaxRef.SyntaxTree, syntaxRef.GetVisualBasicSyntax(), firstNode, foundPartial, diagnostics) Next End If End Sub ' Declare all the non-type members in a single part of this type, and add them to the member list. Private Function AddMembersInPart(binder As Binder, node As VisualBasicSyntaxNode, diagBag As BindingDiagnosticBag, accessModifiers As DeclarationModifiers, members As MembersAndInitializersBuilder, ByRef staticInitializers As ArrayBuilder(Of FieldOrPropertyInitializer), ByRef instanceInitializers As ArrayBuilder(Of FieldOrPropertyInitializer), ByRef nodeNameIsAlreadyDefined As Boolean) As DeclarationModifiers Debug.Assert(diagBag.AccumulatesDiagnostics) ' Check that the node's fully qualified name is not too long and that the type name is unique. CheckDeclarationNameAndTypeParameters(node, binder, diagBag, nodeNameIsAlreadyDefined) Dim foundModifiers = CheckDeclarationModifiers(node, binder, diagBag.DiagnosticBag, accessModifiers) If TypeKind = TypeKind.Delegate Then ' add implicit delegate members (invoke, .ctor, begininvoke and endinvoke) If members.Members.Count = 0 Then Dim ctor As MethodSymbol = Nothing Dim beginInvoke As MethodSymbol = Nothing Dim endInvoke As MethodSymbol = Nothing Dim invoke As MethodSymbol = Nothing Dim parameters = DirectCast(node, DelegateStatementSyntax).ParameterList SourceDelegateMethodSymbol.MakeDelegateMembers(Me, node, parameters, binder, ctor, beginInvoke, endInvoke, invoke, diagBag) AddSymbolToMembers(ctor, members.Members) ' If this is a winmd compilation begin/endInvoke will be Nothing ' and we shouldn't add them to the symbol If beginInvoke IsNot Nothing Then AddSymbolToMembers(beginInvoke, members.Members) End If If endInvoke IsNot Nothing Then AddSymbolToMembers(endInvoke, members.Members) End If ' Invoke must always be the last member AddSymbolToMembers(invoke, members.Members) Else Debug.Assert(members.Members.Count = 4) End If ElseIf TypeKind = TypeKind.Enum Then Dim enumBlock = DirectCast(node, EnumBlockSyntax) AddEnumMembers(enumBlock, binder, diagBag, members) Else Dim typeBlock = DirectCast(node, TypeBlockSyntax) For Each memberSyntax In typeBlock.Members AddMember(memberSyntax, binder, diagBag, members, staticInitializers, instanceInitializers, reportAsInvalid:=False) Next End If Return foundModifiers End Function Private Function CheckDeclarationModifiers(node As VisualBasicSyntaxNode, binder As Binder, diagBag As DiagnosticBag, accessModifiers As DeclarationModifiers) As DeclarationModifiers Dim modifiers As SyntaxTokenList = Nothing Dim id As SyntaxToken = Nothing Dim foundModifiers = DecodeDeclarationModifiers(node, binder, diagBag, modifiers, id) If accessModifiers <> Nothing Then Dim newModifiers = foundModifiers And DeclarationModifiers.AllAccessibilityModifiers And Not accessModifiers ' Specified access '|1' for '|2' does not match the access '|3' specified on one of its other partial types. If newModifiers <> 0 Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_PartialTypeAccessMismatch3, newModifiers.ToAccessibility().ToDisplay(), id.ToString(), accessModifiers.ToAccessibility().ToDisplay()) End If End If If Me.IsNotInheritable Then ' 'MustInherit' cannot be specified for partial type '|1' because it cannot be combined with 'NotInheritable' ' specified for one of its other partial types. If (foundModifiers And DeclarationModifiers.MustInherit) <> 0 Then ' Generate error #30926 only if this (partial) declaration does not have both MustInherit and ' NotInheritable (in which case #31408 error must have been generated which should be enough in this ' case). If (foundModifiers And DeclarationModifiers.NotInheritable) = 0 Then ' Note: in case one partial declaration has both MustInherit & NotInheritable and other partial ' declarations have MustInherit, #31408 will be generated for the first one and #30926 for all ' others with MustInherit Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_PartialTypeBadMustInherit1, id.ToString()) End If End If End If Dim containingType = TryCast(Me.ContainingType, SourceNamedTypeSymbol) ' IsNested means this is in a Class or Module or Structure Dim isNested = containingType IsNot Nothing AndAlso Not containingType.IsNamespace If isNested Then Select Case containingType.DeclarationKind Case VisualBasic.Symbols.DeclarationKind.Module If (foundModifiers And DeclarationModifiers.InvalidInModule) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_ModuleCantUseTypeSpecifier1, diagBag, InvalidModifiersInModule) foundModifiers = (foundModifiers And (Not DeclarationModifiers.InvalidInModule)) End If Case VisualBasic.Symbols.DeclarationKind.Interface If (foundModifiers And DeclarationModifiers.InvalidInInterface) <> 0 Then Dim err As ERRID = ERRID.ERR_None Select Case Me.DeclarationKind Case VisualBasic.Symbols.DeclarationKind.Class err = ERRID.ERR_BadInterfaceClassSpecifier1 Case VisualBasic.Symbols.DeclarationKind.Delegate err = ERRID.ERR_BadInterfaceDelegateSpecifier1 Case VisualBasic.Symbols.DeclarationKind.Structure err = ERRID.ERR_BadInterfaceStructSpecifier1 Case VisualBasic.Symbols.DeclarationKind.Enum err = ERRID.ERR_BadInterfaceEnumSpecifier1 Case VisualBasic.Symbols.DeclarationKind.Interface ' For whatever reason, Dev10 does not report an error on [Friend] or [Public] modifier on an interface inside an interface. ' Need to handle this specially Dim invalidModifiers = DeclarationModifiers.InvalidInInterface And (Not (DeclarationModifiers.Friend Or DeclarationModifiers.Public)) If (foundModifiers And invalidModifiers) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_BadInterfaceInterfaceSpecifier1, diagBag, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SharedKeyword) foundModifiers = (foundModifiers And (Not invalidModifiers)) End If End Select If err <> ERRID.ERR_None Then binder.ReportModifierError(modifiers, err, diagBag, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.FriendKeyword, SyntaxKind.PublicKeyword, SyntaxKind.SharedKeyword) foundModifiers = (foundModifiers And (Not DeclarationModifiers.InvalidInInterface)) End If End If End Select Else If (foundModifiers And DeclarationModifiers.Private) <> 0 Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_PrivateTypeOutsideType) End If If (foundModifiers And DeclarationModifiers.Shadows) <> 0 Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_ShadowingTypeOutsideClass1, id.ToString()) foundModifiers = (foundModifiers And (Not DeclarationModifiers.Shadows)) End If End If ' Only nested type (not nested in a struct, nested in a class, etc. ) can be Protected. If (foundModifiers And DeclarationModifiers.Protected) <> 0 AndAlso (Not isNested OrElse containingType.DeclarationKind <> VisualBasic.Symbols.DeclarationKind.Class) Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_ProtectedTypeOutsideClass) foundModifiers = (foundModifiers And (Not DeclarationModifiers.Protected)) End If Return foundModifiers End Function Private Function DecodeDeclarationModifiers(node As VisualBasicSyntaxNode, binder As Binder, diagBag As DiagnosticBag, ByRef modifiers As SyntaxTokenList, ByRef id As SyntaxToken) As DeclarationModifiers Dim allowableModifiers = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Shadows Dim err = ERRID.ERR_None Dim typeBlock As TypeBlockSyntax Select Case node.Kind Case SyntaxKind.ModuleBlock err = ERRID.ERR_BadModuleFlags1 allowableModifiers = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Partial typeBlock = DirectCast(node, TypeBlockSyntax) modifiers = typeBlock.BlockStatement.Modifiers id = typeBlock.BlockStatement.Identifier Case SyntaxKind.ClassBlock err = ERRID.ERR_BadClassFlags1 allowableModifiers = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Shadows Or SourceMemberFlags.MustInherit Or SourceMemberFlags.NotInheritable Or SourceMemberFlags.Partial typeBlock = DirectCast(node, TypeBlockSyntax) modifiers = typeBlock.BlockStatement.Modifiers id = typeBlock.BlockStatement.Identifier Case SyntaxKind.StructureBlock err = ERRID.ERR_BadRecordFlags1 allowableModifiers = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Shadows Or SourceMemberFlags.Partial typeBlock = DirectCast(node, TypeBlockSyntax) modifiers = typeBlock.BlockStatement.Modifiers id = typeBlock.BlockStatement.Identifier Case SyntaxKind.InterfaceBlock err = ERRID.ERR_BadInterfaceFlags1 allowableModifiers = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Shadows Or SourceMemberFlags.Partial typeBlock = DirectCast(node, TypeBlockSyntax) modifiers = typeBlock.BlockStatement.Modifiers id = typeBlock.BlockStatement.Identifier Case SyntaxKind.EnumBlock err = ERRID.ERR_BadEnumFlags1 Dim enumBlock As EnumBlockSyntax = DirectCast(node, EnumBlockSyntax) modifiers = enumBlock.EnumStatement.Modifiers id = enumBlock.EnumStatement.Identifier Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement err = ERRID.ERR_BadDelegateFlags1 modifiers = DirectCast(node, DelegateStatementSyntax).Modifiers id = DirectCast(node, DelegateStatementSyntax).Identifier Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select If modifiers.Count <> 0 Then Dim foundFlags As SourceMemberFlags = binder.DecodeModifiers(modifiers, allowableModifiers, err, Nothing, diagBag).FoundFlags Return CType((foundFlags And SourceMemberFlags.DeclarationModifierFlagMask) >> SourceMemberFlags.DeclarationModifierFlagShift, DeclarationModifiers) End If Return Nothing End Function Private Sub CheckDeclarationNameAndTypeParameters(node As VisualBasicSyntaxNode, binder As Binder, diagBag As BindingDiagnosticBag, ByRef nodeNameIsAlreadyDeclared As Boolean) ' Check that the node's fully qualified name is not too long. Only check declarations that create types. Dim id As SyntaxToken = GetTypeIdentifierToken(node) Binder.DisallowTypeCharacter(id, diagBag) Dim thisTypeIsEmbedded As Boolean = Me.IsEmbedded ' Check name for duplicate type declarations in this container Dim container = TryCast(Me.ContainingSymbol, NamespaceOrTypeSymbol) If container IsNot Nothing Then ' Get all type or namespace symbols with this name. Dim symbols As ImmutableArray(Of Symbol) If container.IsNamespace Then symbols = container.GetMembers(Me.Name) Else symbols = StaticCast(Of Symbol).From(container.GetTypeMembers(Me.Name)) End If Dim arity As Integer = Me.Arity For Each s In symbols If s IsNot Me Then Dim _3rdArg As Object Select Case s.Kind Case SymbolKind.Namespace If arity > 0 Then Continue For End If _3rdArg = DirectCast(s, NamespaceSymbol).GetKindText() Case SymbolKind.NamedType Dim contender = DirectCast(s, NamedTypeSymbol) If contender.Arity <> arity Then Continue For End If _3rdArg = contender.GetKindText() Case Else Continue For End Select If s.IsEmbedded Then ' We expect 'this' type not to be an embedded type in this ' case because otherwise it should be design time bug. Debug.Assert(Not thisTypeIsEmbedded) ' This non-embedded type conflicts with an embedded type or namespace Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_TypeClashesWithVbCoreType4, Me.GetKindText(), id.ToString, _3rdArg, s.Name) ElseIf thisTypeIsEmbedded Then ' Embedded type conflicts with non-embedded type or namespace. ' We should ignore non-embedded types in this case, as a proper ' diagnostic will be reported when the non-embedded type is processed. If s.Kind = SymbolKind.Namespace Then ' But we should report errors on the first namespace locations Dim errorReported As Boolean = False For Each location In s.Locations If location.IsInSource AndAlso Not DirectCast(location.SourceTree, VisualBasicSyntaxTree).IsEmbeddedSyntaxTree Then Binder.ReportDiagnostic(diagBag, location, ERRID.ERR_TypeClashesWithVbCoreType4, _3rdArg, s.Name, Me.GetKindText(), id.ToString) errorReported = True Exit For End If Next If errorReported Then Exit For End If End If Continue For ' continue analysis of the type if no errors were reported Else ' Neither of types is embedded. If (Me.ContainingType Is Nothing OrElse container.Locations.Length = 1 OrElse Not (TypeOf container Is SourceMemberContainerTypeSymbol) OrElse CType(container, SourceMemberContainerTypeSymbol).IsPartial) Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_TypeConflict6, Me.GetKindText(), id.ToString, _3rdArg, s.Name, container.GetKindText(), Me.ContainingSymbol.ToErrorMessageArgument(ERRID.ERR_TypeConflict6)) End If End If nodeNameIsAlreadyDeclared = True Exit For End If Next If Not nodeNameIsAlreadyDeclared AndAlso container.IsNamespace AndAlso Me.ContainingAssembly.Modules.Length > 1 Then ' Check for collision with types from added modules Dim containingNamespace = DirectCast(container, NamespaceSymbol) Dim mergedAssemblyNamespace = TryCast(Me.ContainingAssembly.GetAssemblyNamespace(containingNamespace), MergedNamespaceSymbol) If mergedAssemblyNamespace IsNot Nothing Then Dim targetQualifiedNamespaceName As String = If(Me.GetEmittedNamespaceName(), containingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)) Dim collision As NamedTypeSymbol = Nothing For Each constituent As NamespaceSymbol In mergedAssemblyNamespace.ConstituentNamespaces If constituent Is container Then Continue For End If If collision IsNot Nothing AndAlso collision.ContainingModule.Ordinal < constituent.ContainingModule.Ordinal Then Continue For End If Dim contenders As ImmutableArray(Of NamedTypeSymbol) = constituent.GetTypeMembers(Me.Name, arity) If contenders.Length = 0 Then Continue For End If Dim constituentQualifiedName As String = constituent.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) For Each namedType In contenders If namedType.DeclaredAccessibility = Accessibility.Public AndAlso namedType.MangleName = Me.MangleName Then ' Because namespaces are merged case-insensitively, ' we need to make sure that we have a match for ' full emitted name of the type. If String.Equals(Me.Name, namedType.Name, StringComparison.Ordinal) AndAlso String.Equals(targetQualifiedNamespaceName, If(namedType.GetEmittedNamespaceName(), constituentQualifiedName), StringComparison.Ordinal) Then collision = namedType Exit For End If End If Next Next If collision IsNot Nothing Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_CollisionWithPublicTypeInModule, Me, collision.ContainingModule) End If End If End If End If ' Check name against type parameters of immediate container Dim containingSourceType = TryCast(container, SourceNamedTypeSymbol) If containingSourceType IsNot Nothing AndAlso containingSourceType.TypeParameters.MatchesAnyName(Me.Name) Then ' "'|1' has the same name as a type parameter." Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_ShadowingGenericParamWithMember1, Me.Name) End If ' Check the source symbol type parameters for duplicates and shadowing CheckForDuplicateTypeParameters(TypeParameters, diagBag) End Sub Private Sub CheckDeclarationPart(tree As SyntaxTree, node As VisualBasicSyntaxNode, firstNode As VisualBasicSyntaxNode, foundPartial As Boolean, diagBag As BindingDiagnosticBag) ' No error or warning on the first declaration If node Is firstNode Then Return End If ' Set up a binder for this part of the type. Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, tree, Me) ' all type declarations are treated as possible partial types. Because these type have different base classes ' we need to get the modifiers in different ways. ' class, interface, struct and module all are all derived from TypeBlockSyntax. ' delegate is derived from MethodBase Dim modifiers As SyntaxTokenList = Nothing Select Case node.Kind Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement modifiers = DirectCast(node, DelegateStatementSyntax).Modifiers Case SyntaxKind.EnumBlock modifiers = DirectCast(node, EnumBlockSyntax).EnumStatement.Modifiers Case SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock modifiers = DirectCast(node, TypeBlockSyntax).BlockStatement.Modifiers Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select Dim id As SyntaxToken = Nothing ' because this method was called before, we will pass a new (unused) instance of ' diagnostics to avoid duplicate error messages for the same nodes Dim unusedDiagnostics = DiagnosticBag.GetInstance() Dim foundModifiers = DecodeDeclarationModifiers(node, binder, unusedDiagnostics, modifiers, id) unusedDiagnostics.Free() If (foundModifiers And DeclarationModifiers.Partial) = 0 Then Dim errorCode = If(foundPartial, ERRID.WRN_TypeConflictButMerged6, ERRID.ERR_TypeConflict6) ' Ensure multiple class declarations all have partial. Report a warning if more than 2 declarations are missing partial. ' VB allows one class declaration with partial and one declaration without partial because designer generated code ' may not have specified partial. This allows user-code to force it. However, VB does not allow more than one declaration ' to not have partial as this would (erroneously) make what would have been a error (duplicate declarations) compile. Dim _6thArg As Object = Me.ContainingSymbol.ToErrorMessageArgument(errorCode) Dim identifier As String = GetTypeIdentifierToken(firstNode).ToString Dim nodeKindText = Me.GetKindText() Binder.ReportDiagnostic(diagBag, id, errorCode, nodeKindText, id.ToString, nodeKindText, identifier, Me.ContainingSymbol.GetKindText(), _6thArg) End If End Sub Private Sub AddEnumMembers(syntax As EnumBlockSyntax, bodyBinder As Binder, diagnostics As BindingDiagnosticBag, members As MembersAndInitializersBuilder) Dim valField = New SynthesizedFieldSymbol( Me, Me, Me.EnumUnderlyingType, WellKnownMemberNames.EnumBackingFieldName, accessibility:=Accessibility.Public, isSpecialNameAndRuntimeSpecial:=True) AddMember(valField, bodyBinder, members, omitDiagnostics:=False) ' The previous enum constant used to calculate subsequent ' implicit enum constants. (This is the most recent explicit ' enum constant or the first implicit constant if no explicit values.) Dim otherSymbol As SourceEnumConstantSymbol = Nothing ' Offset from "otherSymbol". Dim otherSymbolOffset As Integer = 0 If syntax.Members.Count = 0 Then Binder.ReportDiagnostic(diagnostics, syntax.EnumStatement.Identifier, ERRID.ERR_BadEmptyEnum1, syntax.EnumStatement.Identifier.ValueText) Return End If For Each member In syntax.Members If member.Kind <> SyntaxKind.EnumMemberDeclaration Then ' skip invalid syntax Continue For End If Dim declaration = DirectCast(member, EnumMemberDeclarationSyntax) Dim symbol As SourceEnumConstantSymbol Dim valueOpt = declaration.Initializer If valueOpt IsNot Nothing Then symbol = SourceEnumConstantSymbol.CreateExplicitValuedConstant(Me, bodyBinder, declaration, diagnostics) Else symbol = SourceEnumConstantSymbol.CreateImplicitValuedConstant(Me, bodyBinder, declaration, otherSymbol, otherSymbolOffset, diagnostics) End If If (valueOpt IsNot Nothing) OrElse (otherSymbol Is Nothing) Then otherSymbol = symbol otherSymbolOffset = 1 Else otherSymbolOffset = otherSymbolOffset + 1 End If AddMember(symbol, bodyBinder, members, omitDiagnostics:=False) Next End Sub #End Region #Region "Type Parameters (phase 3)" Private Structure TypeParameterInfo Public Sub New( variance As VarianceKind, constraints As ImmutableArray(Of TypeParameterConstraint)) Me.Variance = variance Me.Constraints = constraints End Sub Public ReadOnly Variance As VarianceKind Public ReadOnly Constraints As ImmutableArray(Of TypeParameterConstraint) Public ReadOnly Property Initialized As Boolean Get Return Not Me.Constraints.IsDefault End Get End Property End Structure Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get If _lazyTypeParameters.IsDefault Then ImmutableInterlocked.InterlockedInitialize(_lazyTypeParameters, MakeTypeParameters()) End If Return _lazyTypeParameters End Get End Property ''' <summary> ''' Bind the constraint declarations for the given type parameter. ''' </summary> ''' <remarks> ''' The caller is expected to handle constraint checking and any caching of results. ''' </remarks> Friend Sub BindTypeParameterConstraints( typeParameter As SourceTypeParameterOnTypeSymbol, <Out()> ByRef variance As VarianceKind, <Out()> ByRef constraints As ImmutableArray(Of TypeParameterConstraint), diagnostics As BindingDiagnosticBag) Dim unused = GetTypeMembersDictionary() ' forced nested types to be declared. Dim info As TypeParameterInfo = Nothing ' Go through all declarations, determining the type parameter information ' from each, and updating the type parameter and reporting errors. For Each syntaxRef In SyntaxReferences Dim tree = syntaxRef.SyntaxTree Dim syntaxNode = syntaxRef.GetVisualBasicSyntax() Dim allowVariance = False Select Case syntaxNode.Kind Case SyntaxKind.InterfaceBlock, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement allowVariance = True End Select Dim typeParameterList = GetTypeParameterListSyntax(syntaxNode) CreateTypeParameterInfoInPart(tree, typeParameter, typeParameterList, allowVariance, info, diagnostics) Next Debug.Assert(info.Initialized) variance = info.Variance constraints = info.Constraints End Sub ' Create all the type parameter information from the given declaration. Private Sub CreateTypeParameterInfoInPart(tree As SyntaxTree, typeParameter As SourceTypeParameterOnTypeSymbol, typeParamListSyntax As TypeParameterListSyntax, allowVarianceSpecifier As Boolean, ByRef info As TypeParameterInfo, diagBag As BindingDiagnosticBag) Debug.Assert(typeParamListSyntax IsNot Nothing) Debug.Assert(typeParamListSyntax.Parameters.Count = Me.Arity) ' If this is false, something is really wrong with the declaration tree. ' Set up a binder for this part of the type. Dim binder As Binder = CreateLocationSpecificBinderForType(tree, BindingLocation.GenericConstraintsClause) Dim typeParamSyntax = typeParamListSyntax.Parameters(typeParameter.Ordinal) ' Handle type parameter identifier. Dim identSymbol = typeParamSyntax.Identifier Binder.DisallowTypeCharacter(identSymbol, diagBag, ERRID.ERR_TypeCharOnGenericParam) Dim name As String = identSymbol.ValueText ' Handle type parameter variance. Dim varianceKeyword = typeParamSyntax.VarianceKeyword Dim variance As VarianceKind = VarianceKind.None If varianceKeyword.Kind <> SyntaxKind.None Then If allowVarianceSpecifier Then variance = Binder.DecodeVariance(varianceKeyword) Else Binder.ReportDiagnostic(diagBag, varianceKeyword, ERRID.ERR_VarianceDisallowedHere) End If End If ' Handle constraints. Dim constraints = binder.BindTypeParameterConstraintClause(Me, typeParamSyntax.TypeParameterConstraintClause, diagBag) If info.Initialized Then If Not IdentifierComparison.Equals(typeParameter.Name, name) Then ' "Type parameter name '{0}' does not match the name '{1}' of the corresponding type parameter defined on one of the other partial types of '{2}'." Binder.ReportDiagnostic(diagBag, identSymbol, ERRID.ERR_PartialTypeTypeParamNameMismatch3, name, typeParameter.Name, Me.Name) End If If Not HaveSameConstraints(info.Constraints, constraints) Then ' "Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of '{0}'." Binder.ReportDiagnostic(diagBag, identSymbol, ERRID.ERR_PartialTypeConstraintMismatch1, Me.Name) End If Else info = New TypeParameterInfo(variance, constraints) End If End Sub Private Shared Function HaveSameConstraints(constraints1 As ImmutableArray(Of TypeParameterConstraint), constraints2 As ImmutableArray(Of TypeParameterConstraint)) As Boolean Dim n1 = constraints1.Length Dim n2 = constraints2.Length If n1 <> n2 Then Return False End If If (n1 = 0) AndAlso (n2 = 0) Then Return True End If If GetConstraintKind(constraints1) <> GetConstraintKind(constraints2) Then Return False End If ' Construct a HashSet<T> for one of the sets ' to allow O(n) comparison of the two sets. Dim constraintTypes1 = New HashSet(Of TypeSymbol) For Each constraint In constraints1 Dim constraintType = constraint.TypeConstraint If constraintType IsNot Nothing Then constraintTypes1.Add(constraintType) End If Next For Each constraint In constraints2 Dim constraintType = constraint.TypeConstraint If (constraintType IsNot Nothing) AndAlso Not constraintTypes1.Contains(constraintType) Then Return False End If Next Return True End Function Private Shared Function GetConstraintKind(constraints As ImmutableArray(Of TypeParameterConstraint)) As TypeParameterConstraintKind Dim kind = TypeParameterConstraintKind.None For Each constraint In constraints kind = kind Or constraint.Kind Next Return kind End Function Private Function MakeTypeParameters() As ImmutableArray(Of TypeParameterSymbol) Dim n = TypeDeclaration.Arity If n = 0 Then Return ImmutableArray(Of TypeParameterSymbol).Empty End If Dim typeParameters(0 To n - 1) As TypeParameterSymbol For i = 0 To n - 1 Dim syntaxRefBuilder = ArrayBuilder(Of SyntaxReference).GetInstance() Dim name As String = Nothing For Each syntaxRef In SyntaxReferences Dim tree = syntaxRef.SyntaxTree Dim syntaxNode = syntaxRef.GetVisualBasicSyntax() Dim typeParamListSyntax = GetTypeParameterListSyntax(syntaxNode).Parameters Debug.Assert(typeParamListSyntax.Count = n) Dim typeParamSyntax = typeParamListSyntax(i) If name Is Nothing Then name = typeParamSyntax.Identifier.ValueText End If syntaxRefBuilder.Add(tree.GetReference(typeParamSyntax)) Next Debug.Assert(name IsNot Nothing) Debug.Assert(syntaxRefBuilder.Count > 0) typeParameters(i) = New SourceTypeParameterOnTypeSymbol(Me, i, name, syntaxRefBuilder.ToImmutableAndFree()) Next Return typeParameters.AsImmutableOrNull() End Function Private Shared Function GetTypeParameterListSyntax(syntax As VisualBasicSyntaxNode) As TypeParameterListSyntax Select Case syntax.Kind Case SyntaxKind.StructureBlock, SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock Return DirectCast(syntax, TypeBlockSyntax).BlockStatement.TypeParameterList Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(syntax, DelegateStatementSyntax).TypeParameterList Case Else Return Nothing End Select End Function Friend Sub CheckForDuplicateTypeParameters(typeParameters As ImmutableArray(Of TypeParameterSymbol), diagBag As BindingDiagnosticBag) If Not typeParameters.IsDefault Then Dim typeParameterSet As New HashSet(Of String)(IdentifierComparison.Comparer) ' Check for duplicate type parameters For i = 0 To typeParameters.Length - 1 Dim s = typeParameters(i) If Not typeParameterSet.Contains(s.Name) Then typeParameterSet.Add(s.Name) If ShadowsTypeParameter(s) Then Binder.ReportDiagnostic(diagBag, s.Locations(0), ERRID.WRN_ShadowingGenericParamWithParam1, s.Name) End If Else Binder.ReportDiagnostic(diagBag, s.Locations(0), ERRID.ERR_DuplicateTypeParamName1, s.Name) End If Next End If End Sub Private Function ShadowsTypeParameter(typeParameter As TypeParameterSymbol) As Boolean Dim name As String = typeParameter.Name Dim containingType As SourceNamedTypeSymbol If typeParameter.TypeParameterKind = TypeParameterKind.Method Then containingType = Me Else containingType = TryCast(Me.ContainingType, SourceNamedTypeSymbol) End If While containingType IsNot Nothing If containingType.TypeParameters.MatchesAnyName(name) Then Return True End If containingType = TryCast(containingType.ContainingType, SourceNamedTypeSymbol) End While Return False End Function #End Region #Region "Base Type and Interfaces (phase 4)" Private Sub MakeDeclaredBaseInPart(tree As SyntaxTree, syntaxNode As VisualBasicSyntaxNode, ByRef baseType As NamedTypeSymbol, basesBeingResolved As BasesBeingResolved, diagBag As BindingDiagnosticBag) ' Set up a binder for this part of the type. Dim binder As Binder = CreateLocationSpecificBinderForType(tree, BindingLocation.BaseTypes) Select Case syntaxNode.Kind Case SyntaxKind.ClassBlock Dim inheritsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Inherits ' classes may have a base class Dim thisBase As NamedTypeSymbol = ValidateClassBase(inheritsSyntax, baseType, basesBeingResolved, binder, diagBag) If baseType Is Nothing Then baseType = thisBase End If Case SyntaxKind.StructureBlock Dim inheritsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Inherits CheckNoBase(inheritsSyntax, ERRID.ERR_StructCantInherit, diagBag) Case SyntaxKind.ModuleBlock Dim inheritsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Inherits CheckNoBase(inheritsSyntax, ERRID.ERR_ModuleCantInherit, diagBag) End Select End Sub Private Sub MakeDeclaredInterfacesInPart(tree As SyntaxTree, syntaxNode As VisualBasicSyntaxNode, interfaces As SetWithInsertionOrder(Of NamedTypeSymbol), basesBeingResolved As BasesBeingResolved, diagBag As BindingDiagnosticBag) ' Set up a binder for this part of the type. Dim binder As Binder = CreateLocationSpecificBinderForType(tree, BindingLocation.BaseTypes) Select Case syntaxNode.Kind Case SyntaxKind.ClassBlock Dim implementsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Implements ' class may implement interfaces ValidateImplementedInterfaces(implementsSyntax, interfaces, basesBeingResolved, binder, diagBag) Case SyntaxKind.StructureBlock Dim implementsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Implements ' struct may implement interfaces ValidateImplementedInterfaces(implementsSyntax, interfaces, basesBeingResolved, binder, diagBag) Case SyntaxKind.InterfaceBlock Dim implementsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Inherits ' interface may inherit interfaces ValidateInheritedInterfaces(implementsSyntax, interfaces, basesBeingResolved, binder, diagBag) Case SyntaxKind.ModuleBlock Dim implementsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Implements CheckNoBase(implementsSyntax, ERRID.ERR_ModuleCantImplement, diagBag) End Select End Sub ' Check that there are no base declarations in the given list, and report the given error if any are found. Private Sub CheckNoBase(Of T As InheritsOrImplementsStatementSyntax)(baseDeclList As SyntaxList(Of T), errId As ERRID, diagBag As BindingDiagnosticBag) If baseDeclList.Count > 0 Then For Each baseDecl In baseDeclList Binder.ReportDiagnostic(diagBag, baseDecl, errId) Next End If End Sub ' Validate the base class declared by a class, diagnosing errors. ' If a base class is found already in another partial, it is passed as baseInOtherPartial. ' Returns the base class if a good base class was found, otherwise Nothing. Private Function ValidateClassBase(inheritsSyntax As SyntaxList(Of InheritsStatementSyntax), baseInOtherPartial As NamedTypeSymbol, basesBeingResolved As BasesBeingResolved, binder As Binder, diagBag As BindingDiagnosticBag) As NamedTypeSymbol If inheritsSyntax.Count = 0 Then Return Nothing ' Add myself to the set of classes whose bases are being resolved basesBeingResolved = basesBeingResolved.PrependInheritsBeingResolved(Me) binder = New BasesBeingResolvedBinder(binder, basesBeingResolved) ' Get the first base class declared, and give errors for multiple base classes Dim baseClassSyntax As TypeSyntax = Nothing For Each baseDeclaration In inheritsSyntax If baseDeclaration.Kind = SyntaxKind.InheritsStatement Then Dim inheritsDeclaration = DirectCast(baseDeclaration, InheritsStatementSyntax) If baseClassSyntax IsNot Nothing OrElse inheritsDeclaration.Types.Count > 1 Then Binder.ReportDiagnostic(diagBag, inheritsDeclaration, ERRID.ERR_MultipleExtends) End If If baseClassSyntax Is Nothing AndAlso inheritsDeclaration.Types.Count > 0 Then baseClassSyntax = inheritsDeclaration.Types(0) End If End If Next If baseClassSyntax Is Nothing Then Return Nothing End If ' Bind the base class. Dim baseClassType = binder.BindTypeSyntax(baseClassSyntax, diagBag, suppressUseSiteError:=True, resolvingBaseType:=True) If baseClassType Is Nothing Then Return Nothing End If ' Check to make sure the base class is valid. Dim diagInfo As DiagnosticInfo = Nothing Select Case baseClassType.TypeKind Case TypeKind.TypeParameter Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_GenericParamBase2, "Class", Me.Name) Return Nothing Case TypeKind.Interface, TypeKind.Enum, TypeKind.Delegate, TypeKind.Structure, TypeKind.Module, TypeKind.Array ' array can't really occur Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_InheritsFromNonClass) Return Nothing Case TypeKind.Error, TypeKind.Unknown Return DirectCast(baseClassType, NamedTypeSymbol) Case TypeKind.Class If IsRestrictedBaseClass(baseClassType.SpecialType) Then Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_InheritsFromRestrictedType1, baseClassType) Return Nothing ElseIf DirectCast(baseClassType, NamedTypeSymbol).IsNotInheritable Then Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_InheritsFromCantInherit3, Me.Name, baseClassType.Name, baseClassType.GetKindText()) Return Nothing End If End Select ' The same base class can be declared in multiple partials, but not different ones If baseInOtherPartial IsNot Nothing Then If Not baseClassType.Equals(baseInOtherPartial) Then Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_BaseMismatchForPartialClass3, baseClassType, Me.Name, baseInOtherPartial) Return Nothing End If ElseIf Not baseClassType.IsErrorType() Then ' Verify that we don't have public classes inheriting from private ones, etc. AccessCheck.VerifyAccessExposureOfBaseClassOrInterface(Me, baseClassSyntax, baseClassType, diagBag) End If Return DirectCast(baseClassType, NamedTypeSymbol) End Function Private Sub ValidateInheritedInterfaces(baseSyntax As SyntaxList(Of InheritsStatementSyntax), basesInOtherPartials As SetWithInsertionOrder(Of NamedTypeSymbol), basesBeingResolved As BasesBeingResolved, binder As Binder, diagBag As BindingDiagnosticBag) If baseSyntax.Count = 0 Then Return ' Add myself to the set of classes whose bases are being resolved basesBeingResolved = basesBeingResolved.PrependInheritsBeingResolved(Me) binder = New BasesBeingResolvedBinder(binder, basesBeingResolved) ' give errors for multiple base classes Dim interfacesInThisPartial As New HashSet(Of NamedTypeSymbol)() For Each baseDeclaration In baseSyntax Dim types = DirectCast(baseDeclaration, InheritsStatementSyntax).Types For Each baseClassSyntax In types Dim typeSymbol = binder.BindTypeSyntax(baseClassSyntax, diagBag, suppressUseSiteError:=True) Dim namedType = TryCast(typeSymbol, NamedTypeSymbol) If namedType IsNot Nothing AndAlso interfacesInThisPartial.Contains(namedType) Then Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_DuplicateInInherits1, typeSymbol) Else If namedType IsNot Nothing Then interfacesInThisPartial.Add(namedType) End If ' Check to make sure the base interfaces are valid. Select Case typeSymbol.TypeKind Case TypeKind.TypeParameter Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_GenericParamBase2, "Interface", Me.Name) Continue For Case TypeKind.Unknown Continue For Case TypeKind.Interface, TypeKind.Error basesInOtherPartials.Add(namedType) If Not typeSymbol.IsErrorType() Then ' Make sure that we aren't exposing an interface with a restricted type, ' e.g. a public interface can't inherit from a private interface AccessCheck.VerifyAccessExposureOfBaseClassOrInterface(Me, baseClassSyntax, typeSymbol, diagBag) End If Case Else Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_InheritsFromNonInterface) Continue For End Select End If Next Next End Sub Private Sub ValidateImplementedInterfaces(baseSyntax As SyntaxList(Of ImplementsStatementSyntax), basesInOtherPartials As SetWithInsertionOrder(Of NamedTypeSymbol), basesBeingResolved As BasesBeingResolved, binder As Binder, diagBag As BindingDiagnosticBag) If baseSyntax.Count = 0 Then Return ' Add myself to the set of classes whose implemented interfaces are being resolved basesBeingResolved = basesBeingResolved.PrependImplementsBeingResolved(Me) binder = New BasesBeingResolvedBinder(binder, basesBeingResolved) ' give errors for multiple base classes Dim interfacesInThisPartial As New HashSet(Of TypeSymbol)() For Each baseDeclaration In baseSyntax Dim types = DirectCast(baseDeclaration, ImplementsStatementSyntax).Types For Each baseClassSyntax In types Dim typeSymbol = binder.BindTypeSyntax(baseClassSyntax, diagBag, suppressUseSiteError:=True) If Not interfacesInThisPartial.Add(typeSymbol) Then Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_InterfaceImplementedTwice1, typeSymbol) Else ' Check to make sure the base interfaces are valid. Select Case typeSymbol.TypeKind Case TypeKind.TypeParameter Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_ImplementsGenericParam, "Interface", Me.Name) Continue For Case TypeKind.Unknown Continue For Case TypeKind.Interface, TypeKind.Error basesInOtherPartials.Add(DirectCast(typeSymbol, NamedTypeSymbol)) Case Else Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_BadImplementsType) Continue For End Select End If Next Next End Sub ' Determines if this type is one of the special types we can't inherit from Private Function IsRestrictedBaseClass(type As SpecialType) As Boolean Select Case type Case SpecialType.System_Array, SpecialType.System_Delegate, SpecialType.System_MulticastDelegate, SpecialType.System_Enum, SpecialType.System_ValueType Return True Case Else Return False End Select End Function Private Function AsPeOrRetargetingType(potentialBaseType As TypeSymbol) As NamedTypeSymbol Dim peType As NamedTypeSymbol = TryCast(potentialBaseType, Symbols.Metadata.PE.PENamedTypeSymbol) If peType Is Nothing Then peType = TryCast(potentialBaseType, Retargeting.RetargetingNamedTypeSymbol) End If Return peType End Function Friend Overrides Function MakeDeclaredBase(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol ' For types nested in a source type symbol (not in a script class): ' before resolving the base type ensure that enclosing type's base type is already resolved Dim containingSourceType = TryCast(ContainingSymbol, SourceNamedTypeSymbol) If containingSourceType IsNot Nothing Then containingSourceType.GetDeclaredBaseSafe(basesBeingResolved.PrependInheritsBeingResolved(Me)) End If Dim baseType As NamedTypeSymbol = Nothing ' Go through all the parts of this type, and declare the information in that part, ' reporting errors appropriately. For Each decl In Me.TypeDeclaration.Declarations If decl.HasBaseDeclarations Then Dim syntaxRef = decl.SyntaxReference MakeDeclaredBaseInPart(syntaxRef.SyntaxTree, syntaxRef.GetVisualBasicSyntax(), baseType, basesBeingResolved, diagnostics) End If Next Return baseType End Function Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) ' For types nested in a source type symbol (not in a script class): ' before resolving the base type ensure that enclosing type's base type is already resolved Dim containingSourceType = TryCast(ContainingSymbol, SourceNamedTypeSymbol) If Me.IsInterface AndAlso containingSourceType IsNot Nothing AndAlso containingSourceType.IsInterface Then containingSourceType.GetDeclaredBaseInterfacesSafe(basesBeingResolved.PrependInheritsBeingResolved(Me)) End If Dim interfaces As New SetWithInsertionOrder(Of NamedTypeSymbol) ' Go through all the parts of this type, and declare the information in that part, ' reporting errors appropriately. For Each syntaxRef In SyntaxReferences MakeDeclaredInterfacesInPart(syntaxRef.SyntaxTree, syntaxRef.GetVisualBasicSyntax(), interfaces, basesBeingResolved, diagnostics) Next Return interfaces.AsImmutable End Function Private Function GetInheritsLocation(base As NamedTypeSymbol) As Location Return GetInheritsOrImplementsLocation(base, True) End Function Protected Overrides Function GetInheritsOrImplementsLocation(base As NamedTypeSymbol, getInherits As Boolean) As Location Dim backupLocation As Location = Nothing For Each part In SyntaxReferences Dim typeBlock = DirectCast(part.GetSyntax(), TypeBlockSyntax) Dim inhDecl = If(getInherits, DirectCast(typeBlock.Inherits, IEnumerable(Of InheritsOrImplementsStatementSyntax)), DirectCast(typeBlock.Implements, IEnumerable(Of InheritsOrImplementsStatementSyntax))) Dim binder As Binder = CreateLocationSpecificBinderForType(part.SyntaxTree, BindingLocation.BaseTypes) Dim basesBeingResolved As BasesBeingResolved = Nothing If getInherits Then basesBeingResolved = basesBeingResolved.PrependInheritsBeingResolved(Me) Else basesBeingResolved = basesBeingResolved.PrependImplementsBeingResolved(Me) End If binder = New BasesBeingResolvedBinder(binder, basesBeingResolved) For Each t In inhDecl If backupLocation Is Nothing Then backupLocation = t.GetLocation() End If Dim types As SeparatedSyntaxList(Of TypeSyntax) = If(getInherits, DirectCast(t, InheritsStatementSyntax).Types, DirectCast(t, ImplementsStatementSyntax).Types) For Each typeSyntax In types Dim bt = binder.BindTypeSyntax(typeSyntax, BindingDiagnosticBag.Discarded, suppressUseSiteError:=True) If TypeSymbol.Equals(bt, base, TypeCompareKind.ConsiderEverything) Then Return typeSyntax.GetLocation() End If Next Next Next ' In recursive or circular cases, the BindTypeSyntax fails to give the same result as the circularity ' removing algorithm does. In this case, use the entire Inherits or Implements statement as the location. Return backupLocation End Function Friend Overrides Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Dim compilation As VisualBasicCompilation = Me.DeclaringCompilation Dim declaredBase As NamedTypeSymbol = Me.GetDeclaredBase(Nothing) If declaredBase IsNot Nothing Then Dim diag As DiagnosticInfo = If(m_baseCycleDiagnosticInfo, BaseTypeAnalysis.GetDependenceDiagnosticForBase(Me, declaredBase)) If diag IsNot Nothing Then Dim location = GetInheritsLocation(declaredBase) ' TODO: if there is a cycle dependency in base type we might want to ignore all ' other diagnostics collected so far because they may be incorrectly generated ' because of the cycle -- check and decide if we want to do so 'diagnostics.Clear() diagnostics.Add(New VBDiagnostic(diag, location)) Return New ExtendedErrorTypeSymbol(diag, False) End If End If Dim declaredOrDefaultBase As NamedTypeSymbol = declaredBase ' Get the default base type if none was declared If declaredOrDefaultBase Is Nothing AndAlso Me.SpecialType <> Microsoft.CodeAnalysis.SpecialType.System_Object Then Select Case TypeKind Case TypeKind.Submission ' check that System.Object is available. ' Although the submission semantically doesn't have a base class we need to emit one. ReportUseSiteInfoForBaseType(Me.DeclaringCompilation.GetSpecialType(SpecialType.System_Object), declaredBase, diagnostics) declaredOrDefaultBase = Nothing Case TypeKind.Class declaredOrDefaultBase = GetSpecialType(SpecialType.System_Object) Case TypeKind.Interface declaredOrDefaultBase = Nothing Case TypeKind.Enum declaredOrDefaultBase = GetSpecialType(SpecialType.System_Enum) Case TypeKind.Structure declaredOrDefaultBase = GetSpecialType(SpecialType.System_ValueType) Case TypeKind.Delegate declaredOrDefaultBase = GetSpecialType(SpecialType.System_MulticastDelegate) Case TypeKind.Module declaredOrDefaultBase = GetSpecialType(SpecialType.System_Object) Case Else Throw ExceptionUtilities.UnexpectedValue(TypeKind) End Select End If If declaredOrDefaultBase IsNot Nothing Then ReportUseSiteInfoForBaseType(declaredOrDefaultBase, declaredBase, diagnostics) End If Return declaredOrDefaultBase End Function Private Function GetSpecialType(type As SpecialType) As NamedTypeSymbol Return ContainingModule.ContainingAssembly.GetSpecialType(type) End Function Private Sub ReportUseSiteInfoForBaseType(baseType As NamedTypeSymbol, declaredBase As NamedTypeSymbol, diagnostics As BindingDiagnosticBag) Dim useSiteInfo As New CompoundUseSiteInfo(Of AssemblySymbol)(diagnostics, ContainingAssembly) Dim current As NamedTypeSymbol = baseType Do If current.DeclaringCompilation Is Me.DeclaringCompilation Then Exit Do End If current.AddUseSiteInfo(useSiteInfo) current = current.BaseTypeNoUseSiteDiagnostics Loop While current IsNot Nothing If Not useSiteInfo.Diagnostics.IsNullOrEmpty Then Dim location As Location If declaredBase Is baseType Then location = GetInheritsLocation(baseType) Else Dim syntaxRef = SyntaxReferences.First() Dim syntax = syntaxRef.GetVisualBasicSyntax() ' script, submission and implicit classes have no identifier location: location = If(syntax.Kind = SyntaxKind.CompilationUnit OrElse syntax.Kind = SyntaxKind.NamespaceBlock, Locations(0), GetTypeIdentifierToken(syntax).GetLocation()) End If diagnostics.Add(location, useSiteInfo) Else diagnostics.AddDependencies(useSiteInfo) End If End Sub Friend Overrides Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Dim declaredInterfaces As ImmutableArray(Of NamedTypeSymbol) = GetDeclaredInterfacesNoUseSiteDiagnostics(Nothing) Dim isInterface As Boolean = Me.IsInterfaceType() Dim result As ArrayBuilder(Of NamedTypeSymbol) = If(isInterface, ArrayBuilder(Of NamedTypeSymbol).GetInstance(), Nothing) For Each t In declaredInterfaces Dim diag = If(isInterface AndAlso Not t.IsErrorType(), GetDependenceDiagnosticForBase(Me, t), Nothing) If diag IsNot Nothing Then Dim location = GetInheritsLocation(t) diagnostics.Add(New VBDiagnostic(diag, location)) result.Add(New ExtendedErrorTypeSymbol(diag, False)) Else ' Error types were reported elsewhere. If Not t.IsErrorType() Then Dim useSiteInfo As New CompoundUseSiteInfo(Of AssemblySymbol)(diagnostics, ContainingAssembly) If t.DeclaringCompilation IsNot Me.DeclaringCompilation Then t.AddUseSiteInfo(useSiteInfo) For Each [interface] In t.AllInterfacesNoUseSiteDiagnostics If [interface].DeclaringCompilation IsNot Me.DeclaringCompilation Then [interface].AddUseSiteInfo(useSiteInfo) End If Next End If If Not useSiteInfo.Diagnostics.IsNullOrEmpty Then Dim location = If(isInterface, GetInheritsLocation(t), GetInheritsOrImplementsLocation(t, getInherits:=False)) diagnostics.Add(location, useSiteInfo) Else diagnostics.AddDependencies(useSiteInfo) End If End If If isInterface Then result.Add(t) End If End If Next Return If(isInterface, result.ToImmutableAndFree, declaredInterfaces) End Function Friend Overrides Function GetDirectBaseTypeNoUseSiteDiagnostics(basesBeingResolved As BasesBeingResolved) As NamedTypeSymbol Debug.Assert(Me.TypeKind <> TypeKind.Interface) If TypeKind = TypeKind.Enum Then ' Base type has the underlying type instead. Return GetSpecialType(SpecialType.System_Enum) ElseIf TypeKind = TypeKind.Delegate Then ' Base type has the underlying type instead. Return GetSpecialType(SpecialType.System_MulticastDelegate) Else If basesBeingResolved.InheritsBeingResolvedOpt Is Nothing Then Return Me.BaseTypeNoUseSiteDiagnostics Else Return GetDeclaredBaseSafe(basesBeingResolved) End If End If End Function ''' <summary> ''' 'Safe' version of GetDeclaredBase takes into account bases being resolved to make sure ''' we avoid infinite loops in some scenarios. Note that the cycle is being broken not when ''' we detect it, but when we detect it on the 'smallest' type of the cycle, this brings stability ''' in multithreaded scenarios while still ensures that we don't loop more than twice. ''' </summary> Private Function GetDeclaredBaseSafe(basesBeingResolved As BasesBeingResolved) As NamedTypeSymbol If m_baseCycleDiagnosticInfo IsNot Nothing Then ' We have already detected this type has a cycle and it was chosen ' to be the one which reports the problem and breaks the cycle Return Nothing End If Debug.Assert(basesBeingResolved.InheritsBeingResolvedOpt.Any) If Me Is basesBeingResolved.InheritsBeingResolvedOpt.Head Then ' This is a little tricky: the head of 'basesBeingResolved' represents the innermost ' type whose base is being resolved. That means if we start name lookup with that type ' as containing type and if we cannot find the name in its scope we want just to skip base ' type search and avoid any errors. We want this to happen only for that innermost type ' in base resolution chain. An example: ' ' Class A ' Class B ' Inherits D ' Lookup for 'D' starts in scope of 'B', we ' Class C ' are skipping diving into B's base class here ' End Class ' to make it possible to find A.D ' End Class ' Class D ' End Class ' End Class ' NOTE: that it the lookup is not the first indirect one, but B was found earlier ' during lookup process, we still can ignore B's base type because another ' error (B cannot reference itself in its Inherits clause) should be generated ' by this time, like in the following example: ' ' Class A ' Class B ' Inherits A.B.C ' <- error BC31447: Class 'A.B' cannot ' Class C ' reference itself in Inherits clause. ' End Class ' End Class ' Class D ' End Class ' End Class Return Nothing End If Dim diag As DiagnosticInfo = GetDependenceDiagnosticForBase(Me, basesBeingResolved) If diag Is Nothing Then Dim declaredBase As NamedTypeSymbol = GetDeclaredBase(basesBeingResolved) ' If we detected the cycle while calculating the declared base, return Nothing Return If(m_baseCycleDiagnosticInfo Is Nothing, declaredBase, Nothing) End If Dim prev = Interlocked.CompareExchange(m_baseCycleDiagnosticInfo, diag, Nothing) Debug.Assert(prev Is Nothing OrElse prev.GetMessage().Equals(diag.GetMessage())) Return Nothing End Function Friend Overrides Function GetDeclaredBaseInterfacesSafe(basesBeingResolved As BasesBeingResolved) As ImmutableArray(Of NamedTypeSymbol) Debug.Assert(Me.IsInterface) If m_baseCycleDiagnosticInfo IsNot Nothing Then ' We have already detected this type has a cycle and it was chosen ' to be the one which reports the problem and breaks the cycle Return Nothing End If Debug.Assert(basesBeingResolved.InheritsBeingResolvedOpt.Any) If Me Is basesBeingResolved.InheritsBeingResolvedOpt.Head Then Return Nothing End If Dim diag As DiagnosticInfo = GetDependenceDiagnosticForBase(Me, basesBeingResolved) If diag Is Nothing Then Dim declaredBases As ImmutableArray(Of NamedTypeSymbol) = GetDeclaredInterfacesNoUseSiteDiagnostics(basesBeingResolved) ' If we detected the cycle while calculating the declared base, return Nothing Return If(m_baseCycleDiagnosticInfo Is Nothing, declaredBases, ImmutableArray(Of NamedTypeSymbol).Empty) End If Dim prev = Interlocked.CompareExchange(m_baseCycleDiagnosticInfo, diag, Nothing) Debug.Assert(prev Is Nothing OrElse prev.GetMessage().Equals(diag.GetMessage())) Return Nothing End Function ''' <summary> ''' Do additional verification of base types the after acyclic base is found. This is ''' the chance to generate diagnostics that may require walking bases and as such ''' can be performed only after the base has been determined and cycles broken. ''' (For instance, checking constraints on Class B(Of T) Inherits A(Of B(Of T)).) ''' </summary> Private Sub CheckBaseConstraints() If (m_lazyState And StateFlags.ReportedBaseClassConstraintsDiagnostics) <> 0 Then Return End If Dim diagnostics As BindingDiagnosticBag = Nothing Dim localBase = BaseTypeNoUseSiteDiagnostics If localBase IsNot Nothing Then ' Check constraints on the first declaration with explicit bases. Dim singleDeclaration = FirstDeclarationWithExplicitBases() If singleDeclaration IsNot Nothing Then Dim location = singleDeclaration.NameLocation diagnostics = BindingDiagnosticBag.GetInstance() localBase.CheckAllConstraints(location, diagnostics, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagnostics, m_containingModule.ContainingAssembly)) If IsGenericType Then ' Check that generic type does not derive from System.Attribute. ' This check must be done here instead of in ValidateClassBase to avoid infinite recursion when there are ' cycles in the inheritance chain. In Dev10/11, the error was reported on the inherited statement, now it ' is reported on the class statement. Dim useSiteInfo As New CompoundUseSiteInfo(Of AssemblySymbol)(diagnostics, m_containingModule.ContainingAssembly) Dim isBaseType As Boolean = DeclaringCompilation.GetWellKnownType(WellKnownType.System_Attribute).IsBaseTypeOf(localBase, useSiteInfo) diagnostics.Add(location, useSiteInfo) If isBaseType Then ' WARNING: in case System_Attribute was not found or has errors, the above check may ' fail to detect inheritance from System.Attribute, but we assume that in this case ' another error will be generated anyway Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_GenericClassCannotInheritAttr) End If End If End If End If m_containingModule.AtomicSetFlagAndStoreDiagnostics(m_lazyState, StateFlags.ReportedBaseClassConstraintsDiagnostics, 0, diagnostics) If diagnostics IsNot Nothing Then diagnostics.Free() End If End Sub ''' <summary> ''' Do additional verification of interfaces after acyclic interfaces are found. This is ''' the chance to generate diagnostics that may need to walk interfaces and as such ''' can be performed only after the interfaces have been determined and cycles broken. ''' (For instance, checking constraints on Class C(Of T) Implements I(Of C(Of T)).) ''' </summary> Private Sub CheckInterfacesConstraints() If (m_lazyState And StateFlags.ReportedInterfacesConstraintsDiagnostics) <> 0 Then Return End If Dim diagnostics As BindingDiagnosticBag = Nothing Dim localInterfaces = InterfacesNoUseSiteDiagnostics If Not localInterfaces.IsEmpty Then ' Check constraints on the first declaration with explicit interfaces. Dim singleDeclaration = FirstDeclarationWithExplicitInterfaces() If singleDeclaration IsNot Nothing Then Dim location = singleDeclaration.NameLocation diagnostics = BindingDiagnosticBag.GetInstance() For Each [interface] In localInterfaces [interface].CheckAllConstraints(location, diagnostics, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagnostics, m_containingModule.ContainingAssembly)) Next End If End If If m_containingModule.AtomicSetFlagAndStoreDiagnostics(m_lazyState, StateFlags.ReportedInterfacesConstraintsDiagnostics, 0, diagnostics) Then DeclaringCompilation.SymbolDeclaredEvent(Me) End If If diagnostics IsNot Nothing Then diagnostics.Free() End If End Sub ''' <summary> ''' Return the first Class declaration with explicit base classes to use for ''' checking base class constraints. Other type declarations (Structures, ''' Modules, Interfaces) are ignored since other errors will have been ''' reported if those types include bases. ''' </summary> Private Function FirstDeclarationWithExplicitBases() As SingleTypeDeclaration For Each decl In TypeDeclaration.Declarations Dim syntaxNode = decl.SyntaxReference.GetVisualBasicSyntax() Select Case syntaxNode.Kind Case SyntaxKind.ClassBlock If DirectCast(syntaxNode, TypeBlockSyntax).Inherits.Count > 0 Then Return decl End If End Select Next Return Nothing End Function ''' <summary> ''' Return the first Class, Structure, or Interface declaration with explicit interfaces ''' to use for checking interface constraints. Other type declarations (Modules) are ''' ignored since other errors will have been reported if those types include interfaces. ''' </summary> Private Function FirstDeclarationWithExplicitInterfaces() As SingleTypeDeclaration For Each decl In TypeDeclaration.Declarations Dim syntaxNode = decl.SyntaxReference.GetVisualBasicSyntax() Select Case syntaxNode.Kind Case SyntaxKind.ClassBlock, SyntaxKind.StructureBlock If DirectCast(syntaxNode, TypeBlockSyntax).Implements.Count > 0 Then Return decl End If Case SyntaxKind.InterfaceBlock If DirectCast(syntaxNode, TypeBlockSyntax).Inherits.Count > 0 Then Return decl End If End Select Next Return Nothing End Function #End Region #Region "Enums" ''' <summary> ''' For enum types, gets the underlying type. Returns null on all other ''' kinds of types. ''' </summary> Public Overrides ReadOnly Property EnumUnderlyingType As NamedTypeSymbol Get If Not Me.IsEnumType Then Return Nothing End If Dim underlyingType = Me._lazyEnumUnderlyingType If underlyingType Is Nothing Then Dim tempDiags = BindingDiagnosticBag.GetInstance Dim blockRef = SyntaxReferences(0) Dim tree = blockRef.SyntaxTree Dim syntax = DirectCast(blockRef.GetSyntax, EnumBlockSyntax) Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, tree, Me) underlyingType = BindEnumUnderlyingType(syntax, binder, tempDiags) If Interlocked.CompareExchange(Me._lazyEnumUnderlyingType, underlyingType, Nothing) Is Nothing Then ContainingSourceModule.AddDeclarationDiagnostics(tempDiags) Else Debug.Assert(TypeSymbol.Equals(underlyingType, Me._lazyEnumUnderlyingType, TypeCompareKind.ConsiderEverything)) underlyingType = Me._lazyEnumUnderlyingType End If tempDiags.Free() End If Debug.Assert(underlyingType IsNot Nothing) Return underlyingType End Get End Property Private Function BindEnumUnderlyingType(syntax As EnumBlockSyntax, bodyBinder As Binder, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Dim underlyingType = syntax.EnumStatement.UnderlyingType If underlyingType IsNot Nothing AndAlso Not underlyingType.Type.IsMissing Then Dim type = bodyBinder.BindTypeSyntax(underlyingType.Type, diagnostics) If type.IsValidEnumUnderlyingType Then Return DirectCast(type, NamedTypeSymbol) Else Binder.ReportDiagnostic(diagnostics, underlyingType.Type, ERRID.ERR_InvalidEnumBase) End If End If Return bodyBinder.GetSpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32, syntax.EnumStatement.Identifier, diagnostics) End Function #End Region #Region "Attributes" Public ReadOnly Property DefaultAttributeLocation As AttributeLocation Implements IAttributeTargetSymbol.DefaultAttributeLocation Get Return AttributeLocation.Type End Get End Property Private Function GetAttributeDeclarations() As ImmutableArray(Of SyntaxList(Of AttributeListSyntax)) Dim result = TypeDeclaration.GetAttributeDeclarations() Debug.Assert(result.Length = 0 OrElse (Not Me.IsScriptClass AndAlso Not Me.IsImplicitClass)) ' Should be handled by above test. Return result End Function Private Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) If m_lazyCustomAttributesBag Is Nothing OrElse Not m_lazyCustomAttributesBag.IsSealed Then LoadAndValidateAttributes(OneOrMany.Create(GetAttributeDeclarations()), m_lazyCustomAttributesBag) End If Debug.Assert(m_lazyCustomAttributesBag.IsSealed) Return m_lazyCustomAttributesBag End Function ''' <summary> ''' Gets the attributes applied on this symbol. ''' Returns an empty array if there are no attributes. ''' </summary> Public NotOverridable Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me.GetAttributesBag().Attributes End Function Private Function GetDecodedWellKnownAttributeData() As CommonTypeWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.m_lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonTypeWellKnownAttributeData) End Function Friend Overrides ReadOnly Property HasCodeAnalysisEmbeddedAttribute As Boolean Get Dim data As TypeEarlyWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCodeAnalysisEmbeddedAttribute End Get End Property Friend Overrides ReadOnly Property HasVisualBasicEmbeddedAttribute As Boolean Get Dim data As TypeEarlyWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasVisualBasicEmbeddedAttribute End Get End Property Friend Overrides ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean Get If _lazyIsExtensibleInterface = ThreeState.Unknown Then _lazyIsExtensibleInterface = DecodeIsExtensibleInterface().ToThreeState() End If Return _lazyIsExtensibleInterface.Value End Get End Property Private Function DecodeIsExtensibleInterface() As Boolean If Me.IsInterfaceType() Then Dim data As TypeEarlyWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData() If data IsNot Nothing AndAlso data.HasAttributeForExtensibleInterface Then Return True End If For Each [interface] In Me.AllInterfacesNoUseSiteDiagnostics If [interface].IsExtensibleInterfaceNoUseSiteDiagnostics Then Return True End If Next End If Return False End Function ''' <summary> ''' Returns data decoded from early bound well-known attributes applied to the symbol or null if there are no applied attributes. ''' </summary> ''' <remarks> ''' Forces binding and decoding of attributes. ''' </remarks> Private Function GetEarlyDecodedWellKnownAttributeData() As TypeEarlyWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.m_lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsEarlyDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.EarlyDecodedWellKnownAttributeData, TypeEarlyWellKnownAttributeData) End Function Friend Overrides ReadOnly Property IsComImport As Boolean Get Dim data As TypeEarlyWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasComImportAttribute End Get End Property Friend Overrides ReadOnly Property CoClassType As TypeSymbol Get If _lazyCoClassType Is ErrorTypeSymbol.UnknownResultType Then If Not Me.IsInterface Then Interlocked.CompareExchange(_lazyCoClassType, Nothing, DirectCast(ErrorTypeSymbol.UnknownResultType, TypeSymbol)) Else Dim dummy As CommonTypeWellKnownAttributeData = GetDecodedWellKnownAttributeData() If _lazyCoClassType Is ErrorTypeSymbol.UnknownResultType Then ' if this is still ErrorTypeSymbol.UnknownResultType, interface ' does not have the attribute applied Interlocked.CompareExchange(_lazyCoClassType, Nothing, DirectCast(ErrorTypeSymbol.UnknownResultType, TypeSymbol)) End If End If End If Debug.Assert(_lazyCoClassType IsNot ErrorTypeSymbol.UnknownResultType) Debug.Assert(Me.IsInterface OrElse _lazyCoClassType Is Nothing) Return _lazyCoClassType End Get End Property Friend Overrides ReadOnly Property IsWindowsRuntimeImport As Boolean Get Dim typeData As CommonTypeWellKnownAttributeData = Me.GetDecodedWellKnownAttributeData() Return typeData IsNot Nothing AndAlso typeData.HasWindowsRuntimeImportAttribute End Get End Property Friend Overrides ReadOnly Property ShouldAddWinRTMembers As Boolean Get Return False End Get End Property Friend ReadOnly Property HasSecurityCriticalAttributes As Boolean Get Dim typeData As CommonTypeWellKnownAttributeData = Me.GetDecodedWellKnownAttributeData() Return typeData IsNot Nothing AndAlso typeData.HasSecurityCriticalAttributes End Get End Property ''' <summary> ''' Is System.Runtime.InteropServices.GuidAttribute applied to this type in code. ''' </summary> Friend Function HasGuidAttribute() As Boolean ' So far this information is used only by ComClass feature, therefore, I do not believe ' it is worth to intercept this attribute in DecodeWellKnownAttribute and cache the fact of attribute's ' presence and the guid value. If we start caching that information, implementation of this function ' should change to take advantage of the cache. Return GetAttributes().IndexOfAttribute(Me, AttributeDescription.GuidAttribute) > -1 End Function ''' <summary> ''' Is System.Runtime.InteropServices.ClassInterfaceAttribute applied to this type in code. ''' </summary> Friend Function HasClassInterfaceAttribute() As Boolean ' So far this information is used only by ComClass feature, therefore, I do not believe ' it is worth to intercept this attribute in DecodeWellKnownAttribute and cache the fact of attribute's ' presence and its data. If we start caching that information, implementation of this function ' should change to take advantage of the cache. Return GetAttributes().IndexOfAttribute(Me, AttributeDescription.ClassInterfaceAttribute) > -1 End Function ''' <summary> ''' Is System.Runtime.InteropServices.ComSourceInterfacesAttribute applied to this type in code. ''' </summary> Friend Function HasComSourceInterfacesAttribute() As Boolean ' So far this information is used only by ComClass feature, therefore, I do not believe ' it is worth to intercept this attribute in DecodeWellKnownAttribute and cache the fact of attribute's ' presence and the its data. If we start caching that information, implementation of this function ' should change to take advantage of the cache. Return GetAttributes().IndexOfAttribute(Me, AttributeDescription.ComSourceInterfacesAttribute) > -1 End Function Friend Overrides Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData Debug.Assert(arguments.AttributeType IsNot Nothing) Debug.Assert(Not arguments.AttributeType.IsErrorType()) Dim hasAnyDiagnostics As Boolean = False If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.VisualBasicEmbeddedAttribute) Then ' Handle Microsoft.VisualBasic.Embedded attribute Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().HasVisualBasicEmbeddedAttribute = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CodeAnalysisEmbeddedAttribute) Then ' Handle Microsoft.CodeAnalysis.Embedded attribute Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().HasCodeAnalysisEmbeddedAttribute = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ComImportAttribute) Then ' Handle ComImportAttribute Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().HasComImportAttribute = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ConditionalAttribute) Then ' Handle ConditionalAttribute Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then Dim conditionalSymbol As String = attrdata.GetConstructorArgument(Of String)(0, SpecialType.System_String) arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().AddConditionalSymbol(conditionalSymbol) Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If End If Dim boundAttribute As VisualBasicAttributeData = Nothing Dim obsoleteData As ObsoleteAttributeData = Nothing If EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(arguments, boundAttribute, obsoleteData) Then If obsoleteData IsNot Nothing Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().ObsoleteAttributeData = obsoleteData End If Return boundAttribute End If If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.AttributeUsageAttribute) Then ' Avoid decoding duplicate AttributeUsageAttribute. If Not arguments.HasDecodedData OrElse DirectCast(arguments.DecodedData, TypeEarlyWellKnownAttributeData).AttributeUsageInfo.IsNull Then ' Handle AttributeUsageAttribute: If this type is an attribute type then decode the AttributeUsageAttribute, otherwise ignore it. Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().AttributeUsageInfo = attrdata.DecodeAttributeUsageAttribute() Debug.Assert(Not DirectCast(arguments.DecodedData, TypeEarlyWellKnownAttributeData).AttributeUsageInfo.IsNull) ' NOTE: Native VB compiler does not validate the AttributeTargets argument to AttributeUsageAttribute, we do the same. Return If(Not hasAnyDiagnostics, attrdata, Nothing) End If End If Return Nothing End If If Me.IsInterfaceType() Then If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.InterfaceTypeAttribute) Then Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then Dim interfaceType As ComInterfaceType = Nothing If attrdata.DecodeInterfaceTypeAttribute(interfaceType) AndAlso (interfaceType And Cci.Constants.ComInterfaceType_InterfaceIsIDispatch) <> 0 Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData).HasAttributeForExtensibleInterface = True End If Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.TypeLibTypeAttribute) Then Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then Dim flags As Cci.TypeLibTypeFlags = attrdata.DecodeTypeLibTypeAttribute() If (flags And Cci.TypeLibTypeFlags.FNonExtensible) = 0 Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData).HasAttributeForExtensibleInterface = True End If Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If End If End If Return MyBase.EarlyDecodeWellKnownAttribute(arguments) End Function Friend NotOverridable Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Dim data As CommonTypeEarlyWellKnownAttributeData = Me.GetEarlyDecodedWellKnownAttributeData() Return If(data IsNot Nothing, data.ConditionalSymbols, ImmutableArray(Of String).Empty) End Function Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Dim lazyCustomAttributesBag = m_lazyCustomAttributesBag If lazyCustomAttributesBag IsNot Nothing AndAlso lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed Then Dim data = DirectCast(lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData, CommonTypeEarlyWellKnownAttributeData) Return If(data IsNot Nothing, data.ObsoleteAttributeData, Nothing) End If For Each decl In TypeDeclaration.Declarations If decl.HasAnyAttributes Then Return ObsoleteAttributeData.Uninitialized End If Next Return Nothing End Get End Property Friend NotOverridable Overrides Function GetAttributeUsageInfo() As AttributeUsageInfo Debug.Assert(Me.IsOrDerivedFromWellKnownClass(WellKnownType.System_Attribute, DeclaringCompilation, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) OrElse Me.SpecialType = Microsoft.CodeAnalysis.SpecialType.System_Object) Dim data As TypeEarlyWellKnownAttributeData = Me.GetEarlyDecodedWellKnownAttributeData() If data IsNot Nothing AndAlso Not data.AttributeUsageInfo.IsNull Then Return data.AttributeUsageInfo Else Dim baseType = Me.BaseTypeNoUseSiteDiagnostics Return If(baseType IsNot Nothing, baseType.GetAttributeUsageInfo(), AttributeUsageInfo.Default) End If End Function Friend NotOverridable Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Dim data As CommonTypeWellKnownAttributeData = Me.GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasDeclarativeSecurity End Get End Property Friend NotOverridable Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.GetAttributesBag() Dim wellKnownAttributeData = DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonTypeWellKnownAttributeData) If wellKnownAttributeData IsNot Nothing Then Dim securityData As SecurityWellKnownAttributeData = wellKnownAttributeData.SecurityInformation If securityData IsNot Nothing Then Return securityData.GetSecurityAttributes(attributesBag.Attributes) End If End If Return SpecializedCollections.EmptyEnumerable(Of Microsoft.Cci.SecurityAttribute)() End Function Friend NotOverridable Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) Dim attrData = arguments.Attribute Debug.Assert(Not attrData.HasErrors) Debug.Assert(arguments.SymbolPart = AttributeLocation.None) Dim diagnostics = DirectCast(arguments.Diagnostics, BindingDiagnosticBag) ' If we start caching information about GuidAttribute here, implementation of HasGuidAttribute function should be changed accordingly. ' If we start caching information about ClassInterfaceAttribute here, implementation of HasClassInterfaceAttribute function should be changed accordingly. ' If we start caching information about ComSourceInterfacesAttribute here, implementation of HasComSourceInterfacesAttribute function should be changed accordingly. ' If we start caching information about ComVisibleAttribute here, implementation of GetComVisibleState function should be changed accordingly. If attrData.IsTargetAttribute(Me, AttributeDescription.TupleElementNamesAttribute) Then diagnostics.Add(ERRID.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location) End If Dim decoded As Boolean = False Select Case Me.TypeKind Case TypeKind.Class If attrData.IsTargetAttribute(Me, AttributeDescription.CaseInsensitiveExtensionAttribute) Then diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionOnlyAllowedOnModuleSubOrFunction), Me.Locations(0)) decoded = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.VisualBasicComClassAttribute) Then If Me.IsGenericType Then diagnostics.Add(ERRID.ERR_ComClassOnGeneric, Me.Locations(0)) Else Interlocked.CompareExchange(_comClassData, New ComClassData(attrData), Nothing) End If decoded = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.DefaultEventAttribute) Then If attrData.CommonConstructorArguments.Length = 1 AndAlso attrData.CommonConstructorArguments(0).Kind = TypedConstantKind.Primitive Then Dim eventName = TryCast(attrData.CommonConstructorArguments(0).ValueInternal, String) If eventName IsNot Nothing AndAlso eventName.Length > 0 AndAlso Not FindDefaultEvent(eventName) Then diagnostics.Add(ERRID.ERR_DefaultEventNotFound1, arguments.AttributeSyntaxOpt.GetLocation(), eventName) End If End If decoded = True End If Case TypeKind.Interface If attrData.IsTargetAttribute(Me, AttributeDescription.CoClassAttribute) Then Debug.Assert(Not attrData.CommonConstructorArguments.IsDefault AndAlso attrData.CommonConstructorArguments.Length = 1) Dim argument As TypedConstant = attrData.CommonConstructorArguments(0) Debug.Assert(argument.Kind = TypedConstantKind.Type) Debug.Assert(argument.TypeInternal IsNot Nothing) Debug.Assert(DirectCast(argument.TypeInternal, TypeSymbol).Equals(DeclaringCompilation.GetWellKnownType(WellKnownType.System_Type), TypeCompareKind.ConsiderEverything)) ' Note that 'argument.Value' may be Nothing in which case Roslyn will ' generate an error as if CoClassAttribute attribute was not defined on ' the interface; this behavior matches Dev11, but we should probably ' revise it later Interlocked.CompareExchange(Me._lazyCoClassType, DirectCast(argument.ValueInternal, TypeSymbol), DirectCast(ErrorTypeSymbol.UnknownResultType, TypeSymbol)) decoded = True End If Case TypeKind.Module If ContainingSymbol.Kind = SymbolKind.Namespace AndAlso attrData.IsTargetAttribute(Me, AttributeDescription.CaseInsensitiveExtensionAttribute) Then ' Already have an attribute, no need to add another one. SuppressExtensionAttributeSynthesis() decoded = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.VisualBasicComClassAttribute) Then ' Can't apply ComClassAttribute to a Module diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_InvalidAttributeUsage2, AttributeDescription.VisualBasicComClassAttribute.Name, Me.Name), Me.Locations(0)) decoded = True End If End Select If Not decoded Then If attrData.IsTargetAttribute(Me, AttributeDescription.DefaultMemberAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasDefaultMemberAttribute = True ' Check that the explicit <DefaultMember(...)> argument matches the default property if any. Dim attributeValue = attrData.DecodeDefaultMemberAttribute() Dim defaultProperty = DefaultPropertyName If Not String.IsNullOrEmpty(defaultProperty) AndAlso Not IdentifierComparison.Equals(defaultProperty, attributeValue) Then diagnostics.Add(ERRID.ERR_ConflictDefaultPropertyAttribute, Locations(0), Me) End If ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SerializableAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasSerializableAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ExcludeFromCodeCoverageAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasExcludeFromCodeCoverageAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SpecialNameAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasSpecialNameAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.StructLayoutAttribute) Then Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) Dim defaultAutoLayoutSize = If(Me.TypeKind = TypeKind.Structure, 1, 0) AttributeData.DecodeStructLayoutAttribute(Of CommonTypeWellKnownAttributeData, AttributeSyntax, VisualBasicAttributeData, AttributeLocation)( arguments, Me.DefaultMarshallingCharSet, defaultAutoLayoutSize, MessageProvider.Instance) If Me.IsGenericType Then diagnostics.Add(ERRID.ERR_StructLayoutAttributeNotAllowed, arguments.AttributeSyntaxOpt.GetLocation(), Me) End If ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SuppressUnmanagedCodeSecurityAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasSuppressUnmanagedCodeSecurityAttribute = True ElseIf attrData.IsSecurityAttribute(Me.DeclaringCompilation) Then attrData.DecodeSecurityAttribute(Of CommonTypeWellKnownAttributeData)(Me, Me.DeclaringCompilation, arguments) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ClassInterfaceAttribute) Then attrData.DecodeClassInterfaceAttribute(arguments.AttributeSyntaxOpt, diagnostics) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.InterfaceTypeAttribute) Then attrData.DecodeInterfaceTypeAttribute(arguments.AttributeSyntaxOpt, diagnostics) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.GuidAttribute) Then attrData.DecodeGuidAttribute(arguments.AttributeSyntaxOpt, diagnostics) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.WindowsRuntimeImportAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasWindowsRuntimeImportAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SecurityCriticalAttribute) OrElse attrData.IsTargetAttribute(Me, AttributeDescription.SecuritySafeCriticalAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasSecurityCriticalAttributes = True ElseIf _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.Unknown AndAlso attrData.IsTargetAttribute(Me, AttributeDescription.TypeIdentifierAttribute) Then _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.RequiredAttributeAttribute) Then Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) diagnostics.Add(ERRID.ERR_CantUseRequiredAttribute, arguments.AttributeSyntaxOpt.GetLocation(), Me) End If End If MyBase.DecodeWellKnownAttribute(arguments) End Sub Friend Overrides ReadOnly Property IsExplicitDefinitionOfNoPiaLocalType As Boolean Get If _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.Unknown Then CheckPresenceOfTypeIdentifierAttribute() If _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.Unknown Then _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.False End If End If Debug.Assert(_lazyIsExplicitDefinitionOfNoPiaLocalType <> ThreeState.Unknown) Return _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.True End Get End Property Private Sub CheckPresenceOfTypeIdentifierAttribute() ' Have we already decoded well-known attributes? If Me.m_lazyCustomAttributesBag?.IsDecodedWellKnownAttributeDataComputed Then Return End If ' We want this function to be as cheap as possible, it is called for every top level type ' and we don't want to bind attributes attached to the declaration unless there is a chance ' that one of them is TypeIdentifier attribute. Dim attributeLists As ImmutableArray(Of SyntaxList(Of AttributeListSyntax)) = GetAttributeDeclarations() For Each list As SyntaxList(Of AttributeListSyntax) In attributeLists Dim sourceFile = ContainingSourceModule.TryGetSourceFile(list.Node.SyntaxTree) For Each attrList As AttributeListSyntax In list For Each attr As AttributeSyntax In attrList.Attributes If (sourceFile.QuickAttributeChecker.CheckAttribute(attr) And QuickAttributes.TypeIdentifier) <> 0 Then ' This attribute syntax might be an application of TypeIdentifierAttribute. ' Let's bind it. ' For simplicity we bind all attributes. GetAttributes() Return End If Next Next Next End Sub Private Function FindDefaultEvent(eventName As String) As Boolean Dim current As NamedTypeSymbol = Me Do For Each member As Symbol In current.GetMembers(eventName) If member.Kind = SymbolKind.Event AndAlso (member.DeclaredAccessibility = Accessibility.Public OrElse member.DeclaredAccessibility = Accessibility.Friend) Then ' We have a match so the default event is valid. Return True End If Next current = current.BaseTypeNoUseSiteDiagnostics Loop While current IsNot Nothing Return False End Function Friend Overrides Sub PostDecodeWellKnownAttributes( boundAttributes As ImmutableArray(Of VisualBasicAttributeData), allAttributeSyntaxNodes As ImmutableArray(Of AttributeSyntax), diagnostics As BindingDiagnosticBag, symbolPart As AttributeLocation, decodedData As WellKnownAttributeData) Debug.Assert(Not boundAttributes.IsDefault) Debug.Assert(Not allAttributeSyntaxNodes.IsDefault) Debug.Assert(boundAttributes.Length = allAttributeSyntaxNodes.Length) Debug.Assert(symbolPart = AttributeLocation.None) ValidateStandardModuleAttribute(diagnostics) MyBase.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData) End Sub Private Sub ValidateStandardModuleAttribute(diagnostics As BindingDiagnosticBag) ' If this type is a VB Module, touch the ctor for MS.VB.Globals.StandardModuleAttribute to ' produce any diagnostics related to that member and type. ' Dev10 reported a special diagnostic ERR_NoStdModuleAttribute if the constructor was missing. ' Roslyn now used the more general use site errors, which also reports diagnostics if the type or the constructor ' is missing. If Me.TypeKind = TypeKind.Module Then Dim useSiteError As DiagnosticInfo = Nothing Binder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor, Me.DeclaringCompilation, Locations(0), diagnostics) End If End Sub Friend NotOverridable Overrides ReadOnly Property IsDirectlyExcludedFromCodeCoverage As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasExcludeFromCodeCoverageAttribute End Get End Property Friend NotOverridable Overrides ReadOnly Property HasSpecialName As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasSpecialNameAttribute End Get End Property Public NotOverridable Overrides ReadOnly Property IsSerializable As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasSerializableAttribute End Get End Property Private Function HasInstanceFields() As Boolean Dim members = Me.GetMembersUnordered() For i = 0 To members.Length - 1 Dim m = members(i) If Not m.IsShared And m.Kind = SymbolKind.Field Then Return True End If Next Return False End Function Friend NotOverridable Overrides ReadOnly Property Layout As TypeLayout Get Dim data = GetDecodedWellKnownAttributeData() If data IsNot Nothing AndAlso data.HasStructLayoutAttribute Then Return data.Layout End If If Me.TypeKind = TypeKind.Structure Then ' CLI spec 22.37.16: ' "A ValueType shall have a non-zero size - either by defining at least one field, or by providing a non-zero ClassSize" ' ' Dev11 compiler sets the value to 1 for structs with no fields and no size specified. ' It does not change the size value if it was explicitly specified to be 0, nor does it report an error. Return New TypeLayout(LayoutKind.Sequential, If(Me.HasInstanceFields(), 0, 1), alignment:=0) End If Return Nothing End Get End Property Friend ReadOnly Property HasStructLayoutAttribute As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasStructLayoutAttribute End Get End Property Friend Overrides ReadOnly Property MarshallingCharSet As CharSet Get Dim data = GetDecodedWellKnownAttributeData() Return If((data IsNot Nothing AndAlso data.HasStructLayoutAttribute), data.MarshallingCharSet, DefaultMarshallingCharSet) End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) Dim compilation = Me.DeclaringCompilation If Not String.IsNullOrEmpty(DefaultPropertyName) AndAlso Not HasDefaultMemberAttribute() Then Dim stringType = GetSpecialType(SpecialType.System_String) ' NOTE: used from emit, so shouldn't have gotten here if there were errors Debug.Assert(stringType.GetUseSiteInfo().DiagnosticInfo Is Nothing) AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Reflection_DefaultMemberAttribute__ctor, ImmutableArray.Create( New TypedConstant(stringType, TypedConstantKind.Primitive, DefaultPropertyName)))) End If If Me.TypeKind = TypeKind.Module Then 'TODO check that there's not a user supplied instance already. This attribute is AllowMultiple:=False. AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor)) End If If _comClassData IsNot Nothing Then If _comClassData.ClassId IsNot Nothing Then AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_InteropServices_GuidAttribute__ctor, ImmutableArray.Create( New TypedConstant(GetSpecialType(SpecialType.System_String), TypedConstantKind.Primitive, _comClassData.ClassId)))) End If AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_InteropServices_ClassInterfaceAttribute__ctorClassInterfaceType, ImmutableArray.Create( New TypedConstant(GetSpecialType(SpecialType.System_Int32), TypedConstantKind.Enum, CInt(ClassInterfaceType.None))))) Dim eventInterface As NamedTypeSymbol = _comClassData.GetSynthesizedEventInterface() If eventInterface IsNot Nothing Then Dim eventInterfaceName As String = eventInterface.Name Dim container1 As NamedTypeSymbol = Me Dim container2 As NamedTypeSymbol = container1.ContainingType While container2 IsNot Nothing eventInterfaceName = container1.Name & "+" & eventInterfaceName container1 = container2 container2 = container1.ContainingType End While eventInterfaceName = container1.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) & "+" & eventInterfaceName AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_InteropServices_ComSourceInterfacesAttribute__ctorString, ImmutableArray.Create( New TypedConstant(GetSpecialType(SpecialType.System_String), TypedConstantKind.Primitive, eventInterfaceName)))) End If End If Dim baseType As NamedTypeSymbol = Me.BaseTypeNoUseSiteDiagnostics If baseType IsNot Nothing Then If baseType.ContainsTupleNames() Then AddSynthesizedAttribute(attributes, compilation.SynthesizeTupleNamesAttribute(baseType)) End If End If End Sub Private Function HasDefaultMemberAttribute() As Boolean Dim attributesBag = GetAttributesBag() Dim wellKnownAttributeData = DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonTypeWellKnownAttributeData) Return (wellKnownAttributeData IsNot Nothing) AndAlso wellKnownAttributeData.HasDefaultMemberAttribute End Function #End Region Friend Function GetOrAddWithEventsOverride(baseProperty As PropertySymbol) As SynthesizedOverridingWithEventsProperty Dim overridesDict = Me._lazyWithEventsOverrides If overridesDict Is Nothing Then Interlocked.CompareExchange(Me._lazyWithEventsOverrides, New ConcurrentDictionary(Of PropertySymbol, SynthesizedOverridingWithEventsProperty), Nothing) overridesDict = Me._lazyWithEventsOverrides End If Dim result As SynthesizedOverridingWithEventsProperty = Nothing If overridesDict.TryGetValue(baseProperty, result) Then Return result Else ' we need to create a lambda here since we need to close over baseProperty ' we will however create a lambda only on a cache miss, hopefully not very often. Return overridesDict.GetOrAdd(baseProperty, Function() Debug.Assert(Not _withEventsOverridesAreFrozen) Return New SynthesizedOverridingWithEventsProperty(baseProperty, Me) End Function) End If End Function Friend NotOverridable Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) EnsureAllHandlesAreBound() Dim overridesDict = Me._lazyWithEventsOverrides If overridesDict IsNot Nothing Then Return overridesDict.Values End If Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)() End Function Private Sub EnsureAllHandlesAreBound() If Not _withEventsOverridesAreFrozen Then For Each member In Me.GetMembersUnordered() If member.Kind = SymbolKind.Method Then Dim notUsed = DirectCast(member, MethodSymbol).HandledEvents End If Next _withEventsOverridesAreFrozen = True End If End Sub Protected Overrides Sub AddEntryPointIfNeeded(membersBuilder As MembersAndInitializersBuilder) If Me.TypeKind = TypeKind.Class AndAlso Not Me.IsGenericType Then Dim mainTypeName As String = DeclaringCompilation.Options.MainTypeName If mainTypeName IsNot Nothing AndAlso IdentifierComparison.EndsWith(mainTypeName, Me.Name) AndAlso IdentifierComparison.Equals(mainTypeName, Me.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)) Then ' Must derive from Windows.Forms.Form Dim formClass As NamedTypeSymbol = DeclaringCompilation.GetWellKnownType(WellKnownType.System_Windows_Forms_Form) If formClass.IsErrorType() OrElse Not Me.IsOrDerivedFrom(formClass, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then Return End If Dim entryPointMethodName As String = WellKnownMemberNames.EntryPointMethodName ' If we already have a child named 'Main', do not add a synthetic one. If membersBuilder.Members.ContainsKey(entryPointMethodName) Then Return End If If GetTypeMembersDictionary().ContainsKey(entryPointMethodName) Then Return End If ' We need to have a constructor that can be called without arguments. Dim symbols As ArrayBuilder(Of Symbol) = Nothing Dim haveSuitableConstructor As Boolean = False If membersBuilder.Members.TryGetValue(WellKnownMemberNames.InstanceConstructorName, symbols) Then For Each method As MethodSymbol In symbols If method.MethodKind = MethodKind.Constructor AndAlso method.ParameterCount = 0 Then haveSuitableConstructor = True Exit For End If Next If Not haveSuitableConstructor Then ' Do the second pass to check for optional parameters, etc., it will require binding parameter modifiers and probably types. For Each method As MethodSymbol In symbols If method.MethodKind = MethodKind.Constructor AndAlso method.CanBeCalledWithNoParameters() Then haveSuitableConstructor = True Exit For End If Next End If End If If haveSuitableConstructor Then Dim syntaxRef = SyntaxReferences.First() ' use arbitrary part Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, syntaxRef.SyntaxTree, Me) Dim entryPoint As New SynthesizedMainTypeEntryPoint(syntaxRef.GetVisualBasicSyntax(), Me) AddMember(entryPoint, binder, membersBuilder, omitDiagnostics:=True) End If End If End If End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Concurrent Imports System.Collections.Generic Imports System.Collections.Immutable Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a type or module declared in source. ''' Could be a class, structure, interface, delegate, enum, or module. ''' </summary> Partial Friend Class SourceNamedTypeSymbol Inherits SourceMemberContainerTypeSymbol Implements IAttributeTargetSymbol ' Type parameters (Nothing if not created yet) Private _lazyTypeParameters As ImmutableArray(Of TypeParameterSymbol) ' Attributes on type. Set once after construction. IsNull means not set. Protected m_lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) Private ReadOnly _corTypeId As SpecialType Private _lazyDocComment As String Private _lazyExpandedDocComment As String Private _lazyEnumUnderlyingType As NamedTypeSymbol ' Stores symbols for overriding WithEvents properties if we have such ' Overriding properties are created when a methods "Handles" is bound and can happen concurrently. ' We need this table to ensure that we create each override just once. Private _lazyWithEventsOverrides As ConcurrentDictionary(Of PropertySymbol, SynthesizedOverridingWithEventsProperty) Private _withEventsOverridesAreFrozen As Boolean ' method flags for the synthesized delegate methods Friend Const DelegateConstructorMethodFlags As SourceMemberFlags = SourceMemberFlags.MethodKindConstructor Friend Const DelegateCommonMethodFlags As SourceMemberFlags = SourceMemberFlags.Overridable Private _lazyLexicalSortKey As LexicalSortKey = LexicalSortKey.NotInitialized Private _lazyIsExtensibleInterface As ThreeState = ThreeState.Unknown Private _lazyIsExplicitDefinitionOfNoPiaLocalType As ThreeState = ThreeState.Unknown ''' <summary> ''' Information for ComClass specific analysis and metadata generation, created ''' once ComClassAttribute is encountered. ''' </summary> Private _comClassData As ComClassData ''' <summary> ''' Lazy CoClass type if the attribute is specified. Nothing if not. ''' </summary> Private _lazyCoClassType As TypeSymbol = ErrorTypeSymbol.UnknownResultType ''' <summary> ''' In case a cyclic dependency was detected during base type resolution ''' this field stores the diagnostic. ''' </summary> Protected m_baseCycleDiagnosticInfo As DiagnosticInfo = Nothing ' Create the type symbol and associated type parameter symbols. Most information ' is deferred until later. Friend Sub New(declaration As MergedTypeDeclaration, containingSymbol As NamespaceOrTypeSymbol, containingModule As SourceModuleSymbol) MyBase.New(declaration, containingSymbol, containingModule) ' check if this is one of the COR library types If containingSymbol.Kind = SymbolKind.Namespace AndAlso containingSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes AndAlso Me.DeclaredAccessibility = Accessibility.Public Then Dim emittedName As String = If(Me.GetEmittedNamespaceName(), Me.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)) Debug.Assert((Arity <> 0) = MangleName) emittedName = MetadataHelpers.BuildQualifiedName(emittedName, MetadataName) _corTypeId = SpecialTypes.GetTypeFromMetadataName(emittedName) Else _corTypeId = SpecialType.None End If If containingSymbol.Kind = SymbolKind.NamedType Then ' Nested types are never unified. _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.False End If End Sub Public Overrides ReadOnly Property SpecialType As SpecialType Get Return _corTypeId End Get End Property #Region "Completion" Protected Overrides Sub GenerateAllDeclarationErrorsImpl(cancellationToken As CancellationToken) #If DEBUG Then EnsureAllHandlesAreBound() #End If MyBase.GenerateAllDeclarationErrorsImpl(cancellationToken) _withEventsOverridesAreFrozen = True cancellationToken.ThrowIfCancellationRequested() PerformComClassAnalysis() cancellationToken.ThrowIfCancellationRequested() CheckBaseConstraints() cancellationToken.ThrowIfCancellationRequested() CheckInterfacesConstraints() End Sub #End Region #Region "Syntax" Friend Function GetTypeIdentifierToken(node As VisualBasicSyntaxNode) As SyntaxToken Select Case node.Kind Case SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock Return DirectCast(node, TypeBlockSyntax).BlockStatement.Identifier Case SyntaxKind.EnumBlock Return DirectCast(node, EnumBlockSyntax).EnumStatement.Identifier Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(node, DelegateStatementSyntax).Identifier Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select End Function Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String If expandIncludes Then Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyExpandedDocComment, cancellationToken) Else Return GetAndCacheDocumentationComment(Me, preferredCulture, expandIncludes, _lazyDocComment, cancellationToken) End If End Function ' Create a LocationSpecificBinder for the type. This is a binder that wraps the ' default binder for the type in a binder that will avoid checking constraints, ' for cases where constraint checking may result in a recursive binding attempt. Private Function CreateLocationSpecificBinderForType(tree As SyntaxTree, location As BindingLocation) As Binder Debug.Assert(location <> BindingLocation.None) Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, tree, Me) Return New LocationSpecificBinder(location, binder) End Function #End Region #Region "Members" Protected Overrides Sub AddDeclaredNonTypeMembers(membersBuilder As SourceMemberContainerTypeSymbol.MembersAndInitializersBuilder, diagnostics As BindingDiagnosticBag) Dim accessModifiers As DeclarationModifiers = Nothing Dim foundModifiers As DeclarationModifiers Dim foundPartial As Boolean = False Dim nodeNameIsAlreadyDefined As Boolean = False Dim firstNode As VisualBasicSyntaxNode = Nothing Dim countMissingPartial = 0 For Each syntaxRef In SyntaxReferences Dim node = syntaxRef.GetVisualBasicSyntax() ' Set up a binder for this part of the type. Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, syntaxRef.SyntaxTree, Me) ' Script and implicit classes are syntactically represented by CompilationUnitSyntax or NamespaceBlockSyntax nodes. Dim staticInitializers As ArrayBuilder(Of FieldOrPropertyInitializer) = Nothing Dim instanceInitializers As ArrayBuilder(Of FieldOrPropertyInitializer) = Nothing foundModifiers = AddMembersInPart(binder, node, diagnostics, accessModifiers, membersBuilder, staticInitializers, instanceInitializers, nodeNameIsAlreadyDefined) If accessModifiers = Nothing Then accessModifiers = foundModifiers And DeclarationModifiers.AllAccessibilityModifiers End If If (foundModifiers And DeclarationModifiers.Partial) <> 0 Then If Not foundPartial Then firstNode = node foundPartial = True End If Else countMissingPartial += 1 If firstNode Is Nothing Then firstNode = node End If End If ' add the collected initializers for this (partial) type to the collections ' and free the array builders AddInitializers(membersBuilder.StaticInitializers, staticInitializers) AddInitializers(membersBuilder.InstanceInitializers, instanceInitializers) Next If Not nodeNameIsAlreadyDefined AndAlso countMissingPartial >= 2 Then ' Only check partials if no duplicate symbols were found and at least two class declarations are missing the partial keyword. For Each syntaxRef In SyntaxReferences ' Report a warning or error for all classes missing the partial modifier CheckDeclarationPart(syntaxRef.SyntaxTree, syntaxRef.GetVisualBasicSyntax(), firstNode, foundPartial, diagnostics) Next End If End Sub ' Declare all the non-type members in a single part of this type, and add them to the member list. Private Function AddMembersInPart(binder As Binder, node As VisualBasicSyntaxNode, diagBag As BindingDiagnosticBag, accessModifiers As DeclarationModifiers, members As MembersAndInitializersBuilder, ByRef staticInitializers As ArrayBuilder(Of FieldOrPropertyInitializer), ByRef instanceInitializers As ArrayBuilder(Of FieldOrPropertyInitializer), ByRef nodeNameIsAlreadyDefined As Boolean) As DeclarationModifiers Debug.Assert(diagBag.AccumulatesDiagnostics) ' Check that the node's fully qualified name is not too long and that the type name is unique. CheckDeclarationNameAndTypeParameters(node, binder, diagBag, nodeNameIsAlreadyDefined) Dim foundModifiers = CheckDeclarationModifiers(node, binder, diagBag.DiagnosticBag, accessModifiers) If TypeKind = TypeKind.Delegate Then ' add implicit delegate members (invoke, .ctor, begininvoke and endinvoke) If members.Members.Count = 0 Then Dim ctor As MethodSymbol = Nothing Dim beginInvoke As MethodSymbol = Nothing Dim endInvoke As MethodSymbol = Nothing Dim invoke As MethodSymbol = Nothing Dim parameters = DirectCast(node, DelegateStatementSyntax).ParameterList SourceDelegateMethodSymbol.MakeDelegateMembers(Me, node, parameters, binder, ctor, beginInvoke, endInvoke, invoke, diagBag) AddSymbolToMembers(ctor, members.Members) ' If this is a winmd compilation begin/endInvoke will be Nothing ' and we shouldn't add them to the symbol If beginInvoke IsNot Nothing Then AddSymbolToMembers(beginInvoke, members.Members) End If If endInvoke IsNot Nothing Then AddSymbolToMembers(endInvoke, members.Members) End If ' Invoke must always be the last member AddSymbolToMembers(invoke, members.Members) Else Debug.Assert(members.Members.Count = 4) End If ElseIf TypeKind = TypeKind.Enum Then Dim enumBlock = DirectCast(node, EnumBlockSyntax) AddEnumMembers(enumBlock, binder, diagBag, members) Else Dim typeBlock = DirectCast(node, TypeBlockSyntax) For Each memberSyntax In typeBlock.Members AddMember(memberSyntax, binder, diagBag, members, staticInitializers, instanceInitializers, reportAsInvalid:=False) Next End If Return foundModifiers End Function Private Function CheckDeclarationModifiers(node As VisualBasicSyntaxNode, binder As Binder, diagBag As DiagnosticBag, accessModifiers As DeclarationModifiers) As DeclarationModifiers Dim modifiers As SyntaxTokenList = Nothing Dim id As SyntaxToken = Nothing Dim foundModifiers = DecodeDeclarationModifiers(node, binder, diagBag, modifiers, id) If accessModifiers <> Nothing Then Dim newModifiers = foundModifiers And DeclarationModifiers.AllAccessibilityModifiers And Not accessModifiers ' Specified access '|1' for '|2' does not match the access '|3' specified on one of its other partial types. If newModifiers <> 0 Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_PartialTypeAccessMismatch3, newModifiers.ToAccessibility().ToDisplay(), id.ToString(), accessModifiers.ToAccessibility().ToDisplay()) End If End If If Me.IsNotInheritable Then ' 'MustInherit' cannot be specified for partial type '|1' because it cannot be combined with 'NotInheritable' ' specified for one of its other partial types. If (foundModifiers And DeclarationModifiers.MustInherit) <> 0 Then ' Generate error #30926 only if this (partial) declaration does not have both MustInherit and ' NotInheritable (in which case #31408 error must have been generated which should be enough in this ' case). If (foundModifiers And DeclarationModifiers.NotInheritable) = 0 Then ' Note: in case one partial declaration has both MustInherit & NotInheritable and other partial ' declarations have MustInherit, #31408 will be generated for the first one and #30926 for all ' others with MustInherit Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_PartialTypeBadMustInherit1, id.ToString()) End If End If End If Dim containingType = TryCast(Me.ContainingType, SourceNamedTypeSymbol) ' IsNested means this is in a Class or Module or Structure Dim isNested = containingType IsNot Nothing AndAlso Not containingType.IsNamespace If isNested Then Select Case containingType.DeclarationKind Case VisualBasic.Symbols.DeclarationKind.Module If (foundModifiers And DeclarationModifiers.InvalidInModule) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_ModuleCantUseTypeSpecifier1, diagBag, InvalidModifiersInModule) foundModifiers = (foundModifiers And (Not DeclarationModifiers.InvalidInModule)) End If Case VisualBasic.Symbols.DeclarationKind.Interface If (foundModifiers And DeclarationModifiers.InvalidInInterface) <> 0 Then Dim err As ERRID = ERRID.ERR_None Select Case Me.DeclarationKind Case VisualBasic.Symbols.DeclarationKind.Class err = ERRID.ERR_BadInterfaceClassSpecifier1 Case VisualBasic.Symbols.DeclarationKind.Delegate err = ERRID.ERR_BadInterfaceDelegateSpecifier1 Case VisualBasic.Symbols.DeclarationKind.Structure err = ERRID.ERR_BadInterfaceStructSpecifier1 Case VisualBasic.Symbols.DeclarationKind.Enum err = ERRID.ERR_BadInterfaceEnumSpecifier1 Case VisualBasic.Symbols.DeclarationKind.Interface ' For whatever reason, Dev10 does not report an error on [Friend] or [Public] modifier on an interface inside an interface. ' Need to handle this specially Dim invalidModifiers = DeclarationModifiers.InvalidInInterface And (Not (DeclarationModifiers.Friend Or DeclarationModifiers.Public)) If (foundModifiers And invalidModifiers) <> 0 Then binder.ReportModifierError(modifiers, ERRID.ERR_BadInterfaceInterfaceSpecifier1, diagBag, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SharedKeyword) foundModifiers = (foundModifiers And (Not invalidModifiers)) End If End Select If err <> ERRID.ERR_None Then binder.ReportModifierError(modifiers, err, diagBag, SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.FriendKeyword, SyntaxKind.PublicKeyword, SyntaxKind.SharedKeyword) foundModifiers = (foundModifiers And (Not DeclarationModifiers.InvalidInInterface)) End If End If End Select Else If (foundModifiers And DeclarationModifiers.Private) <> 0 Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_PrivateTypeOutsideType) End If If (foundModifiers And DeclarationModifiers.Shadows) <> 0 Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_ShadowingTypeOutsideClass1, id.ToString()) foundModifiers = (foundModifiers And (Not DeclarationModifiers.Shadows)) End If End If ' Only nested type (not nested in a struct, nested in a class, etc. ) can be Protected. If (foundModifiers And DeclarationModifiers.Protected) <> 0 AndAlso (Not isNested OrElse containingType.DeclarationKind <> VisualBasic.Symbols.DeclarationKind.Class) Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_ProtectedTypeOutsideClass) foundModifiers = (foundModifiers And (Not DeclarationModifiers.Protected)) End If Return foundModifiers End Function Private Function DecodeDeclarationModifiers(node As VisualBasicSyntaxNode, binder As Binder, diagBag As DiagnosticBag, ByRef modifiers As SyntaxTokenList, ByRef id As SyntaxToken) As DeclarationModifiers Dim allowableModifiers = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Shadows Dim err = ERRID.ERR_None Dim typeBlock As TypeBlockSyntax Select Case node.Kind Case SyntaxKind.ModuleBlock err = ERRID.ERR_BadModuleFlags1 allowableModifiers = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Partial typeBlock = DirectCast(node, TypeBlockSyntax) modifiers = typeBlock.BlockStatement.Modifiers id = typeBlock.BlockStatement.Identifier Case SyntaxKind.ClassBlock err = ERRID.ERR_BadClassFlags1 allowableModifiers = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Shadows Or SourceMemberFlags.MustInherit Or SourceMemberFlags.NotInheritable Or SourceMemberFlags.Partial typeBlock = DirectCast(node, TypeBlockSyntax) modifiers = typeBlock.BlockStatement.Modifiers id = typeBlock.BlockStatement.Identifier Case SyntaxKind.StructureBlock err = ERRID.ERR_BadRecordFlags1 allowableModifiers = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Shadows Or SourceMemberFlags.Partial typeBlock = DirectCast(node, TypeBlockSyntax) modifiers = typeBlock.BlockStatement.Modifiers id = typeBlock.BlockStatement.Identifier Case SyntaxKind.InterfaceBlock err = ERRID.ERR_BadInterfaceFlags1 allowableModifiers = SourceMemberFlags.AllAccessibilityModifiers Or SourceMemberFlags.Shadows Or SourceMemberFlags.Partial typeBlock = DirectCast(node, TypeBlockSyntax) modifiers = typeBlock.BlockStatement.Modifiers id = typeBlock.BlockStatement.Identifier Case SyntaxKind.EnumBlock err = ERRID.ERR_BadEnumFlags1 Dim enumBlock As EnumBlockSyntax = DirectCast(node, EnumBlockSyntax) modifiers = enumBlock.EnumStatement.Modifiers id = enumBlock.EnumStatement.Identifier Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement err = ERRID.ERR_BadDelegateFlags1 modifiers = DirectCast(node, DelegateStatementSyntax).Modifiers id = DirectCast(node, DelegateStatementSyntax).Identifier Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select If modifiers.Count <> 0 Then Dim foundFlags As SourceMemberFlags = binder.DecodeModifiers(modifiers, allowableModifiers, err, Nothing, diagBag).FoundFlags Return CType((foundFlags And SourceMemberFlags.DeclarationModifierFlagMask) >> SourceMemberFlags.DeclarationModifierFlagShift, DeclarationModifiers) End If Return Nothing End Function Private Sub CheckDeclarationNameAndTypeParameters(node As VisualBasicSyntaxNode, binder As Binder, diagBag As BindingDiagnosticBag, ByRef nodeNameIsAlreadyDeclared As Boolean) ' Check that the node's fully qualified name is not too long. Only check declarations that create types. Dim id As SyntaxToken = GetTypeIdentifierToken(node) Binder.DisallowTypeCharacter(id, diagBag) Dim thisTypeIsEmbedded As Boolean = Me.IsEmbedded ' Check name for duplicate type declarations in this container Dim container = TryCast(Me.ContainingSymbol, NamespaceOrTypeSymbol) If container IsNot Nothing Then ' Get all type or namespace symbols with this name. Dim symbols As ImmutableArray(Of Symbol) If container.IsNamespace Then symbols = container.GetMembers(Me.Name) Else symbols = StaticCast(Of Symbol).From(container.GetTypeMembers(Me.Name)) End If Dim arity As Integer = Me.Arity For Each s In symbols If s IsNot Me Then Dim _3rdArg As Object Select Case s.Kind Case SymbolKind.Namespace If arity > 0 Then Continue For End If _3rdArg = DirectCast(s, NamespaceSymbol).GetKindText() Case SymbolKind.NamedType Dim contender = DirectCast(s, NamedTypeSymbol) If contender.Arity <> arity Then Continue For End If _3rdArg = contender.GetKindText() Case Else Continue For End Select If s.IsEmbedded Then ' We expect 'this' type not to be an embedded type in this ' case because otherwise it should be design time bug. Debug.Assert(Not thisTypeIsEmbedded) ' This non-embedded type conflicts with an embedded type or namespace Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_TypeClashesWithVbCoreType4, Me.GetKindText(), id.ToString, _3rdArg, s.Name) ElseIf thisTypeIsEmbedded Then ' Embedded type conflicts with non-embedded type or namespace. ' We should ignore non-embedded types in this case, as a proper ' diagnostic will be reported when the non-embedded type is processed. If s.Kind = SymbolKind.Namespace Then ' But we should report errors on the first namespace locations Dim errorReported As Boolean = False For Each location In s.Locations If location.IsInSource AndAlso Not DirectCast(location.SourceTree, VisualBasicSyntaxTree).IsEmbeddedSyntaxTree Then Binder.ReportDiagnostic(diagBag, location, ERRID.ERR_TypeClashesWithVbCoreType4, _3rdArg, s.Name, Me.GetKindText(), id.ToString) errorReported = True Exit For End If Next If errorReported Then Exit For End If End If Continue For ' continue analysis of the type if no errors were reported Else ' Neither of types is embedded. If (Me.ContainingType Is Nothing OrElse container.Locations.Length = 1 OrElse Not (TypeOf container Is SourceMemberContainerTypeSymbol) OrElse CType(container, SourceMemberContainerTypeSymbol).IsPartial) Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_TypeConflict6, Me.GetKindText(), id.ToString, _3rdArg, s.Name, container.GetKindText(), Me.ContainingSymbol.ToErrorMessageArgument(ERRID.ERR_TypeConflict6)) End If End If nodeNameIsAlreadyDeclared = True Exit For End If Next If Not nodeNameIsAlreadyDeclared AndAlso container.IsNamespace AndAlso Me.ContainingAssembly.Modules.Length > 1 Then ' Check for collision with types from added modules Dim containingNamespace = DirectCast(container, NamespaceSymbol) Dim mergedAssemblyNamespace = TryCast(Me.ContainingAssembly.GetAssemblyNamespace(containingNamespace), MergedNamespaceSymbol) If mergedAssemblyNamespace IsNot Nothing Then Dim targetQualifiedNamespaceName As String = If(Me.GetEmittedNamespaceName(), containingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)) Dim collision As NamedTypeSymbol = Nothing For Each constituent As NamespaceSymbol In mergedAssemblyNamespace.ConstituentNamespaces If constituent Is container Then Continue For End If If collision IsNot Nothing AndAlso collision.ContainingModule.Ordinal < constituent.ContainingModule.Ordinal Then Continue For End If Dim contenders As ImmutableArray(Of NamedTypeSymbol) = constituent.GetTypeMembers(Me.Name, arity) If contenders.Length = 0 Then Continue For End If Dim constituentQualifiedName As String = constituent.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) For Each namedType In contenders If namedType.DeclaredAccessibility = Accessibility.Public AndAlso namedType.MangleName = Me.MangleName Then ' Because namespaces are merged case-insensitively, ' we need to make sure that we have a match for ' full emitted name of the type. If String.Equals(Me.Name, namedType.Name, StringComparison.Ordinal) AndAlso String.Equals(targetQualifiedNamespaceName, If(namedType.GetEmittedNamespaceName(), constituentQualifiedName), StringComparison.Ordinal) Then collision = namedType Exit For End If End If Next Next If collision IsNot Nothing Then Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_CollisionWithPublicTypeInModule, Me, collision.ContainingModule) End If End If End If End If ' Check name against type parameters of immediate container Dim containingSourceType = TryCast(container, SourceNamedTypeSymbol) If containingSourceType IsNot Nothing AndAlso containingSourceType.TypeParameters.MatchesAnyName(Me.Name) Then ' "'|1' has the same name as a type parameter." Binder.ReportDiagnostic(diagBag, id, ERRID.ERR_ShadowingGenericParamWithMember1, Me.Name) End If ' Check the source symbol type parameters for duplicates and shadowing CheckForDuplicateTypeParameters(TypeParameters, diagBag) End Sub Private Sub CheckDeclarationPart(tree As SyntaxTree, node As VisualBasicSyntaxNode, firstNode As VisualBasicSyntaxNode, foundPartial As Boolean, diagBag As BindingDiagnosticBag) ' No error or warning on the first declaration If node Is firstNode Then Return End If ' Set up a binder for this part of the type. Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, tree, Me) ' all type declarations are treated as possible partial types. Because these type have different base classes ' we need to get the modifiers in different ways. ' class, interface, struct and module all are all derived from TypeBlockSyntax. ' delegate is derived from MethodBase Dim modifiers As SyntaxTokenList = Nothing Select Case node.Kind Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement modifiers = DirectCast(node, DelegateStatementSyntax).Modifiers Case SyntaxKind.EnumBlock modifiers = DirectCast(node, EnumBlockSyntax).EnumStatement.Modifiers Case SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock modifiers = DirectCast(node, TypeBlockSyntax).BlockStatement.Modifiers Case Else Throw ExceptionUtilities.UnexpectedValue(node.Kind) End Select Dim id As SyntaxToken = Nothing ' because this method was called before, we will pass a new (unused) instance of ' diagnostics to avoid duplicate error messages for the same nodes Dim unusedDiagnostics = DiagnosticBag.GetInstance() Dim foundModifiers = DecodeDeclarationModifiers(node, binder, unusedDiagnostics, modifiers, id) unusedDiagnostics.Free() If (foundModifiers And DeclarationModifiers.Partial) = 0 Then Dim errorCode = If(foundPartial, ERRID.WRN_TypeConflictButMerged6, ERRID.ERR_TypeConflict6) ' Ensure multiple class declarations all have partial. Report a warning if more than 2 declarations are missing partial. ' VB allows one class declaration with partial and one declaration without partial because designer generated code ' may not have specified partial. This allows user-code to force it. However, VB does not allow more than one declaration ' to not have partial as this would (erroneously) make what would have been a error (duplicate declarations) compile. Dim _6thArg As Object = Me.ContainingSymbol.ToErrorMessageArgument(errorCode) Dim identifier As String = GetTypeIdentifierToken(firstNode).ToString Dim nodeKindText = Me.GetKindText() Binder.ReportDiagnostic(diagBag, id, errorCode, nodeKindText, id.ToString, nodeKindText, identifier, Me.ContainingSymbol.GetKindText(), _6thArg) End If End Sub Private Sub AddEnumMembers(syntax As EnumBlockSyntax, bodyBinder As Binder, diagnostics As BindingDiagnosticBag, members As MembersAndInitializersBuilder) Dim valField = New SynthesizedFieldSymbol( Me, Me, Me.EnumUnderlyingType, WellKnownMemberNames.EnumBackingFieldName, accessibility:=Accessibility.Public, isSpecialNameAndRuntimeSpecial:=True) AddMember(valField, bodyBinder, members, omitDiagnostics:=False) ' The previous enum constant used to calculate subsequent ' implicit enum constants. (This is the most recent explicit ' enum constant or the first implicit constant if no explicit values.) Dim otherSymbol As SourceEnumConstantSymbol = Nothing ' Offset from "otherSymbol". Dim otherSymbolOffset As Integer = 0 If syntax.Members.Count = 0 Then Binder.ReportDiagnostic(diagnostics, syntax.EnumStatement.Identifier, ERRID.ERR_BadEmptyEnum1, syntax.EnumStatement.Identifier.ValueText) Return End If For Each member In syntax.Members If member.Kind <> SyntaxKind.EnumMemberDeclaration Then ' skip invalid syntax Continue For End If Dim declaration = DirectCast(member, EnumMemberDeclarationSyntax) Dim symbol As SourceEnumConstantSymbol Dim valueOpt = declaration.Initializer If valueOpt IsNot Nothing Then symbol = SourceEnumConstantSymbol.CreateExplicitValuedConstant(Me, bodyBinder, declaration, diagnostics) Else symbol = SourceEnumConstantSymbol.CreateImplicitValuedConstant(Me, bodyBinder, declaration, otherSymbol, otherSymbolOffset, diagnostics) End If If (valueOpt IsNot Nothing) OrElse (otherSymbol Is Nothing) Then otherSymbol = symbol otherSymbolOffset = 1 Else otherSymbolOffset = otherSymbolOffset + 1 End If AddMember(symbol, bodyBinder, members, omitDiagnostics:=False) Next End Sub #End Region #Region "Type Parameters (phase 3)" Private Structure TypeParameterInfo Public Sub New( variance As VarianceKind, constraints As ImmutableArray(Of TypeParameterConstraint)) Me.Variance = variance Me.Constraints = constraints End Sub Public ReadOnly Variance As VarianceKind Public ReadOnly Constraints As ImmutableArray(Of TypeParameterConstraint) Public ReadOnly Property Initialized As Boolean Get Return Not Me.Constraints.IsDefault End Get End Property End Structure Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get If _lazyTypeParameters.IsDefault Then ImmutableInterlocked.InterlockedInitialize(_lazyTypeParameters, MakeTypeParameters()) End If Return _lazyTypeParameters End Get End Property ''' <summary> ''' Bind the constraint declarations for the given type parameter. ''' </summary> ''' <remarks> ''' The caller is expected to handle constraint checking and any caching of results. ''' </remarks> Friend Sub BindTypeParameterConstraints( typeParameter As SourceTypeParameterOnTypeSymbol, <Out()> ByRef variance As VarianceKind, <Out()> ByRef constraints As ImmutableArray(Of TypeParameterConstraint), diagnostics As BindingDiagnosticBag) Dim unused = GetTypeMembersDictionary() ' forced nested types to be declared. Dim info As TypeParameterInfo = Nothing ' Go through all declarations, determining the type parameter information ' from each, and updating the type parameter and reporting errors. For Each syntaxRef In SyntaxReferences Dim tree = syntaxRef.SyntaxTree Dim syntaxNode = syntaxRef.GetVisualBasicSyntax() Dim allowVariance = False Select Case syntaxNode.Kind Case SyntaxKind.InterfaceBlock, SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement allowVariance = True End Select Dim typeParameterList = GetTypeParameterListSyntax(syntaxNode) CreateTypeParameterInfoInPart(tree, typeParameter, typeParameterList, allowVariance, info, diagnostics) Next Debug.Assert(info.Initialized) variance = info.Variance constraints = info.Constraints End Sub ' Create all the type parameter information from the given declaration. Private Sub CreateTypeParameterInfoInPart(tree As SyntaxTree, typeParameter As SourceTypeParameterOnTypeSymbol, typeParamListSyntax As TypeParameterListSyntax, allowVarianceSpecifier As Boolean, ByRef info As TypeParameterInfo, diagBag As BindingDiagnosticBag) Debug.Assert(typeParamListSyntax IsNot Nothing) Debug.Assert(typeParamListSyntax.Parameters.Count = Me.Arity) ' If this is false, something is really wrong with the declaration tree. ' Set up a binder for this part of the type. Dim binder As Binder = CreateLocationSpecificBinderForType(tree, BindingLocation.GenericConstraintsClause) Dim typeParamSyntax = typeParamListSyntax.Parameters(typeParameter.Ordinal) ' Handle type parameter identifier. Dim identSymbol = typeParamSyntax.Identifier Binder.DisallowTypeCharacter(identSymbol, diagBag, ERRID.ERR_TypeCharOnGenericParam) Dim name As String = identSymbol.ValueText ' Handle type parameter variance. Dim varianceKeyword = typeParamSyntax.VarianceKeyword Dim variance As VarianceKind = VarianceKind.None If varianceKeyword.Kind <> SyntaxKind.None Then If allowVarianceSpecifier Then variance = Binder.DecodeVariance(varianceKeyword) Else Binder.ReportDiagnostic(diagBag, varianceKeyword, ERRID.ERR_VarianceDisallowedHere) End If End If ' Handle constraints. Dim constraints = binder.BindTypeParameterConstraintClause(Me, typeParamSyntax.TypeParameterConstraintClause, diagBag) If info.Initialized Then If Not IdentifierComparison.Equals(typeParameter.Name, name) Then ' "Type parameter name '{0}' does not match the name '{1}' of the corresponding type parameter defined on one of the other partial types of '{2}'." Binder.ReportDiagnostic(diagBag, identSymbol, ERRID.ERR_PartialTypeTypeParamNameMismatch3, name, typeParameter.Name, Me.Name) End If If Not HaveSameConstraints(info.Constraints, constraints) Then ' "Constraints for this type parameter do not match the constraints on the corresponding type parameter defined on one of the other partial types of '{0}'." Binder.ReportDiagnostic(diagBag, identSymbol, ERRID.ERR_PartialTypeConstraintMismatch1, Me.Name) End If Else info = New TypeParameterInfo(variance, constraints) End If End Sub Private Shared Function HaveSameConstraints(constraints1 As ImmutableArray(Of TypeParameterConstraint), constraints2 As ImmutableArray(Of TypeParameterConstraint)) As Boolean Dim n1 = constraints1.Length Dim n2 = constraints2.Length If n1 <> n2 Then Return False End If If (n1 = 0) AndAlso (n2 = 0) Then Return True End If If GetConstraintKind(constraints1) <> GetConstraintKind(constraints2) Then Return False End If ' Construct a HashSet<T> for one of the sets ' to allow O(n) comparison of the two sets. Dim constraintTypes1 = New HashSet(Of TypeSymbol) For Each constraint In constraints1 Dim constraintType = constraint.TypeConstraint If constraintType IsNot Nothing Then constraintTypes1.Add(constraintType) End If Next For Each constraint In constraints2 Dim constraintType = constraint.TypeConstraint If (constraintType IsNot Nothing) AndAlso Not constraintTypes1.Contains(constraintType) Then Return False End If Next Return True End Function Private Shared Function GetConstraintKind(constraints As ImmutableArray(Of TypeParameterConstraint)) As TypeParameterConstraintKind Dim kind = TypeParameterConstraintKind.None For Each constraint In constraints kind = kind Or constraint.Kind Next Return kind End Function Private Function MakeTypeParameters() As ImmutableArray(Of TypeParameterSymbol) Dim n = TypeDeclaration.Arity If n = 0 Then Return ImmutableArray(Of TypeParameterSymbol).Empty End If Dim typeParameters(0 To n - 1) As TypeParameterSymbol For i = 0 To n - 1 Dim syntaxRefBuilder = ArrayBuilder(Of SyntaxReference).GetInstance() Dim name As String = Nothing For Each syntaxRef In SyntaxReferences Dim tree = syntaxRef.SyntaxTree Dim syntaxNode = syntaxRef.GetVisualBasicSyntax() Dim typeParamListSyntax = GetTypeParameterListSyntax(syntaxNode).Parameters Debug.Assert(typeParamListSyntax.Count = n) Dim typeParamSyntax = typeParamListSyntax(i) If name Is Nothing Then name = typeParamSyntax.Identifier.ValueText End If syntaxRefBuilder.Add(tree.GetReference(typeParamSyntax)) Next Debug.Assert(name IsNot Nothing) Debug.Assert(syntaxRefBuilder.Count > 0) typeParameters(i) = New SourceTypeParameterOnTypeSymbol(Me, i, name, syntaxRefBuilder.ToImmutableAndFree()) Next Return typeParameters.AsImmutableOrNull() End Function Private Shared Function GetTypeParameterListSyntax(syntax As VisualBasicSyntaxNode) As TypeParameterListSyntax Select Case syntax.Kind Case SyntaxKind.StructureBlock, SyntaxKind.ClassBlock, SyntaxKind.InterfaceBlock Return DirectCast(syntax, TypeBlockSyntax).BlockStatement.TypeParameterList Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(syntax, DelegateStatementSyntax).TypeParameterList Case Else Return Nothing End Select End Function Friend Sub CheckForDuplicateTypeParameters(typeParameters As ImmutableArray(Of TypeParameterSymbol), diagBag As BindingDiagnosticBag) If Not typeParameters.IsDefault Then Dim typeParameterSet As New HashSet(Of String)(IdentifierComparison.Comparer) ' Check for duplicate type parameters For i = 0 To typeParameters.Length - 1 Dim s = typeParameters(i) If Not typeParameterSet.Contains(s.Name) Then typeParameterSet.Add(s.Name) If ShadowsTypeParameter(s) Then Binder.ReportDiagnostic(diagBag, s.Locations(0), ERRID.WRN_ShadowingGenericParamWithParam1, s.Name) End If Else Binder.ReportDiagnostic(diagBag, s.Locations(0), ERRID.ERR_DuplicateTypeParamName1, s.Name) End If Next End If End Sub Private Function ShadowsTypeParameter(typeParameter As TypeParameterSymbol) As Boolean Dim name As String = typeParameter.Name Dim containingType As SourceNamedTypeSymbol If typeParameter.TypeParameterKind = TypeParameterKind.Method Then containingType = Me Else containingType = TryCast(Me.ContainingType, SourceNamedTypeSymbol) End If While containingType IsNot Nothing If containingType.TypeParameters.MatchesAnyName(name) Then Return True End If containingType = TryCast(containingType.ContainingType, SourceNamedTypeSymbol) End While Return False End Function #End Region #Region "Base Type and Interfaces (phase 4)" Private Sub MakeDeclaredBaseInPart(tree As SyntaxTree, syntaxNode As VisualBasicSyntaxNode, ByRef baseType As NamedTypeSymbol, basesBeingResolved As BasesBeingResolved, diagBag As BindingDiagnosticBag) ' Set up a binder for this part of the type. Dim binder As Binder = CreateLocationSpecificBinderForType(tree, BindingLocation.BaseTypes) Select Case syntaxNode.Kind Case SyntaxKind.ClassBlock Dim inheritsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Inherits ' classes may have a base class Dim thisBase As NamedTypeSymbol = ValidateClassBase(inheritsSyntax, baseType, basesBeingResolved, binder, diagBag) If baseType Is Nothing Then baseType = thisBase End If Case SyntaxKind.StructureBlock Dim inheritsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Inherits CheckNoBase(inheritsSyntax, ERRID.ERR_StructCantInherit, diagBag) Case SyntaxKind.ModuleBlock Dim inheritsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Inherits CheckNoBase(inheritsSyntax, ERRID.ERR_ModuleCantInherit, diagBag) End Select End Sub Private Sub MakeDeclaredInterfacesInPart(tree As SyntaxTree, syntaxNode As VisualBasicSyntaxNode, interfaces As SetWithInsertionOrder(Of NamedTypeSymbol), basesBeingResolved As BasesBeingResolved, diagBag As BindingDiagnosticBag) ' Set up a binder for this part of the type. Dim binder As Binder = CreateLocationSpecificBinderForType(tree, BindingLocation.BaseTypes) Select Case syntaxNode.Kind Case SyntaxKind.ClassBlock Dim implementsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Implements ' class may implement interfaces ValidateImplementedInterfaces(implementsSyntax, interfaces, basesBeingResolved, binder, diagBag) Case SyntaxKind.StructureBlock Dim implementsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Implements ' struct may implement interfaces ValidateImplementedInterfaces(implementsSyntax, interfaces, basesBeingResolved, binder, diagBag) Case SyntaxKind.InterfaceBlock Dim implementsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Inherits ' interface may inherit interfaces ValidateInheritedInterfaces(implementsSyntax, interfaces, basesBeingResolved, binder, diagBag) Case SyntaxKind.ModuleBlock Dim implementsSyntax = DirectCast(syntaxNode, TypeBlockSyntax).Implements CheckNoBase(implementsSyntax, ERRID.ERR_ModuleCantImplement, diagBag) End Select End Sub ' Check that there are no base declarations in the given list, and report the given error if any are found. Private Sub CheckNoBase(Of T As InheritsOrImplementsStatementSyntax)(baseDeclList As SyntaxList(Of T), errId As ERRID, diagBag As BindingDiagnosticBag) If baseDeclList.Count > 0 Then For Each baseDecl In baseDeclList Binder.ReportDiagnostic(diagBag, baseDecl, errId) Next End If End Sub ' Validate the base class declared by a class, diagnosing errors. ' If a base class is found already in another partial, it is passed as baseInOtherPartial. ' Returns the base class if a good base class was found, otherwise Nothing. Private Function ValidateClassBase(inheritsSyntax As SyntaxList(Of InheritsStatementSyntax), baseInOtherPartial As NamedTypeSymbol, basesBeingResolved As BasesBeingResolved, binder As Binder, diagBag As BindingDiagnosticBag) As NamedTypeSymbol If inheritsSyntax.Count = 0 Then Return Nothing ' Add myself to the set of classes whose bases are being resolved basesBeingResolved = basesBeingResolved.PrependInheritsBeingResolved(Me) binder = New BasesBeingResolvedBinder(binder, basesBeingResolved) ' Get the first base class declared, and give errors for multiple base classes Dim baseClassSyntax As TypeSyntax = Nothing For Each baseDeclaration In inheritsSyntax If baseDeclaration.Kind = SyntaxKind.InheritsStatement Then Dim inheritsDeclaration = DirectCast(baseDeclaration, InheritsStatementSyntax) If baseClassSyntax IsNot Nothing OrElse inheritsDeclaration.Types.Count > 1 Then Binder.ReportDiagnostic(diagBag, inheritsDeclaration, ERRID.ERR_MultipleExtends) End If If baseClassSyntax Is Nothing AndAlso inheritsDeclaration.Types.Count > 0 Then baseClassSyntax = inheritsDeclaration.Types(0) End If End If Next If baseClassSyntax Is Nothing Then Return Nothing End If ' Bind the base class. Dim baseClassType = binder.BindTypeSyntax(baseClassSyntax, diagBag, suppressUseSiteError:=True, resolvingBaseType:=True) If baseClassType Is Nothing Then Return Nothing End If ' Check to make sure the base class is valid. Dim diagInfo As DiagnosticInfo = Nothing Select Case baseClassType.TypeKind Case TypeKind.TypeParameter Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_GenericParamBase2, "Class", Me.Name) Return Nothing Case TypeKind.Interface, TypeKind.Enum, TypeKind.Delegate, TypeKind.Structure, TypeKind.Module, TypeKind.Array ' array can't really occur Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_InheritsFromNonClass) Return Nothing Case TypeKind.Error, TypeKind.Unknown Return DirectCast(baseClassType, NamedTypeSymbol) Case TypeKind.Class If IsRestrictedBaseClass(baseClassType.SpecialType) Then Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_InheritsFromRestrictedType1, baseClassType) Return Nothing ElseIf DirectCast(baseClassType, NamedTypeSymbol).IsNotInheritable Then Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_InheritsFromCantInherit3, Me.Name, baseClassType.Name, baseClassType.GetKindText()) Return Nothing End If End Select ' The same base class can be declared in multiple partials, but not different ones If baseInOtherPartial IsNot Nothing Then If Not baseClassType.Equals(baseInOtherPartial) Then Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_BaseMismatchForPartialClass3, baseClassType, Me.Name, baseInOtherPartial) Return Nothing End If ElseIf Not baseClassType.IsErrorType() Then ' Verify that we don't have public classes inheriting from private ones, etc. AccessCheck.VerifyAccessExposureOfBaseClassOrInterface(Me, baseClassSyntax, baseClassType, diagBag) End If Return DirectCast(baseClassType, NamedTypeSymbol) End Function Private Sub ValidateInheritedInterfaces(baseSyntax As SyntaxList(Of InheritsStatementSyntax), basesInOtherPartials As SetWithInsertionOrder(Of NamedTypeSymbol), basesBeingResolved As BasesBeingResolved, binder As Binder, diagBag As BindingDiagnosticBag) If baseSyntax.Count = 0 Then Return ' Add myself to the set of classes whose bases are being resolved basesBeingResolved = basesBeingResolved.PrependInheritsBeingResolved(Me) binder = New BasesBeingResolvedBinder(binder, basesBeingResolved) ' give errors for multiple base classes Dim interfacesInThisPartial As New HashSet(Of NamedTypeSymbol)() For Each baseDeclaration In baseSyntax Dim types = DirectCast(baseDeclaration, InheritsStatementSyntax).Types For Each baseClassSyntax In types Dim typeSymbol = binder.BindTypeSyntax(baseClassSyntax, diagBag, suppressUseSiteError:=True) Dim namedType = TryCast(typeSymbol, NamedTypeSymbol) If namedType IsNot Nothing AndAlso interfacesInThisPartial.Contains(namedType) Then Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_DuplicateInInherits1, typeSymbol) Else If namedType IsNot Nothing Then interfacesInThisPartial.Add(namedType) End If ' Check to make sure the base interfaces are valid. Select Case typeSymbol.TypeKind Case TypeKind.TypeParameter Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_GenericParamBase2, "Interface", Me.Name) Continue For Case TypeKind.Unknown Continue For Case TypeKind.Interface, TypeKind.Error basesInOtherPartials.Add(namedType) If Not typeSymbol.IsErrorType() Then ' Make sure that we aren't exposing an interface with a restricted type, ' e.g. a public interface can't inherit from a private interface AccessCheck.VerifyAccessExposureOfBaseClassOrInterface(Me, baseClassSyntax, typeSymbol, diagBag) End If Case Else Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_InheritsFromNonInterface) Continue For End Select End If Next Next End Sub Private Sub ValidateImplementedInterfaces(baseSyntax As SyntaxList(Of ImplementsStatementSyntax), basesInOtherPartials As SetWithInsertionOrder(Of NamedTypeSymbol), basesBeingResolved As BasesBeingResolved, binder As Binder, diagBag As BindingDiagnosticBag) If baseSyntax.Count = 0 Then Return ' Add myself to the set of classes whose implemented interfaces are being resolved basesBeingResolved = basesBeingResolved.PrependImplementsBeingResolved(Me) binder = New BasesBeingResolvedBinder(binder, basesBeingResolved) ' give errors for multiple base classes Dim interfacesInThisPartial As New HashSet(Of TypeSymbol)() For Each baseDeclaration In baseSyntax Dim types = DirectCast(baseDeclaration, ImplementsStatementSyntax).Types For Each baseClassSyntax In types Dim typeSymbol = binder.BindTypeSyntax(baseClassSyntax, diagBag, suppressUseSiteError:=True) If Not interfacesInThisPartial.Add(typeSymbol) Then Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_InterfaceImplementedTwice1, typeSymbol) Else ' Check to make sure the base interfaces are valid. Select Case typeSymbol.TypeKind Case TypeKind.TypeParameter Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_ImplementsGenericParam, "Interface", Me.Name) Continue For Case TypeKind.Unknown Continue For Case TypeKind.Interface, TypeKind.Error basesInOtherPartials.Add(DirectCast(typeSymbol, NamedTypeSymbol)) Case Else Binder.ReportDiagnostic(diagBag, baseClassSyntax, ERRID.ERR_BadImplementsType) Continue For End Select End If Next Next End Sub ' Determines if this type is one of the special types we can't inherit from Private Function IsRestrictedBaseClass(type As SpecialType) As Boolean Select Case type Case SpecialType.System_Array, SpecialType.System_Delegate, SpecialType.System_MulticastDelegate, SpecialType.System_Enum, SpecialType.System_ValueType Return True Case Else Return False End Select End Function Private Function AsPeOrRetargetingType(potentialBaseType As TypeSymbol) As NamedTypeSymbol Dim peType As NamedTypeSymbol = TryCast(potentialBaseType, Symbols.Metadata.PE.PENamedTypeSymbol) If peType Is Nothing Then peType = TryCast(potentialBaseType, Retargeting.RetargetingNamedTypeSymbol) End If Return peType End Function Friend Overrides Function MakeDeclaredBase(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol ' For types nested in a source type symbol (not in a script class): ' before resolving the base type ensure that enclosing type's base type is already resolved Dim containingSourceType = TryCast(ContainingSymbol, SourceNamedTypeSymbol) If containingSourceType IsNot Nothing Then containingSourceType.GetDeclaredBaseSafe(basesBeingResolved.PrependInheritsBeingResolved(Me)) End If Dim baseType As NamedTypeSymbol = Nothing ' Go through all the parts of this type, and declare the information in that part, ' reporting errors appropriately. For Each decl In Me.TypeDeclaration.Declarations If decl.HasBaseDeclarations Then Dim syntaxRef = decl.SyntaxReference MakeDeclaredBaseInPart(syntaxRef.SyntaxTree, syntaxRef.GetVisualBasicSyntax(), baseType, basesBeingResolved, diagnostics) End If Next Return baseType End Function Friend Overrides Function MakeDeclaredInterfaces(basesBeingResolved As BasesBeingResolved, diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) ' For types nested in a source type symbol (not in a script class): ' before resolving the base type ensure that enclosing type's base type is already resolved Dim containingSourceType = TryCast(ContainingSymbol, SourceNamedTypeSymbol) If Me.IsInterface AndAlso containingSourceType IsNot Nothing AndAlso containingSourceType.IsInterface Then containingSourceType.GetDeclaredBaseInterfacesSafe(basesBeingResolved.PrependInheritsBeingResolved(Me)) End If Dim interfaces As New SetWithInsertionOrder(Of NamedTypeSymbol) ' Go through all the parts of this type, and declare the information in that part, ' reporting errors appropriately. For Each syntaxRef In SyntaxReferences MakeDeclaredInterfacesInPart(syntaxRef.SyntaxTree, syntaxRef.GetVisualBasicSyntax(), interfaces, basesBeingResolved, diagnostics) Next Return interfaces.AsImmutable End Function Private Function GetInheritsLocation(base As NamedTypeSymbol) As Location Return GetInheritsOrImplementsLocation(base, True) End Function Protected Overrides Function GetInheritsOrImplementsLocation(base As NamedTypeSymbol, getInherits As Boolean) As Location Dim backupLocation As Location = Nothing For Each part In SyntaxReferences Dim typeBlock = DirectCast(part.GetSyntax(), TypeBlockSyntax) Dim inhDecl = If(getInherits, DirectCast(typeBlock.Inherits, IEnumerable(Of InheritsOrImplementsStatementSyntax)), DirectCast(typeBlock.Implements, IEnumerable(Of InheritsOrImplementsStatementSyntax))) Dim binder As Binder = CreateLocationSpecificBinderForType(part.SyntaxTree, BindingLocation.BaseTypes) Dim basesBeingResolved As BasesBeingResolved = Nothing If getInherits Then basesBeingResolved = basesBeingResolved.PrependInheritsBeingResolved(Me) Else basesBeingResolved = basesBeingResolved.PrependImplementsBeingResolved(Me) End If binder = New BasesBeingResolvedBinder(binder, basesBeingResolved) For Each t In inhDecl If backupLocation Is Nothing Then backupLocation = t.GetLocation() End If Dim types As SeparatedSyntaxList(Of TypeSyntax) = If(getInherits, DirectCast(t, InheritsStatementSyntax).Types, DirectCast(t, ImplementsStatementSyntax).Types) For Each typeSyntax In types Dim bt = binder.BindTypeSyntax(typeSyntax, BindingDiagnosticBag.Discarded, suppressUseSiteError:=True) If TypeSymbol.Equals(bt, base, TypeCompareKind.ConsiderEverything) Then Return typeSyntax.GetLocation() End If Next Next Next ' In recursive or circular cases, the BindTypeSyntax fails to give the same result as the circularity ' removing algorithm does. In this case, use the entire Inherits or Implements statement as the location. Return backupLocation End Function Friend Overrides Function MakeAcyclicBaseType(diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Dim compilation As VisualBasicCompilation = Me.DeclaringCompilation Dim declaredBase As NamedTypeSymbol = Me.GetDeclaredBase(Nothing) If declaredBase IsNot Nothing Then Dim diag As DiagnosticInfo = If(m_baseCycleDiagnosticInfo, BaseTypeAnalysis.GetDependenceDiagnosticForBase(Me, declaredBase)) If diag IsNot Nothing Then Dim location = GetInheritsLocation(declaredBase) ' TODO: if there is a cycle dependency in base type we might want to ignore all ' other diagnostics collected so far because they may be incorrectly generated ' because of the cycle -- check and decide if we want to do so 'diagnostics.Clear() diagnostics.Add(New VBDiagnostic(diag, location)) Return New ExtendedErrorTypeSymbol(diag, False) End If End If Dim declaredOrDefaultBase As NamedTypeSymbol = declaredBase ' Get the default base type if none was declared If declaredOrDefaultBase Is Nothing AndAlso Me.SpecialType <> Microsoft.CodeAnalysis.SpecialType.System_Object Then Select Case TypeKind Case TypeKind.Submission ' check that System.Object is available. ' Although the submission semantically doesn't have a base class we need to emit one. ReportUseSiteInfoForBaseType(Me.DeclaringCompilation.GetSpecialType(SpecialType.System_Object), declaredBase, diagnostics) declaredOrDefaultBase = Nothing Case TypeKind.Class declaredOrDefaultBase = GetSpecialType(SpecialType.System_Object) Case TypeKind.Interface declaredOrDefaultBase = Nothing Case TypeKind.Enum declaredOrDefaultBase = GetSpecialType(SpecialType.System_Enum) Case TypeKind.Structure declaredOrDefaultBase = GetSpecialType(SpecialType.System_ValueType) Case TypeKind.Delegate declaredOrDefaultBase = GetSpecialType(SpecialType.System_MulticastDelegate) Case TypeKind.Module declaredOrDefaultBase = GetSpecialType(SpecialType.System_Object) Case Else Throw ExceptionUtilities.UnexpectedValue(TypeKind) End Select End If If declaredOrDefaultBase IsNot Nothing Then ReportUseSiteInfoForBaseType(declaredOrDefaultBase, declaredBase, diagnostics) End If Return declaredOrDefaultBase End Function Private Function GetSpecialType(type As SpecialType) As NamedTypeSymbol Return ContainingModule.ContainingAssembly.GetSpecialType(type) End Function Private Sub ReportUseSiteInfoForBaseType(baseType As NamedTypeSymbol, declaredBase As NamedTypeSymbol, diagnostics As BindingDiagnosticBag) Dim useSiteInfo As New CompoundUseSiteInfo(Of AssemblySymbol)(diagnostics, ContainingAssembly) Dim current As NamedTypeSymbol = baseType Do If current.DeclaringCompilation Is Me.DeclaringCompilation Then Exit Do End If current.AddUseSiteInfo(useSiteInfo) current = current.BaseTypeNoUseSiteDiagnostics Loop While current IsNot Nothing If Not useSiteInfo.Diagnostics.IsNullOrEmpty Then Dim location As Location If declaredBase Is baseType Then location = GetInheritsLocation(baseType) Else Dim syntaxRef = SyntaxReferences.First() Dim syntax = syntaxRef.GetVisualBasicSyntax() ' script, submission and implicit classes have no identifier location: location = If(syntax.Kind = SyntaxKind.CompilationUnit OrElse syntax.Kind = SyntaxKind.NamespaceBlock, Locations(0), GetTypeIdentifierToken(syntax).GetLocation()) End If diagnostics.Add(location, useSiteInfo) Else diagnostics.AddDependencies(useSiteInfo) End If End Sub Friend Overrides Function MakeAcyclicInterfaces(diagnostics As BindingDiagnosticBag) As ImmutableArray(Of NamedTypeSymbol) Dim declaredInterfaces As ImmutableArray(Of NamedTypeSymbol) = GetDeclaredInterfacesNoUseSiteDiagnostics(Nothing) Dim isInterface As Boolean = Me.IsInterfaceType() Dim result As ArrayBuilder(Of NamedTypeSymbol) = If(isInterface, ArrayBuilder(Of NamedTypeSymbol).GetInstance(), Nothing) For Each t In declaredInterfaces Dim diag = If(isInterface AndAlso Not t.IsErrorType(), GetDependenceDiagnosticForBase(Me, t), Nothing) If diag IsNot Nothing Then Dim location = GetInheritsLocation(t) diagnostics.Add(New VBDiagnostic(diag, location)) result.Add(New ExtendedErrorTypeSymbol(diag, False)) Else ' Error types were reported elsewhere. If Not t.IsErrorType() Then Dim useSiteInfo As New CompoundUseSiteInfo(Of AssemblySymbol)(diagnostics, ContainingAssembly) If t.DeclaringCompilation IsNot Me.DeclaringCompilation Then t.AddUseSiteInfo(useSiteInfo) For Each [interface] In t.AllInterfacesNoUseSiteDiagnostics If [interface].DeclaringCompilation IsNot Me.DeclaringCompilation Then [interface].AddUseSiteInfo(useSiteInfo) End If Next End If If Not useSiteInfo.Diagnostics.IsNullOrEmpty Then Dim location = If(isInterface, GetInheritsLocation(t), GetInheritsOrImplementsLocation(t, getInherits:=False)) diagnostics.Add(location, useSiteInfo) Else diagnostics.AddDependencies(useSiteInfo) End If End If If isInterface Then result.Add(t) End If End If Next Return If(isInterface, result.ToImmutableAndFree, declaredInterfaces) End Function Friend Overrides Function GetDirectBaseTypeNoUseSiteDiagnostics(basesBeingResolved As BasesBeingResolved) As NamedTypeSymbol Debug.Assert(Me.TypeKind <> TypeKind.Interface) If TypeKind = TypeKind.Enum Then ' Base type has the underlying type instead. Return GetSpecialType(SpecialType.System_Enum) ElseIf TypeKind = TypeKind.Delegate Then ' Base type has the underlying type instead. Return GetSpecialType(SpecialType.System_MulticastDelegate) Else If basesBeingResolved.InheritsBeingResolvedOpt Is Nothing Then Return Me.BaseTypeNoUseSiteDiagnostics Else Return GetDeclaredBaseSafe(basesBeingResolved) End If End If End Function ''' <summary> ''' 'Safe' version of GetDeclaredBase takes into account bases being resolved to make sure ''' we avoid infinite loops in some scenarios. Note that the cycle is being broken not when ''' we detect it, but when we detect it on the 'smallest' type of the cycle, this brings stability ''' in multithreaded scenarios while still ensures that we don't loop more than twice. ''' </summary> Private Function GetDeclaredBaseSafe(basesBeingResolved As BasesBeingResolved) As NamedTypeSymbol If m_baseCycleDiagnosticInfo IsNot Nothing Then ' We have already detected this type has a cycle and it was chosen ' to be the one which reports the problem and breaks the cycle Return Nothing End If Debug.Assert(basesBeingResolved.InheritsBeingResolvedOpt.Any) If Me Is basesBeingResolved.InheritsBeingResolvedOpt.Head Then ' This is a little tricky: the head of 'basesBeingResolved' represents the innermost ' type whose base is being resolved. That means if we start name lookup with that type ' as containing type and if we cannot find the name in its scope we want just to skip base ' type search and avoid any errors. We want this to happen only for that innermost type ' in base resolution chain. An example: ' ' Class A ' Class B ' Inherits D ' Lookup for 'D' starts in scope of 'B', we ' Class C ' are skipping diving into B's base class here ' End Class ' to make it possible to find A.D ' End Class ' Class D ' End Class ' End Class ' NOTE: that it the lookup is not the first indirect one, but B was found earlier ' during lookup process, we still can ignore B's base type because another ' error (B cannot reference itself in its Inherits clause) should be generated ' by this time, like in the following example: ' ' Class A ' Class B ' Inherits A.B.C ' <- error BC31447: Class 'A.B' cannot ' Class C ' reference itself in Inherits clause. ' End Class ' End Class ' Class D ' End Class ' End Class Return Nothing End If Dim diag As DiagnosticInfo = GetDependenceDiagnosticForBase(Me, basesBeingResolved) If diag Is Nothing Then Dim declaredBase As NamedTypeSymbol = GetDeclaredBase(basesBeingResolved) ' If we detected the cycle while calculating the declared base, return Nothing Return If(m_baseCycleDiagnosticInfo Is Nothing, declaredBase, Nothing) End If Dim prev = Interlocked.CompareExchange(m_baseCycleDiagnosticInfo, diag, Nothing) Debug.Assert(prev Is Nothing OrElse prev.GetMessage().Equals(diag.GetMessage())) Return Nothing End Function Friend Overrides Function GetDeclaredBaseInterfacesSafe(basesBeingResolved As BasesBeingResolved) As ImmutableArray(Of NamedTypeSymbol) Debug.Assert(Me.IsInterface) If m_baseCycleDiagnosticInfo IsNot Nothing Then ' We have already detected this type has a cycle and it was chosen ' to be the one which reports the problem and breaks the cycle Return Nothing End If Debug.Assert(basesBeingResolved.InheritsBeingResolvedOpt.Any) If Me Is basesBeingResolved.InheritsBeingResolvedOpt.Head Then Return Nothing End If Dim diag As DiagnosticInfo = GetDependenceDiagnosticForBase(Me, basesBeingResolved) If diag Is Nothing Then Dim declaredBases As ImmutableArray(Of NamedTypeSymbol) = GetDeclaredInterfacesNoUseSiteDiagnostics(basesBeingResolved) ' If we detected the cycle while calculating the declared base, return Nothing Return If(m_baseCycleDiagnosticInfo Is Nothing, declaredBases, ImmutableArray(Of NamedTypeSymbol).Empty) End If Dim prev = Interlocked.CompareExchange(m_baseCycleDiagnosticInfo, diag, Nothing) Debug.Assert(prev Is Nothing OrElse prev.GetMessage().Equals(diag.GetMessage())) Return Nothing End Function ''' <summary> ''' Do additional verification of base types the after acyclic base is found. This is ''' the chance to generate diagnostics that may require walking bases and as such ''' can be performed only after the base has been determined and cycles broken. ''' (For instance, checking constraints on Class B(Of T) Inherits A(Of B(Of T)).) ''' </summary> Private Sub CheckBaseConstraints() If (m_lazyState And StateFlags.ReportedBaseClassConstraintsDiagnostics) <> 0 Then Return End If Dim diagnostics As BindingDiagnosticBag = Nothing Dim localBase = BaseTypeNoUseSiteDiagnostics If localBase IsNot Nothing Then ' Check constraints on the first declaration with explicit bases. Dim singleDeclaration = FirstDeclarationWithExplicitBases() If singleDeclaration IsNot Nothing Then Dim location = singleDeclaration.NameLocation diagnostics = BindingDiagnosticBag.GetInstance() localBase.CheckAllConstraints(location, diagnostics, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagnostics, m_containingModule.ContainingAssembly)) If IsGenericType Then ' Check that generic type does not derive from System.Attribute. ' This check must be done here instead of in ValidateClassBase to avoid infinite recursion when there are ' cycles in the inheritance chain. In Dev10/11, the error was reported on the inherited statement, now it ' is reported on the class statement. Dim useSiteInfo As New CompoundUseSiteInfo(Of AssemblySymbol)(diagnostics, m_containingModule.ContainingAssembly) Dim isBaseType As Boolean = DeclaringCompilation.GetWellKnownType(WellKnownType.System_Attribute).IsBaseTypeOf(localBase, useSiteInfo) diagnostics.Add(location, useSiteInfo) If isBaseType Then ' WARNING: in case System_Attribute was not found or has errors, the above check may ' fail to detect inheritance from System.Attribute, but we assume that in this case ' another error will be generated anyway Binder.ReportDiagnostic(diagnostics, location, ERRID.ERR_GenericClassCannotInheritAttr) End If End If End If End If m_containingModule.AtomicSetFlagAndStoreDiagnostics(m_lazyState, StateFlags.ReportedBaseClassConstraintsDiagnostics, 0, diagnostics) If diagnostics IsNot Nothing Then diagnostics.Free() End If End Sub ''' <summary> ''' Do additional verification of interfaces after acyclic interfaces are found. This is ''' the chance to generate diagnostics that may need to walk interfaces and as such ''' can be performed only after the interfaces have been determined and cycles broken. ''' (For instance, checking constraints on Class C(Of T) Implements I(Of C(Of T)).) ''' </summary> Private Sub CheckInterfacesConstraints() If (m_lazyState And StateFlags.ReportedInterfacesConstraintsDiagnostics) <> 0 Then Return End If Dim diagnostics As BindingDiagnosticBag = Nothing Dim localInterfaces = InterfacesNoUseSiteDiagnostics If Not localInterfaces.IsEmpty Then ' Check constraints on the first declaration with explicit interfaces. Dim singleDeclaration = FirstDeclarationWithExplicitInterfaces() If singleDeclaration IsNot Nothing Then Dim location = singleDeclaration.NameLocation diagnostics = BindingDiagnosticBag.GetInstance() For Each [interface] In localInterfaces [interface].CheckAllConstraints(location, diagnostics, template:=New CompoundUseSiteInfo(Of AssemblySymbol)(diagnostics, m_containingModule.ContainingAssembly)) Next End If End If If m_containingModule.AtomicSetFlagAndStoreDiagnostics(m_lazyState, StateFlags.ReportedInterfacesConstraintsDiagnostics, 0, diagnostics) Then DeclaringCompilation.SymbolDeclaredEvent(Me) End If If diagnostics IsNot Nothing Then diagnostics.Free() End If End Sub ''' <summary> ''' Return the first Class declaration with explicit base classes to use for ''' checking base class constraints. Other type declarations (Structures, ''' Modules, Interfaces) are ignored since other errors will have been ''' reported if those types include bases. ''' </summary> Private Function FirstDeclarationWithExplicitBases() As SingleTypeDeclaration For Each decl In TypeDeclaration.Declarations Dim syntaxNode = decl.SyntaxReference.GetVisualBasicSyntax() Select Case syntaxNode.Kind Case SyntaxKind.ClassBlock If DirectCast(syntaxNode, TypeBlockSyntax).Inherits.Count > 0 Then Return decl End If End Select Next Return Nothing End Function ''' <summary> ''' Return the first Class, Structure, or Interface declaration with explicit interfaces ''' to use for checking interface constraints. Other type declarations (Modules) are ''' ignored since other errors will have been reported if those types include interfaces. ''' </summary> Private Function FirstDeclarationWithExplicitInterfaces() As SingleTypeDeclaration For Each decl In TypeDeclaration.Declarations Dim syntaxNode = decl.SyntaxReference.GetVisualBasicSyntax() Select Case syntaxNode.Kind Case SyntaxKind.ClassBlock, SyntaxKind.StructureBlock If DirectCast(syntaxNode, TypeBlockSyntax).Implements.Count > 0 Then Return decl End If Case SyntaxKind.InterfaceBlock If DirectCast(syntaxNode, TypeBlockSyntax).Inherits.Count > 0 Then Return decl End If End Select Next Return Nothing End Function #End Region #Region "Enums" ''' <summary> ''' For enum types, gets the underlying type. Returns null on all other ''' kinds of types. ''' </summary> Public Overrides ReadOnly Property EnumUnderlyingType As NamedTypeSymbol Get If Not Me.IsEnumType Then Return Nothing End If Dim underlyingType = Me._lazyEnumUnderlyingType If underlyingType Is Nothing Then Dim tempDiags = BindingDiagnosticBag.GetInstance Dim blockRef = SyntaxReferences(0) Dim tree = blockRef.SyntaxTree Dim syntax = DirectCast(blockRef.GetSyntax, EnumBlockSyntax) Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, tree, Me) underlyingType = BindEnumUnderlyingType(syntax, binder, tempDiags) If Interlocked.CompareExchange(Me._lazyEnumUnderlyingType, underlyingType, Nothing) Is Nothing Then ContainingSourceModule.AddDeclarationDiagnostics(tempDiags) Else Debug.Assert(TypeSymbol.Equals(underlyingType, Me._lazyEnumUnderlyingType, TypeCompareKind.ConsiderEverything)) underlyingType = Me._lazyEnumUnderlyingType End If tempDiags.Free() End If Debug.Assert(underlyingType IsNot Nothing) Return underlyingType End Get End Property Private Function BindEnumUnderlyingType(syntax As EnumBlockSyntax, bodyBinder As Binder, diagnostics As BindingDiagnosticBag) As NamedTypeSymbol Dim underlyingType = syntax.EnumStatement.UnderlyingType If underlyingType IsNot Nothing AndAlso Not underlyingType.Type.IsMissing Then Dim type = bodyBinder.BindTypeSyntax(underlyingType.Type, diagnostics) If type.IsValidEnumUnderlyingType Then Return DirectCast(type, NamedTypeSymbol) Else Binder.ReportDiagnostic(diagnostics, underlyingType.Type, ERRID.ERR_InvalidEnumBase) End If End If Return bodyBinder.GetSpecialType(Microsoft.CodeAnalysis.SpecialType.System_Int32, syntax.EnumStatement.Identifier, diagnostics) End Function #End Region #Region "Attributes" Public ReadOnly Property DefaultAttributeLocation As AttributeLocation Implements IAttributeTargetSymbol.DefaultAttributeLocation Get Return AttributeLocation.Type End Get End Property Private Function GetAttributeDeclarations(Optional quickAttributes As QuickAttributes? = Nothing) As ImmutableArray(Of SyntaxList(Of AttributeListSyntax)) ' if we were asked to only load attributes if particular quick attributes were set ' then first see if any global aliases might have introduced names for those attributes. ' If so, we'll have to load all type attributes as we really won't know if they might ' be referencing that attribute through an alias or not. If quickAttributes IsNot Nothing Then For Each globalImport In Me.DeclaringCompilation.Options.GlobalImports If globalImport.Clause.Kind = SyntaxKind.SimpleImportsClause Then Dim simpleImportsClause = DirectCast(globalImport.Clause, SimpleImportsClauseSyntax) If simpleImportsClause.Alias IsNot Nothing Then Dim name = QuickAttributeChecker.GetFinalName(simpleImportsClause.Name) Select Case name Case AttributeDescription.CaseInsensitiveExtensionAttribute.Name, AttributeDescription.ObsoleteAttribute.Name, AttributeDescription.DeprecatedAttribute.Name, AttributeDescription.ExperimentalAttribute.Name, AttributeDescription.MyGroupCollectionAttribute.Name, AttributeDescription.TypeIdentifierAttribute.Name ' a global alias exists to one of the special type. can't trust the ' decl table alone. so grab all the attributes from the typedecl Return TypeDeclaration.GetAttributeDeclarations() End Select End If End If Next End If Dim result = TypeDeclaration.GetAttributeDeclarations(quickAttributes) Debug.Assert(result.Length = 0 OrElse (Not Me.IsScriptClass AndAlso Not Me.IsImplicitClass)) ' Should be handled by above test. Return result End Function Private Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) If m_lazyCustomAttributesBag Is Nothing OrElse Not m_lazyCustomAttributesBag.IsSealed Then LoadAndValidateAttributes(OneOrMany.Create(GetAttributeDeclarations()), m_lazyCustomAttributesBag) End If Debug.Assert(m_lazyCustomAttributesBag.IsSealed) Return m_lazyCustomAttributesBag End Function ''' <summary> ''' Gets the attributes applied on this symbol. ''' Returns an empty array if there are no attributes. ''' </summary> Public NotOverridable Overloads Overrides Function GetAttributes() As ImmutableArray(Of VisualBasicAttributeData) Return Me.GetAttributesBag().Attributes End Function Private Function GetDecodedWellKnownAttributeData() As CommonTypeWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.m_lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonTypeWellKnownAttributeData) End Function Friend Overrides ReadOnly Property HasCodeAnalysisEmbeddedAttribute As Boolean Get Dim data As TypeEarlyWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCodeAnalysisEmbeddedAttribute End Get End Property Friend Overrides ReadOnly Property HasVisualBasicEmbeddedAttribute As Boolean Get Dim data As TypeEarlyWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasVisualBasicEmbeddedAttribute End Get End Property Friend Overrides ReadOnly Property IsExtensibleInterfaceNoUseSiteDiagnostics As Boolean Get If _lazyIsExtensibleInterface = ThreeState.Unknown Then _lazyIsExtensibleInterface = DecodeIsExtensibleInterface().ToThreeState() End If Return _lazyIsExtensibleInterface.Value End Get End Property Private Function DecodeIsExtensibleInterface() As Boolean If Me.IsInterfaceType() Then Dim data As TypeEarlyWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData() If data IsNot Nothing AndAlso data.HasAttributeForExtensibleInterface Then Return True End If For Each [interface] In Me.AllInterfacesNoUseSiteDiagnostics If [interface].IsExtensibleInterfaceNoUseSiteDiagnostics Then Return True End If Next End If Return False End Function ''' <summary> ''' Returns data decoded from early bound well-known attributes applied to the symbol or null if there are no applied attributes. ''' </summary> ''' <remarks> ''' Forces binding and decoding of attributes. ''' </remarks> Private Function GetEarlyDecodedWellKnownAttributeData() As TypeEarlyWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.m_lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsEarlyDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.EarlyDecodedWellKnownAttributeData, TypeEarlyWellKnownAttributeData) End Function Friend Overrides ReadOnly Property IsComImport As Boolean Get Dim data As TypeEarlyWellKnownAttributeData = GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasComImportAttribute End Get End Property Friend Overrides ReadOnly Property CoClassType As TypeSymbol Get If _lazyCoClassType Is ErrorTypeSymbol.UnknownResultType Then If Not Me.IsInterface Then Interlocked.CompareExchange(_lazyCoClassType, Nothing, DirectCast(ErrorTypeSymbol.UnknownResultType, TypeSymbol)) Else Dim dummy As CommonTypeWellKnownAttributeData = GetDecodedWellKnownAttributeData() If _lazyCoClassType Is ErrorTypeSymbol.UnknownResultType Then ' if this is still ErrorTypeSymbol.UnknownResultType, interface ' does not have the attribute applied Interlocked.CompareExchange(_lazyCoClassType, Nothing, DirectCast(ErrorTypeSymbol.UnknownResultType, TypeSymbol)) End If End If End If Debug.Assert(_lazyCoClassType IsNot ErrorTypeSymbol.UnknownResultType) Debug.Assert(Me.IsInterface OrElse _lazyCoClassType Is Nothing) Return _lazyCoClassType End Get End Property Friend Overrides ReadOnly Property IsWindowsRuntimeImport As Boolean Get Dim typeData As CommonTypeWellKnownAttributeData = Me.GetDecodedWellKnownAttributeData() Return typeData IsNot Nothing AndAlso typeData.HasWindowsRuntimeImportAttribute End Get End Property Friend Overrides ReadOnly Property ShouldAddWinRTMembers As Boolean Get Return False End Get End Property Friend ReadOnly Property HasSecurityCriticalAttributes As Boolean Get Dim typeData As CommonTypeWellKnownAttributeData = Me.GetDecodedWellKnownAttributeData() Return typeData IsNot Nothing AndAlso typeData.HasSecurityCriticalAttributes End Get End Property ''' <summary> ''' Is System.Runtime.InteropServices.GuidAttribute applied to this type in code. ''' </summary> Friend Function HasGuidAttribute() As Boolean ' So far this information is used only by ComClass feature, therefore, I do not believe ' it is worth to intercept this attribute in DecodeWellKnownAttribute and cache the fact of attribute's ' presence and the guid value. If we start caching that information, implementation of this function ' should change to take advantage of the cache. Return GetAttributes().IndexOfAttribute(Me, AttributeDescription.GuidAttribute) > -1 End Function ''' <summary> ''' Is System.Runtime.InteropServices.ClassInterfaceAttribute applied to this type in code. ''' </summary> Friend Function HasClassInterfaceAttribute() As Boolean ' So far this information is used only by ComClass feature, therefore, I do not believe ' it is worth to intercept this attribute in DecodeWellKnownAttribute and cache the fact of attribute's ' presence and its data. If we start caching that information, implementation of this function ' should change to take advantage of the cache. Return GetAttributes().IndexOfAttribute(Me, AttributeDescription.ClassInterfaceAttribute) > -1 End Function ''' <summary> ''' Is System.Runtime.InteropServices.ComSourceInterfacesAttribute applied to this type in code. ''' </summary> Friend Function HasComSourceInterfacesAttribute() As Boolean ' So far this information is used only by ComClass feature, therefore, I do not believe ' it is worth to intercept this attribute in DecodeWellKnownAttribute and cache the fact of attribute's ' presence and the its data. If we start caching that information, implementation of this function ' should change to take advantage of the cache. Return GetAttributes().IndexOfAttribute(Me, AttributeDescription.ComSourceInterfacesAttribute) > -1 End Function Friend Overrides Function EarlyDecodeWellKnownAttribute(ByRef arguments As EarlyDecodeWellKnownAttributeArguments(Of EarlyWellKnownAttributeBinder, NamedTypeSymbol, AttributeSyntax, AttributeLocation)) As VisualBasicAttributeData Debug.Assert(arguments.AttributeType IsNot Nothing) Debug.Assert(Not arguments.AttributeType.IsErrorType()) Dim hasAnyDiagnostics As Boolean = False If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.VisualBasicEmbeddedAttribute) Then ' Handle Microsoft.VisualBasic.Embedded attribute Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().HasVisualBasicEmbeddedAttribute = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.CodeAnalysisEmbeddedAttribute) Then ' Handle Microsoft.CodeAnalysis.Embedded attribute Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().HasCodeAnalysisEmbeddedAttribute = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ComImportAttribute) Then ' Handle ComImportAttribute Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().HasComImportAttribute = True Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.ConditionalAttribute) Then ' Handle ConditionalAttribute Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then Dim conditionalSymbol As String = attrdata.GetConstructorArgument(Of String)(0, SpecialType.System_String) arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().AddConditionalSymbol(conditionalSymbol) Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If End If Dim boundAttribute As VisualBasicAttributeData = Nothing Dim obsoleteData As ObsoleteAttributeData = Nothing If EarlyDecodeDeprecatedOrExperimentalOrObsoleteAttribute(arguments, boundAttribute, obsoleteData) Then If obsoleteData IsNot Nothing Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().ObsoleteAttributeData = obsoleteData End If Return boundAttribute End If If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.AttributeUsageAttribute) Then ' Avoid decoding duplicate AttributeUsageAttribute. If Not arguments.HasDecodedData OrElse DirectCast(arguments.DecodedData, TypeEarlyWellKnownAttributeData).AttributeUsageInfo.IsNull Then ' Handle AttributeUsageAttribute: If this type is an attribute type then decode the AttributeUsageAttribute, otherwise ignore it. Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData)().AttributeUsageInfo = attrdata.DecodeAttributeUsageAttribute() Debug.Assert(Not DirectCast(arguments.DecodedData, TypeEarlyWellKnownAttributeData).AttributeUsageInfo.IsNull) ' NOTE: Native VB compiler does not validate the AttributeTargets argument to AttributeUsageAttribute, we do the same. Return If(Not hasAnyDiagnostics, attrdata, Nothing) End If End If Return Nothing End If If Me.IsInterfaceType() Then If VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.InterfaceTypeAttribute) Then Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then Dim interfaceType As ComInterfaceType = Nothing If attrdata.DecodeInterfaceTypeAttribute(interfaceType) AndAlso (interfaceType And Cci.Constants.ComInterfaceType_InterfaceIsIDispatch) <> 0 Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData).HasAttributeForExtensibleInterface = True End If Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If ElseIf VisualBasicAttributeData.IsTargetEarlyAttribute(arguments.AttributeType, arguments.AttributeSyntax, AttributeDescription.TypeLibTypeAttribute) Then Dim attrdata = arguments.Binder.GetAttribute(arguments.AttributeSyntax, arguments.AttributeType, hasAnyDiagnostics) If Not attrdata.HasErrors Then Dim flags As Cci.TypeLibTypeFlags = attrdata.DecodeTypeLibTypeAttribute() If (flags And Cci.TypeLibTypeFlags.FNonExtensible) = 0 Then arguments.GetOrCreateData(Of TypeEarlyWellKnownAttributeData).HasAttributeForExtensibleInterface = True End If Return If(Not hasAnyDiagnostics, attrdata, Nothing) Else Return Nothing End If End If End If Return MyBase.EarlyDecodeWellKnownAttribute(arguments) End Function Friend NotOverridable Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Dim data As CommonTypeEarlyWellKnownAttributeData = Me.GetEarlyDecodedWellKnownAttributeData() Return If(data IsNot Nothing, data.ConditionalSymbols, ImmutableArray(Of String).Empty) End Function Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Dim lazyCustomAttributesBag = m_lazyCustomAttributesBag If lazyCustomAttributesBag IsNot Nothing AndAlso lazyCustomAttributesBag.IsEarlyDecodedWellKnownAttributeDataComputed Then Dim data = DirectCast(lazyCustomAttributesBag.EarlyDecodedWellKnownAttributeData, CommonTypeEarlyWellKnownAttributeData) Return If(data IsNot Nothing, data.ObsoleteAttributeData, Nothing) End If For Each decl In TypeDeclaration.Declarations If decl.HasAnyAttributes Then Return ObsoleteAttributeData.Uninitialized End If Next Return Nothing End Get End Property Friend NotOverridable Overrides Function GetAttributeUsageInfo() As AttributeUsageInfo Debug.Assert(Me.IsOrDerivedFromWellKnownClass(WellKnownType.System_Attribute, DeclaringCompilation, CompoundUseSiteInfo(Of AssemblySymbol).Discarded) OrElse Me.SpecialType = Microsoft.CodeAnalysis.SpecialType.System_Object) Dim data As TypeEarlyWellKnownAttributeData = Me.GetEarlyDecodedWellKnownAttributeData() If data IsNot Nothing AndAlso Not data.AttributeUsageInfo.IsNull Then Return data.AttributeUsageInfo Else Dim baseType = Me.BaseTypeNoUseSiteDiagnostics Return If(baseType IsNot Nothing, baseType.GetAttributeUsageInfo(), AttributeUsageInfo.Default) End If End Function Friend NotOverridable Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Dim data As CommonTypeWellKnownAttributeData = Me.GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasDeclarativeSecurity End Get End Property Friend NotOverridable Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me.GetAttributesBag() Dim wellKnownAttributeData = DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonTypeWellKnownAttributeData) If wellKnownAttributeData IsNot Nothing Then Dim securityData As SecurityWellKnownAttributeData = wellKnownAttributeData.SecurityInformation If securityData IsNot Nothing Then Return securityData.GetSecurityAttributes(attributesBag.Attributes) End If End If Return SpecializedCollections.EmptyEnumerable(Of Microsoft.Cci.SecurityAttribute)() End Function Friend NotOverridable Overrides Sub DecodeWellKnownAttribute(ByRef arguments As DecodeWellKnownAttributeArguments(Of AttributeSyntax, VisualBasicAttributeData, AttributeLocation)) Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) Dim attrData = arguments.Attribute Debug.Assert(Not attrData.HasErrors) Debug.Assert(arguments.SymbolPart = AttributeLocation.None) Dim diagnostics = DirectCast(arguments.Diagnostics, BindingDiagnosticBag) ' If we start caching information about GuidAttribute here, implementation of HasGuidAttribute function should be changed accordingly. ' If we start caching information about ClassInterfaceAttribute here, implementation of HasClassInterfaceAttribute function should be changed accordingly. ' If we start caching information about ComSourceInterfacesAttribute here, implementation of HasComSourceInterfacesAttribute function should be changed accordingly. ' If we start caching information about ComVisibleAttribute here, implementation of GetComVisibleState function should be changed accordingly. If attrData.IsTargetAttribute(Me, AttributeDescription.TupleElementNamesAttribute) Then diagnostics.Add(ERRID.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location) End If Dim decoded As Boolean = False Select Case Me.TypeKind Case TypeKind.Class If attrData.IsTargetAttribute(Me, AttributeDescription.CaseInsensitiveExtensionAttribute) Then diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_ExtensionOnlyAllowedOnModuleSubOrFunction), Me.Locations(0)) decoded = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.VisualBasicComClassAttribute) Then If Me.IsGenericType Then diagnostics.Add(ERRID.ERR_ComClassOnGeneric, Me.Locations(0)) Else Interlocked.CompareExchange(_comClassData, New ComClassData(attrData), Nothing) End If decoded = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.DefaultEventAttribute) Then If attrData.CommonConstructorArguments.Length = 1 AndAlso attrData.CommonConstructorArguments(0).Kind = TypedConstantKind.Primitive Then Dim eventName = TryCast(attrData.CommonConstructorArguments(0).ValueInternal, String) If eventName IsNot Nothing AndAlso eventName.Length > 0 AndAlso Not FindDefaultEvent(eventName) Then diagnostics.Add(ERRID.ERR_DefaultEventNotFound1, arguments.AttributeSyntaxOpt.GetLocation(), eventName) End If End If decoded = True End If Case TypeKind.Interface If attrData.IsTargetAttribute(Me, AttributeDescription.CoClassAttribute) Then Debug.Assert(Not attrData.CommonConstructorArguments.IsDefault AndAlso attrData.CommonConstructorArguments.Length = 1) Dim argument As TypedConstant = attrData.CommonConstructorArguments(0) Debug.Assert(argument.Kind = TypedConstantKind.Type) Debug.Assert(argument.TypeInternal IsNot Nothing) Debug.Assert(DirectCast(argument.TypeInternal, TypeSymbol).Equals(DeclaringCompilation.GetWellKnownType(WellKnownType.System_Type), TypeCompareKind.ConsiderEverything)) ' Note that 'argument.Value' may be Nothing in which case Roslyn will ' generate an error as if CoClassAttribute attribute was not defined on ' the interface; this behavior matches Dev11, but we should probably ' revise it later Interlocked.CompareExchange(Me._lazyCoClassType, DirectCast(argument.ValueInternal, TypeSymbol), DirectCast(ErrorTypeSymbol.UnknownResultType, TypeSymbol)) decoded = True End If Case TypeKind.Module If ContainingSymbol.Kind = SymbolKind.Namespace AndAlso attrData.IsTargetAttribute(Me, AttributeDescription.CaseInsensitiveExtensionAttribute) Then ' Already have an attribute, no need to add another one. SuppressExtensionAttributeSynthesis() decoded = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.VisualBasicComClassAttribute) Then ' Can't apply ComClassAttribute to a Module diagnostics.Add(ErrorFactory.ErrorInfo(ERRID.ERR_InvalidAttributeUsage2, AttributeDescription.VisualBasicComClassAttribute.Name, Me.Name), Me.Locations(0)) decoded = True End If End Select If Not decoded Then If attrData.IsTargetAttribute(Me, AttributeDescription.DefaultMemberAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasDefaultMemberAttribute = True ' Check that the explicit <DefaultMember(...)> argument matches the default property if any. Dim attributeValue = attrData.DecodeDefaultMemberAttribute() Dim defaultProperty = DefaultPropertyName If Not String.IsNullOrEmpty(defaultProperty) AndAlso Not IdentifierComparison.Equals(defaultProperty, attributeValue) Then diagnostics.Add(ERRID.ERR_ConflictDefaultPropertyAttribute, Locations(0), Me) End If ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SerializableAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasSerializableAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ExcludeFromCodeCoverageAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasExcludeFromCodeCoverageAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SpecialNameAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasSpecialNameAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.StructLayoutAttribute) Then Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) Dim defaultAutoLayoutSize = If(Me.TypeKind = TypeKind.Structure, 1, 0) AttributeData.DecodeStructLayoutAttribute(Of CommonTypeWellKnownAttributeData, AttributeSyntax, VisualBasicAttributeData, AttributeLocation)( arguments, Me.DefaultMarshallingCharSet, defaultAutoLayoutSize, MessageProvider.Instance) If Me.IsGenericType Then diagnostics.Add(ERRID.ERR_StructLayoutAttributeNotAllowed, arguments.AttributeSyntaxOpt.GetLocation(), Me) End If ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SuppressUnmanagedCodeSecurityAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasSuppressUnmanagedCodeSecurityAttribute = True ElseIf attrData.IsSecurityAttribute(Me.DeclaringCompilation) Then attrData.DecodeSecurityAttribute(Of CommonTypeWellKnownAttributeData)(Me, Me.DeclaringCompilation, arguments) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.ClassInterfaceAttribute) Then attrData.DecodeClassInterfaceAttribute(arguments.AttributeSyntaxOpt, diagnostics) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.InterfaceTypeAttribute) Then attrData.DecodeInterfaceTypeAttribute(arguments.AttributeSyntaxOpt, diagnostics) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.GuidAttribute) Then attrData.DecodeGuidAttribute(arguments.AttributeSyntaxOpt, diagnostics) ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.WindowsRuntimeImportAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasWindowsRuntimeImportAttribute = True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.SecurityCriticalAttribute) OrElse attrData.IsTargetAttribute(Me, AttributeDescription.SecuritySafeCriticalAttribute) Then arguments.GetOrCreateData(Of CommonTypeWellKnownAttributeData)().HasSecurityCriticalAttributes = True ElseIf _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.Unknown AndAlso attrData.IsTargetAttribute(Me, AttributeDescription.TypeIdentifierAttribute) Then _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.True ElseIf attrData.IsTargetAttribute(Me, AttributeDescription.RequiredAttributeAttribute) Then Debug.Assert(arguments.AttributeSyntaxOpt IsNot Nothing) diagnostics.Add(ERRID.ERR_CantUseRequiredAttribute, arguments.AttributeSyntaxOpt.GetLocation(), Me) End If End If MyBase.DecodeWellKnownAttribute(arguments) End Sub Friend Overrides ReadOnly Property IsExplicitDefinitionOfNoPiaLocalType As Boolean Get If _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.Unknown Then CheckPresenceOfTypeIdentifierAttribute() If _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.Unknown Then _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.False End If End If Debug.Assert(_lazyIsExplicitDefinitionOfNoPiaLocalType <> ThreeState.Unknown) Return _lazyIsExplicitDefinitionOfNoPiaLocalType = ThreeState.True End Get End Property Private Sub CheckPresenceOfTypeIdentifierAttribute() ' Have we already decoded well-known attributes? If Me.m_lazyCustomAttributesBag?.IsDecodedWellKnownAttributeDataComputed Then Return End If ' We want this function to be as cheap as possible, it is called for every top level type ' and we don't want to bind attributes attached to the declaration unless there is a chance ' that one of them is TypeIdentifier attribute. Dim attributeLists As ImmutableArray(Of SyntaxList(Of AttributeListSyntax)) = GetAttributeDeclarations(QuickAttributes.TypeIdentifier) For Each list As SyntaxList(Of AttributeListSyntax) In attributeLists Dim sourceFile = ContainingSourceModule.TryGetSourceFile(list.Node.SyntaxTree) For Each attrList As AttributeListSyntax In list For Each attr As AttributeSyntax In attrList.Attributes If (sourceFile.QuickAttributeChecker.CheckAttribute(attr) And QuickAttributes.TypeIdentifier) <> 0 Then ' This attribute syntax might be an application of TypeIdentifierAttribute. ' Let's bind it. ' For simplicity we bind all attributes. GetAttributes() Return End If Next Next Next End Sub Private Function FindDefaultEvent(eventName As String) As Boolean Dim current As NamedTypeSymbol = Me Do For Each member As Symbol In current.GetMembers(eventName) If member.Kind = SymbolKind.Event AndAlso (member.DeclaredAccessibility = Accessibility.Public OrElse member.DeclaredAccessibility = Accessibility.Friend) Then ' We have a match so the default event is valid. Return True End If Next current = current.BaseTypeNoUseSiteDiagnostics Loop While current IsNot Nothing Return False End Function Friend Overrides Sub PostDecodeWellKnownAttributes( boundAttributes As ImmutableArray(Of VisualBasicAttributeData), allAttributeSyntaxNodes As ImmutableArray(Of AttributeSyntax), diagnostics As BindingDiagnosticBag, symbolPart As AttributeLocation, decodedData As WellKnownAttributeData) Debug.Assert(Not boundAttributes.IsDefault) Debug.Assert(Not allAttributeSyntaxNodes.IsDefault) Debug.Assert(boundAttributes.Length = allAttributeSyntaxNodes.Length) Debug.Assert(symbolPart = AttributeLocation.None) ValidateStandardModuleAttribute(diagnostics) MyBase.PostDecodeWellKnownAttributes(boundAttributes, allAttributeSyntaxNodes, diagnostics, symbolPart, decodedData) End Sub Private Sub ValidateStandardModuleAttribute(diagnostics As BindingDiagnosticBag) ' If this type is a VB Module, touch the ctor for MS.VB.Globals.StandardModuleAttribute to ' produce any diagnostics related to that member and type. ' Dev10 reported a special diagnostic ERR_NoStdModuleAttribute if the constructor was missing. ' Roslyn now used the more general use site errors, which also reports diagnostics if the type or the constructor ' is missing. If Me.TypeKind = TypeKind.Module Then Dim useSiteError As DiagnosticInfo = Nothing Binder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor, Me.DeclaringCompilation, Locations(0), diagnostics) End If End Sub Friend NotOverridable Overrides ReadOnly Property IsDirectlyExcludedFromCodeCoverage As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasExcludeFromCodeCoverageAttribute End Get End Property Friend NotOverridable Overrides ReadOnly Property HasSpecialName As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasSpecialNameAttribute End Get End Property Public NotOverridable Overrides ReadOnly Property IsSerializable As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasSerializableAttribute End Get End Property Private Function HasInstanceFields() As Boolean Dim members = Me.GetMembersUnordered() For i = 0 To members.Length - 1 Dim m = members(i) If Not m.IsShared And m.Kind = SymbolKind.Field Then Return True End If Next Return False End Function Friend NotOverridable Overrides ReadOnly Property Layout As TypeLayout Get Dim data = GetDecodedWellKnownAttributeData() If data IsNot Nothing AndAlso data.HasStructLayoutAttribute Then Return data.Layout End If If Me.TypeKind = TypeKind.Structure Then ' CLI spec 22.37.16: ' "A ValueType shall have a non-zero size - either by defining at least one field, or by providing a non-zero ClassSize" ' ' Dev11 compiler sets the value to 1 for structs with no fields and no size specified. ' It does not change the size value if it was explicitly specified to be 0, nor does it report an error. Return New TypeLayout(LayoutKind.Sequential, If(Me.HasInstanceFields(), 0, 1), alignment:=0) End If Return Nothing End Get End Property Friend ReadOnly Property HasStructLayoutAttribute As Boolean Get Dim data = GetDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasStructLayoutAttribute End Get End Property Friend Overrides ReadOnly Property MarshallingCharSet As CharSet Get Dim data = GetDecodedWellKnownAttributeData() Return If((data IsNot Nothing AndAlso data.HasStructLayoutAttribute), data.MarshallingCharSet, DefaultMarshallingCharSet) End Get End Property Friend Overrides Sub AddSynthesizedAttributes(compilationState As ModuleCompilationState, ByRef attributes As ArrayBuilder(Of SynthesizedAttributeData)) MyBase.AddSynthesizedAttributes(compilationState, attributes) Dim compilation = Me.DeclaringCompilation If Not String.IsNullOrEmpty(DefaultPropertyName) AndAlso Not HasDefaultMemberAttribute() Then Dim stringType = GetSpecialType(SpecialType.System_String) ' NOTE: used from emit, so shouldn't have gotten here if there were errors Debug.Assert(stringType.GetUseSiteInfo().DiagnosticInfo Is Nothing) AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Reflection_DefaultMemberAttribute__ctor, ImmutableArray.Create( New TypedConstant(stringType, TypedConstantKind.Primitive, DefaultPropertyName)))) End If If Me.TypeKind = TypeKind.Module Then 'TODO check that there's not a user supplied instance already. This attribute is AllowMultiple:=False. AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.Microsoft_VisualBasic_CompilerServices_StandardModuleAttribute__ctor)) End If If _comClassData IsNot Nothing Then If _comClassData.ClassId IsNot Nothing Then AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_InteropServices_GuidAttribute__ctor, ImmutableArray.Create( New TypedConstant(GetSpecialType(SpecialType.System_String), TypedConstantKind.Primitive, _comClassData.ClassId)))) End If AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_InteropServices_ClassInterfaceAttribute__ctorClassInterfaceType, ImmutableArray.Create( New TypedConstant(GetSpecialType(SpecialType.System_Int32), TypedConstantKind.Enum, CInt(ClassInterfaceType.None))))) Dim eventInterface As NamedTypeSymbol = _comClassData.GetSynthesizedEventInterface() If eventInterface IsNot Nothing Then Dim eventInterfaceName As String = eventInterface.Name Dim container1 As NamedTypeSymbol = Me Dim container2 As NamedTypeSymbol = container1.ContainingType While container2 IsNot Nothing eventInterfaceName = container1.Name & "+" & eventInterfaceName container1 = container2 container2 = container1.ContainingType End While eventInterfaceName = container1.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) & "+" & eventInterfaceName AddSynthesizedAttribute(attributes, compilation.TrySynthesizeAttribute( WellKnownMember.System_Runtime_InteropServices_ComSourceInterfacesAttribute__ctorString, ImmutableArray.Create( New TypedConstant(GetSpecialType(SpecialType.System_String), TypedConstantKind.Primitive, eventInterfaceName)))) End If End If Dim baseType As NamedTypeSymbol = Me.BaseTypeNoUseSiteDiagnostics If baseType IsNot Nothing Then If baseType.ContainsTupleNames() Then AddSynthesizedAttribute(attributes, compilation.SynthesizeTupleNamesAttribute(baseType)) End If End If End Sub Private Function HasDefaultMemberAttribute() As Boolean Dim attributesBag = GetAttributesBag() Dim wellKnownAttributeData = DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonTypeWellKnownAttributeData) Return (wellKnownAttributeData IsNot Nothing) AndAlso wellKnownAttributeData.HasDefaultMemberAttribute End Function #End Region Friend Function GetOrAddWithEventsOverride(baseProperty As PropertySymbol) As SynthesizedOverridingWithEventsProperty Dim overridesDict = Me._lazyWithEventsOverrides If overridesDict Is Nothing Then Interlocked.CompareExchange(Me._lazyWithEventsOverrides, New ConcurrentDictionary(Of PropertySymbol, SynthesizedOverridingWithEventsProperty), Nothing) overridesDict = Me._lazyWithEventsOverrides End If Dim result As SynthesizedOverridingWithEventsProperty = Nothing If overridesDict.TryGetValue(baseProperty, result) Then Return result Else ' we need to create a lambda here since we need to close over baseProperty ' we will however create a lambda only on a cache miss, hopefully not very often. Return overridesDict.GetOrAdd(baseProperty, Function() Debug.Assert(Not _withEventsOverridesAreFrozen) Return New SynthesizedOverridingWithEventsProperty(baseProperty, Me) End Function) End If End Function Friend NotOverridable Overrides Function GetSynthesizedWithEventsOverrides() As IEnumerable(Of PropertySymbol) EnsureAllHandlesAreBound() Dim overridesDict = Me._lazyWithEventsOverrides If overridesDict IsNot Nothing Then Return overridesDict.Values End If Return SpecializedCollections.EmptyEnumerable(Of PropertySymbol)() End Function Private Sub EnsureAllHandlesAreBound() If Not _withEventsOverridesAreFrozen Then For Each member In Me.GetMembersUnordered() If member.Kind = SymbolKind.Method Then Dim notUsed = DirectCast(member, MethodSymbol).HandledEvents End If Next _withEventsOverridesAreFrozen = True End If End Sub Protected Overrides Sub AddEntryPointIfNeeded(membersBuilder As MembersAndInitializersBuilder) If Me.TypeKind = TypeKind.Class AndAlso Not Me.IsGenericType Then Dim mainTypeName As String = DeclaringCompilation.Options.MainTypeName If mainTypeName IsNot Nothing AndAlso IdentifierComparison.EndsWith(mainTypeName, Me.Name) AndAlso IdentifierComparison.Equals(mainTypeName, Me.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat)) Then ' Must derive from Windows.Forms.Form Dim formClass As NamedTypeSymbol = DeclaringCompilation.GetWellKnownType(WellKnownType.System_Windows_Forms_Form) If formClass.IsErrorType() OrElse Not Me.IsOrDerivedFrom(formClass, useSiteInfo:=CompoundUseSiteInfo(Of AssemblySymbol).Discarded) Then Return End If Dim entryPointMethodName As String = WellKnownMemberNames.EntryPointMethodName ' If we already have a child named 'Main', do not add a synthetic one. If membersBuilder.Members.ContainsKey(entryPointMethodName) Then Return End If If GetTypeMembersDictionary().ContainsKey(entryPointMethodName) Then Return End If ' We need to have a constructor that can be called without arguments. Dim symbols As ArrayBuilder(Of Symbol) = Nothing Dim haveSuitableConstructor As Boolean = False If membersBuilder.Members.TryGetValue(WellKnownMemberNames.InstanceConstructorName, symbols) Then For Each method As MethodSymbol In symbols If method.MethodKind = MethodKind.Constructor AndAlso method.ParameterCount = 0 Then haveSuitableConstructor = True Exit For End If Next If Not haveSuitableConstructor Then ' Do the second pass to check for optional parameters, etc., it will require binding parameter modifiers and probably types. For Each method As MethodSymbol In symbols If method.MethodKind = MethodKind.Constructor AndAlso method.CanBeCalledWithNoParameters() Then haveSuitableConstructor = True Exit For End If Next End If End If If haveSuitableConstructor Then Dim syntaxRef = SyntaxReferences.First() ' use arbitrary part Dim binder As Binder = BinderBuilder.CreateBinderForType(ContainingSourceModule, syntaxRef.SyntaxTree, Me) Dim entryPoint As New SynthesizedMainTypeEntryPoint(syntaxRef.GetVisualBasicSyntax(), Me) AddMember(entryPoint, binder, membersBuilder, omitDiagnostics:=True) End If End If End If End Sub End Class End Namespace
1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/VisualStudio/Xaml/Impl/Implementation/LanguageClient/XamlCapabilities.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Linq; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler; using RoslynCompletion = Microsoft.CodeAnalysis.Completion; namespace Microsoft.VisualStudio.LanguageServices.Xaml { internal static class XamlCapabilities { /// <summary> /// The currently supported set of XAML LSP Server capabilities /// </summary> public static VSInternalServerCapabilities Current => new() { CompletionProvider = new CompletionOptions { ResolveProvider = true, TriggerCharacters = new string[] { "<", " ", ":", ".", "=", "\"", "'", "{", ",", "(" }, AllCommitCharacters = RoslynCompletion.CompletionRules.Default.DefaultCommitCharacters.Select(c => c.ToString()).ToArray() }, HoverProvider = true, FoldingRangeProvider = new FoldingRangeOptions { }, DocumentFormattingProvider = true, DocumentRangeFormattingProvider = true, DocumentOnTypeFormattingProvider = new DocumentOnTypeFormattingOptions { FirstTriggerCharacter = ">" }, OnAutoInsertProvider = new VSInternalDocumentOnAutoInsertOptions { TriggerCharacters = new[] { "=", "/" } }, TextDocumentSync = new TextDocumentSyncOptions { Change = TextDocumentSyncKind.None, OpenClose = false }, SupportsDiagnosticRequests = true, LinkedEditingRangeProvider = new LinkedEditingRangeOptions { }, ExecuteCommandProvider = new ExecuteCommandOptions { Commands = new[] { StringConstants.CreateEventHandlerCommand } }, DefinitionProvider = true, }; /// <summary> /// An empty set of capabilities used to disable the XAML LSP Server /// </summary> public static VSServerCapabilities None => new() { TextDocumentSync = new TextDocumentSyncOptions { Change = TextDocumentSyncKind.None, OpenClose = 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.Linq; using Microsoft.CodeAnalysis.Editor.Xaml; using Microsoft.VisualStudio.LanguageServer.Protocol; using Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler; using RoslynCompletion = Microsoft.CodeAnalysis.Completion; namespace Microsoft.VisualStudio.LanguageServices.Xaml { internal static class XamlCapabilities { /// <summary> /// The currently supported set of XAML LSP Server capabilities /// </summary> public static VSInternalServerCapabilities Current => new() { CompletionProvider = new CompletionOptions { ResolveProvider = true, TriggerCharacters = new string[] { "<", " ", ":", ".", "=", "\"", "'", "{", ",", "(" }, AllCommitCharacters = RoslynCompletion.CompletionRules.Default.DefaultCommitCharacters.Select(c => c.ToString()).ToArray() }, HoverProvider = true, FoldingRangeProvider = new FoldingRangeOptions { }, DocumentFormattingProvider = true, DocumentRangeFormattingProvider = true, DocumentOnTypeFormattingProvider = new DocumentOnTypeFormattingOptions { FirstTriggerCharacter = ">" }, OnAutoInsertProvider = new VSInternalDocumentOnAutoInsertOptions { TriggerCharacters = new[] { "=", "/" } }, TextDocumentSync = new TextDocumentSyncOptions { Change = TextDocumentSyncKind.None, OpenClose = false }, SupportsDiagnosticRequests = true, LinkedEditingRangeProvider = new LinkedEditingRangeOptions { }, ExecuteCommandProvider = new ExecuteCommandOptions { Commands = new[] { StringConstants.CreateEventHandlerCommand } }, DefinitionProvider = true, }; /// <summary> /// An empty set of capabilities used to disable the XAML LSP Server /// </summary> public static VSServerCapabilities None => new() { TextDocumentSync = new TextDocumentSyncOptions { Change = TextDocumentSyncKind.None, OpenClose = false }, }; } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/Core/Portable/DiagnosticAnalyzer/CompilationWithAnalyzersOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Diagnostics { /// <summary> /// Options to configure analyzer execution within <see cref="CompilationWithAnalyzers"/>. /// </summary> public sealed class CompilationWithAnalyzersOptions { private readonly AnalyzerOptions? _options; private readonly Action<Exception, DiagnosticAnalyzer, Diagnostic>? _onAnalyzerException; private readonly Func<Exception, bool>? _analyzerExceptionFilter; private readonly bool _concurrentAnalysis; private readonly bool _logAnalyzerExecutionTime; private readonly bool _reportSuppressedDiagnostics; /// <summary> /// Options passed to <see cref="DiagnosticAnalyzer"/>s. /// </summary> public AnalyzerOptions? Options => _options; /// <summary> /// An optional delegate to be invoked when an analyzer throws an exception. /// </summary> public Action<Exception, DiagnosticAnalyzer, Diagnostic>? OnAnalyzerException => _onAnalyzerException; /// <summary> /// An optional delegate to be invoked when an analyzer throws an exception as an exception filter. /// </summary> public Func<Exception, bool>? AnalyzerExceptionFilter => _analyzerExceptionFilter; /// <summary> /// Flag indicating whether analysis can be performed concurrently on multiple threads. /// </summary> public bool ConcurrentAnalysis => _concurrentAnalysis; /// <summary> /// Flag indicating whether analyzer execution time should be logged. /// </summary> public bool LogAnalyzerExecutionTime => _logAnalyzerExecutionTime; /// <summary> /// Flag indicating whether analyzer diagnostics with <see cref="Diagnostic.IsSuppressed"/> should be reported. /// </summary> public bool ReportSuppressedDiagnostics => _reportSuppressedDiagnostics; /// <summary> /// Creates a new <see cref="CompilationWithAnalyzersOptions"/>. /// </summary> /// <param name="options">Options that are passed to analyzers.</param> /// <param name="onAnalyzerException">Action to invoke if an analyzer throws an exception.</param> /// <param name="concurrentAnalysis">Flag indicating whether analysis can be performed concurrently on multiple threads.</param> /// <param name="logAnalyzerExecutionTime">Flag indicating whether analyzer execution time should be logged.</param> public CompilationWithAnalyzersOptions( AnalyzerOptions options, Action<Exception, DiagnosticAnalyzer, Diagnostic>? onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime) : this(options, onAnalyzerException, concurrentAnalysis, logAnalyzerExecutionTime, reportSuppressedDiagnostics: false) { } /// <summary> /// Creates a new <see cref="CompilationWithAnalyzersOptions"/>. /// </summary> /// <param name="options">Options that are passed to analyzers.</param> /// <param name="onAnalyzerException">Action to invoke if an analyzer throws an exception.</param> /// <param name="concurrentAnalysis">Flag indicating whether analysis can be performed concurrently on multiple threads.</param> /// <param name="logAnalyzerExecutionTime">Flag indicating whether analyzer execution time should be logged.</param> /// <param name="reportSuppressedDiagnostics">Flag indicating whether analyzer diagnostics with <see cref="Diagnostic.IsSuppressed"/> should be reported.</param> public CompilationWithAnalyzersOptions( AnalyzerOptions options, Action<Exception, DiagnosticAnalyzer, Diagnostic>? onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime, bool reportSuppressedDiagnostics) : this(options, onAnalyzerException, concurrentAnalysis, logAnalyzerExecutionTime, reportSuppressedDiagnostics, analyzerExceptionFilter: null) { } /// <summary> /// Creates a new <see cref="CompilationWithAnalyzersOptions"/>. /// </summary> /// <param name="options">Options that are passed to analyzers.</param> /// <param name="onAnalyzerException">Action to invoke if an analyzer throws an exception.</param> /// <param name="analyzerExceptionFilter">Action to invoke if an analyzer throws an exception as an exception filter.</param> /// <param name="concurrentAnalysis">Flag indicating whether analysis can be performed concurrently on multiple threads.</param> /// <param name="logAnalyzerExecutionTime">Flag indicating whether analyzer execution time should be logged.</param> /// <param name="reportSuppressedDiagnostics">Flag indicating whether analyzer diagnostics with <see cref="Diagnostic.IsSuppressed"/> should be reported.</param> public CompilationWithAnalyzersOptions( AnalyzerOptions? options, Action<Exception, DiagnosticAnalyzer, Diagnostic>? onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime, bool reportSuppressedDiagnostics, Func<Exception, bool>? analyzerExceptionFilter) { _options = options; _onAnalyzerException = onAnalyzerException; _analyzerExceptionFilter = analyzerExceptionFilter; _concurrentAnalysis = concurrentAnalysis; _logAnalyzerExecutionTime = logAnalyzerExecutionTime; _reportSuppressedDiagnostics = reportSuppressedDiagnostics; } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Diagnostics { /// <summary> /// Options to configure analyzer execution within <see cref="CompilationWithAnalyzers"/>. /// </summary> public sealed class CompilationWithAnalyzersOptions { private readonly AnalyzerOptions? _options; private readonly Action<Exception, DiagnosticAnalyzer, Diagnostic>? _onAnalyzerException; private readonly Func<Exception, bool>? _analyzerExceptionFilter; private readonly bool _concurrentAnalysis; private readonly bool _logAnalyzerExecutionTime; private readonly bool _reportSuppressedDiagnostics; /// <summary> /// Options passed to <see cref="DiagnosticAnalyzer"/>s. /// </summary> public AnalyzerOptions? Options => _options; /// <summary> /// An optional delegate to be invoked when an analyzer throws an exception. /// </summary> public Action<Exception, DiagnosticAnalyzer, Diagnostic>? OnAnalyzerException => _onAnalyzerException; /// <summary> /// An optional delegate to be invoked when an analyzer throws an exception as an exception filter. /// </summary> public Func<Exception, bool>? AnalyzerExceptionFilter => _analyzerExceptionFilter; /// <summary> /// Flag indicating whether analysis can be performed concurrently on multiple threads. /// </summary> public bool ConcurrentAnalysis => _concurrentAnalysis; /// <summary> /// Flag indicating whether analyzer execution time should be logged. /// </summary> public bool LogAnalyzerExecutionTime => _logAnalyzerExecutionTime; /// <summary> /// Flag indicating whether analyzer diagnostics with <see cref="Diagnostic.IsSuppressed"/> should be reported. /// </summary> public bool ReportSuppressedDiagnostics => _reportSuppressedDiagnostics; /// <summary> /// Creates a new <see cref="CompilationWithAnalyzersOptions"/>. /// </summary> /// <param name="options">Options that are passed to analyzers.</param> /// <param name="onAnalyzerException">Action to invoke if an analyzer throws an exception.</param> /// <param name="concurrentAnalysis">Flag indicating whether analysis can be performed concurrently on multiple threads.</param> /// <param name="logAnalyzerExecutionTime">Flag indicating whether analyzer execution time should be logged.</param> public CompilationWithAnalyzersOptions( AnalyzerOptions options, Action<Exception, DiagnosticAnalyzer, Diagnostic>? onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime) : this(options, onAnalyzerException, concurrentAnalysis, logAnalyzerExecutionTime, reportSuppressedDiagnostics: false) { } /// <summary> /// Creates a new <see cref="CompilationWithAnalyzersOptions"/>. /// </summary> /// <param name="options">Options that are passed to analyzers.</param> /// <param name="onAnalyzerException">Action to invoke if an analyzer throws an exception.</param> /// <param name="concurrentAnalysis">Flag indicating whether analysis can be performed concurrently on multiple threads.</param> /// <param name="logAnalyzerExecutionTime">Flag indicating whether analyzer execution time should be logged.</param> /// <param name="reportSuppressedDiagnostics">Flag indicating whether analyzer diagnostics with <see cref="Diagnostic.IsSuppressed"/> should be reported.</param> public CompilationWithAnalyzersOptions( AnalyzerOptions options, Action<Exception, DiagnosticAnalyzer, Diagnostic>? onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime, bool reportSuppressedDiagnostics) : this(options, onAnalyzerException, concurrentAnalysis, logAnalyzerExecutionTime, reportSuppressedDiagnostics, analyzerExceptionFilter: null) { } /// <summary> /// Creates a new <see cref="CompilationWithAnalyzersOptions"/>. /// </summary> /// <param name="options">Options that are passed to analyzers.</param> /// <param name="onAnalyzerException">Action to invoke if an analyzer throws an exception.</param> /// <param name="analyzerExceptionFilter">Action to invoke if an analyzer throws an exception as an exception filter.</param> /// <param name="concurrentAnalysis">Flag indicating whether analysis can be performed concurrently on multiple threads.</param> /// <param name="logAnalyzerExecutionTime">Flag indicating whether analyzer execution time should be logged.</param> /// <param name="reportSuppressedDiagnostics">Flag indicating whether analyzer diagnostics with <see cref="Diagnostic.IsSuppressed"/> should be reported.</param> public CompilationWithAnalyzersOptions( AnalyzerOptions? options, Action<Exception, DiagnosticAnalyzer, Diagnostic>? onAnalyzerException, bool concurrentAnalysis, bool logAnalyzerExecutionTime, bool reportSuppressedDiagnostics, Func<Exception, bool>? analyzerExceptionFilter) { _options = options; _onAnalyzerException = onAnalyzerException; _analyzerExceptionFilter = analyzerExceptionFilter; _concurrentAnalysis = concurrentAnalysis; _logAnalyzerExecutionTime = logAnalyzerExecutionTime; _reportSuppressedDiagnostics = reportSuppressedDiagnostics; } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/VisualStudio/Core/Test/Progression/ProgressionTestHelpers.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.LanguageServices.CSharp.Progression Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Progression Imports <xmlns="http://schemas.microsoft.com/vs/2009/dgml"> Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression Friend Module ProgressionTestHelpers <Extension> Public Function ToSimplifiedXDocument(graph As Graph) As XDocument Dim document = XDocument.Parse(graph.ToXml(graphNodeIdAliasThreshold:=1000000)) document.Root.<Categories>.Remove() document.Root.<Properties>.Remove() document.Root.<QualifiedNames>.Remove() For Each node In document.Descendants(XName.Get("Node", "http://schemas.microsoft.com/vs/2009/dgml")) Dim attribute = node.Attribute("SourceLocation") If attribute IsNot Nothing Then attribute.Remove() End If Next Return document End Function Public Sub AssertSimplifiedGraphIs(graph As Graph, xml As XElement) Dim graphXml = graph.ToSimplifiedXDocument() If Not XNode.DeepEquals(graphXml.Root, xml) Then ' They aren't equal, so therefore the text representations definitely aren't equal. ' We'll Assert.Equal those, so that way xunit will show nice before/after text 'Assert.Equal(xml.ToString(), graphXml.ToString()) ' In an attempt to diagnose some flaky tests, the whole contents of both objects will be output Throw New Exception($"Graph XML was not equal, check for out-of-order elements. Expected: {xml.ToString()} Actual: {graphXml.ToString()} ") End If End Sub End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports Microsoft.CodeAnalysis.Editor.UnitTests Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.VisualStudio.Composition Imports Microsoft.VisualStudio.GraphModel Imports Microsoft.VisualStudio.LanguageServices.CSharp.Progression Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.Progression Imports <xmlns="http://schemas.microsoft.com/vs/2009/dgml"> Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression Friend Module ProgressionTestHelpers <Extension> Public Function ToSimplifiedXDocument(graph As Graph) As XDocument Dim document = XDocument.Parse(graph.ToXml(graphNodeIdAliasThreshold:=1000000)) document.Root.<Categories>.Remove() document.Root.<Properties>.Remove() document.Root.<QualifiedNames>.Remove() For Each node In document.Descendants(XName.Get("Node", "http://schemas.microsoft.com/vs/2009/dgml")) Dim attribute = node.Attribute("SourceLocation") If attribute IsNot Nothing Then attribute.Remove() End If Next Return document End Function Public Sub AssertSimplifiedGraphIs(graph As Graph, xml As XElement) Dim graphXml = graph.ToSimplifiedXDocument() If Not XNode.DeepEquals(graphXml.Root, xml) Then ' They aren't equal, so therefore the text representations definitely aren't equal. ' We'll Assert.Equal those, so that way xunit will show nice before/after text 'Assert.Equal(xml.ToString(), graphXml.ToString()) ' In an attempt to diagnose some flaky tests, the whole contents of both objects will be output Throw New Exception($"Graph XML was not equal, check for out-of-order elements. Expected: {xml.ToString()} Actual: {graphXml.ToString()} ") End If End Sub End Module End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Helpers/RemoveUnnecessaryImports/VisualBasicUnnecessaryImportsProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.RemoveUnnecessaryImports Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryImports Friend NotInheritable Class VisualBasicUnnecessaryImportsProvider Inherits AbstractUnnecessaryImportsProvider(Of ImportsClauseSyntax) Public Shared Instance As New VisualBasicUnnecessaryImportsProvider Private Sub New() End Sub Protected Overrides Function GetUnnecessaryImports( model As SemanticModel, root As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken) As ImmutableArray(Of SyntaxNode) predicate = If(predicate, Functions(Of SyntaxNode).True) Dim diagnostics = model.GetDiagnostics(cancellationToken:=cancellationToken) Dim unnecessaryImports = New HashSet(Of SyntaxNode) For Each diagnostic In diagnostics If diagnostic.Id = "BC50000" Then Dim node = root.FindNode(diagnostic.Location.SourceSpan) If node IsNot Nothing AndAlso predicate(node) Then unnecessaryImports.Add(node) End If End If If diagnostic.Id = "BC50001" Then Dim node = TryCast(root.FindNode(diagnostic.Location.SourceSpan), ImportsStatementSyntax) If node IsNot Nothing AndAlso predicate(node) Then unnecessaryImports.AddRange(node.ImportsClauses) End If End If Next Dim oldRoot = DirectCast(root, CompilationUnitSyntax) AddRedundantImports(oldRoot, model, unnecessaryImports, predicate, cancellationToken) Return unnecessaryImports.ToImmutableArray() End Function Private Shared Sub AddRedundantImports( compilationUnit As CompilationUnitSyntax, semanticModel As SemanticModel, unnecessaryImports As HashSet(Of SyntaxNode), predicate As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken) ' Now that we've visited the tree, add any imports that bound to project level ' imports. We definitely can remove them. For Each statement In compilationUnit.Imports For Each clause In statement.ImportsClauses cancellationToken.ThrowIfCancellationRequested() Dim simpleImportsClause = TryCast(clause, SimpleImportsClauseSyntax) If simpleImportsClause IsNot Nothing Then If simpleImportsClause.Alias Is Nothing Then AddRedundantMemberImportsClause(simpleImportsClause, semanticModel, unnecessaryImports, predicate, cancellationToken) Else AddRedundantAliasImportsClause(simpleImportsClause, semanticModel, unnecessaryImports, predicate, cancellationToken) End If End If Next Next End Sub Private Shared Sub AddRedundantAliasImportsClause( clause As SimpleImportsClauseSyntax, semanticModel As SemanticModel, unnecessaryImports As HashSet(Of SyntaxNode), predicate As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken) Dim semanticInfo = semanticModel.GetSymbolInfo(clause.Name, cancellationToken) Dim namespaceOrType = TryCast(semanticInfo.Symbol, INamespaceOrTypeSymbol) If namespaceOrType Is Nothing Then Return End If Dim compilation = semanticModel.Compilation Dim aliasSymbol = compilation.AliasImports.FirstOrDefault(Function(a) a.Name = clause.Alias.Identifier.ValueText) If aliasSymbol IsNot Nothing AndAlso aliasSymbol.Target.Equals(semanticInfo.Symbol) AndAlso predicate(clause) Then unnecessaryImports.Add(clause) End If End Sub Private Shared Sub AddRedundantMemberImportsClause( clause As SimpleImportsClauseSyntax, semanticModel As SemanticModel, unnecessaryImports As HashSet(Of SyntaxNode), predicate As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken) Dim semanticInfo = semanticModel.GetSymbolInfo(clause.Name, cancellationToken) Dim namespaceOrType = TryCast(semanticInfo.Symbol, INamespaceOrTypeSymbol) If namespaceOrType Is Nothing Then Return End If Dim compilation = semanticModel.Compilation If compilation.MemberImports.Contains(namespaceOrType) AndAlso predicate(clause) Then unnecessaryImports.Add(clause) End If End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Formatting Imports Microsoft.CodeAnalysis.RemoveUnnecessaryImports Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryImports Friend NotInheritable Class VisualBasicUnnecessaryImportsProvider Inherits AbstractUnnecessaryImportsProvider(Of ImportsClauseSyntax) Public Shared Instance As New VisualBasicUnnecessaryImportsProvider Private Sub New() End Sub Protected Overrides Function GetUnnecessaryImports( model As SemanticModel, root As SyntaxNode, predicate As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken) As ImmutableArray(Of SyntaxNode) predicate = If(predicate, Functions(Of SyntaxNode).True) Dim diagnostics = model.GetDiagnostics(cancellationToken:=cancellationToken) Dim unnecessaryImports = New HashSet(Of SyntaxNode) For Each diagnostic In diagnostics If diagnostic.Id = "BC50000" Then Dim node = root.FindNode(diagnostic.Location.SourceSpan) If node IsNot Nothing AndAlso predicate(node) Then unnecessaryImports.Add(node) End If End If If diagnostic.Id = "BC50001" Then Dim node = TryCast(root.FindNode(diagnostic.Location.SourceSpan), ImportsStatementSyntax) If node IsNot Nothing AndAlso predicate(node) Then unnecessaryImports.AddRange(node.ImportsClauses) End If End If Next Dim oldRoot = DirectCast(root, CompilationUnitSyntax) AddRedundantImports(oldRoot, model, unnecessaryImports, predicate, cancellationToken) Return unnecessaryImports.ToImmutableArray() End Function Private Shared Sub AddRedundantImports( compilationUnit As CompilationUnitSyntax, semanticModel As SemanticModel, unnecessaryImports As HashSet(Of SyntaxNode), predicate As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken) ' Now that we've visited the tree, add any imports that bound to project level ' imports. We definitely can remove them. For Each statement In compilationUnit.Imports For Each clause In statement.ImportsClauses cancellationToken.ThrowIfCancellationRequested() Dim simpleImportsClause = TryCast(clause, SimpleImportsClauseSyntax) If simpleImportsClause IsNot Nothing Then If simpleImportsClause.Alias Is Nothing Then AddRedundantMemberImportsClause(simpleImportsClause, semanticModel, unnecessaryImports, predicate, cancellationToken) Else AddRedundantAliasImportsClause(simpleImportsClause, semanticModel, unnecessaryImports, predicate, cancellationToken) End If End If Next Next End Sub Private Shared Sub AddRedundantAliasImportsClause( clause As SimpleImportsClauseSyntax, semanticModel As SemanticModel, unnecessaryImports As HashSet(Of SyntaxNode), predicate As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken) Dim semanticInfo = semanticModel.GetSymbolInfo(clause.Name, cancellationToken) Dim namespaceOrType = TryCast(semanticInfo.Symbol, INamespaceOrTypeSymbol) If namespaceOrType Is Nothing Then Return End If Dim compilation = semanticModel.Compilation Dim aliasSymbol = compilation.AliasImports.FirstOrDefault(Function(a) a.Name = clause.Alias.Identifier.ValueText) If aliasSymbol IsNot Nothing AndAlso aliasSymbol.Target.Equals(semanticInfo.Symbol) AndAlso predicate(clause) Then unnecessaryImports.Add(clause) End If End Sub Private Shared Sub AddRedundantMemberImportsClause( clause As SimpleImportsClauseSyntax, semanticModel As SemanticModel, unnecessaryImports As HashSet(Of SyntaxNode), predicate As Func(Of SyntaxNode, Boolean), cancellationToken As CancellationToken) Dim semanticInfo = semanticModel.GetSymbolInfo(clause.Name, cancellationToken) Dim namespaceOrType = TryCast(semanticInfo.Symbol, INamespaceOrTypeSymbol) If namespaceOrType Is Nothing Then Return End If Dim compilation = semanticModel.Compilation If compilation.MemberImports.Contains(namespaceOrType) AndAlso predicate(clause) Then unnecessaryImports.Add(clause) End If End Sub End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpReplClassification.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpReplClassification : AbstractInteractiveWindowTest { public CSharpReplClassification(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } [WpfFact] public void VerifyColorOfSomeTokens() { VisualStudio.InteractiveWindow.InsertCode(@"using System.Console; /// <summary>innertext /// </summary> /// <see cref=""System.Environment"" /> /// <!--comment--> /// <![CDATA[cdata]]]]>&gt; /// <typeparam name=""attribute"" /> public static void Main(string[] args) { WriteLine(""Hello World""); }"); VisualStudio.InteractiveWindow.PlaceCaret("using"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "keyword"); VisualStudio.InteractiveWindow.PlaceCaret("{"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "punctuation"); VisualStudio.InteractiveWindow.PlaceCaret("Main"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "method name"); VisualStudio.InteractiveWindow.PlaceCaret("Hello"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "string"); VisualStudio.InteractiveWindow.PlaceCaret("<summary", charsOffset: -1); VisualStudio.SendKeys.Send(new KeyPress(VirtualKey.Right, ShiftState.Alt)); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "xml doc comment - delimiter"); VisualStudio.InteractiveWindow.PlaceCaret("summary"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "xml doc comment - name"); VisualStudio.InteractiveWindow.PlaceCaret("innertext"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "xml doc comment - text"); VisualStudio.InteractiveWindow.PlaceCaret("!--"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "xml doc comment - delimiter"); VisualStudio.InteractiveWindow.PlaceCaret("comment"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "xml doc comment - comment"); VisualStudio.InteractiveWindow.PlaceCaret("CDATA"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "xml doc comment - delimiter"); VisualStudio.InteractiveWindow.PlaceCaret("cdata"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "xml doc comment - cdata section"); VisualStudio.InteractiveWindow.PlaceCaret("attribute"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "identifier"); VisualStudio.InteractiveWindow.PlaceCaret("Environment"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "class 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 Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpReplClassification : AbstractInteractiveWindowTest { public CSharpReplClassification(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } [WpfFact] public void VerifyColorOfSomeTokens() { VisualStudio.InteractiveWindow.InsertCode(@"using System.Console; /// <summary>innertext /// </summary> /// <see cref=""System.Environment"" /> /// <!--comment--> /// <![CDATA[cdata]]]]>&gt; /// <typeparam name=""attribute"" /> public static void Main(string[] args) { WriteLine(""Hello World""); }"); VisualStudio.InteractiveWindow.PlaceCaret("using"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "keyword"); VisualStudio.InteractiveWindow.PlaceCaret("{"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "punctuation"); VisualStudio.InteractiveWindow.PlaceCaret("Main"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "method name"); VisualStudio.InteractiveWindow.PlaceCaret("Hello"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "string"); VisualStudio.InteractiveWindow.PlaceCaret("<summary", charsOffset: -1); VisualStudio.SendKeys.Send(new KeyPress(VirtualKey.Right, ShiftState.Alt)); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "xml doc comment - delimiter"); VisualStudio.InteractiveWindow.PlaceCaret("summary"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "xml doc comment - name"); VisualStudio.InteractiveWindow.PlaceCaret("innertext"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "xml doc comment - text"); VisualStudio.InteractiveWindow.PlaceCaret("!--"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "xml doc comment - delimiter"); VisualStudio.InteractiveWindow.PlaceCaret("comment"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "xml doc comment - comment"); VisualStudio.InteractiveWindow.PlaceCaret("CDATA"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "xml doc comment - delimiter"); VisualStudio.InteractiveWindow.PlaceCaret("cdata"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "xml doc comment - cdata section"); VisualStudio.InteractiveWindow.PlaceCaret("attribute"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "identifier"); VisualStudio.InteractiveWindow.PlaceCaret("Environment"); VisualStudio.InteractiveWindow.Verify.CurrentTokenType(tokenType: "class name"); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Workspaces/Core/Portable/Options/IOptionPersister.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Exportable by a host to specify the save and restore behavior for a particular set of /// values. /// </summary> internal interface IOptionPersister { bool TryFetch(OptionKey optionKey, out object? value); bool TryPersist(OptionKey optionKey, object? value); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Exportable by a host to specify the save and restore behavior for a particular set of /// values. /// </summary> internal interface IOptionPersister { bool TryFetch(OptionKey optionKey, out object? value); bool TryPersist(OptionKey optionKey, object? value); } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/Emitter/Model/ExpandedVarargsMethodReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal sealed class ExpandedVarargsMethodReference : Cci.IMethodReference, Cci.IGenericMethodInstanceReference, Cci.ISpecializedMethodReference { private readonly Cci.IMethodReference _underlyingMethod; private readonly ImmutableArray<Cci.IParameterTypeInformation> _argListParams; public ExpandedVarargsMethodReference(Cci.IMethodReference underlyingMethod, ImmutableArray<Cci.IParameterTypeInformation> argListParams) { Debug.Assert(underlyingMethod.AcceptsExtraArguments); Debug.Assert(!argListParams.IsEmpty); _underlyingMethod = underlyingMethod; _argListParams = argListParams; } bool Cci.IMethodReference.AcceptsExtraArguments { get { return _underlyingMethod.AcceptsExtraArguments; } } ushort Cci.IMethodReference.GenericParameterCount { get { return _underlyingMethod.GenericParameterCount; } } bool Cci.IMethodReference.IsGeneric { get { return _underlyingMethod.IsGeneric; } } Cci.IMethodDefinition Cci.IMethodReference.GetResolvedMethod(EmitContext context) { return _underlyingMethod.GetResolvedMethod(context); } ImmutableArray<Cci.IParameterTypeInformation> Cci.IMethodReference.ExtraParameters { get { return _argListParams; } } Cci.IGenericMethodInstanceReference Cci.IMethodReference.AsGenericMethodInstanceReference { get { if (_underlyingMethod.AsGenericMethodInstanceReference == null) { return null; } Debug.Assert(_underlyingMethod.AsGenericMethodInstanceReference == _underlyingMethod); return this; } } Cci.ISpecializedMethodReference Cci.IMethodReference.AsSpecializedMethodReference { get { if (_underlyingMethod.AsSpecializedMethodReference == null) { return null; } Debug.Assert(_underlyingMethod.AsSpecializedMethodReference == _underlyingMethod); return this; } } Cci.CallingConvention Cci.ISignature.CallingConvention { get { return _underlyingMethod.CallingConvention; } } ushort Cci.ISignature.ParameterCount { get { return _underlyingMethod.ParameterCount; } } ImmutableArray<Cci.IParameterTypeInformation> Cci.ISignature.GetParameters(EmitContext context) { return _underlyingMethod.GetParameters(context); } ImmutableArray<Cci.ICustomModifier> Cci.ISignature.ReturnValueCustomModifiers { get { return _underlyingMethod.ReturnValueCustomModifiers; } } ImmutableArray<Cci.ICustomModifier> Cci.ISignature.RefCustomModifiers { get { return _underlyingMethod.RefCustomModifiers; } } bool Cci.ISignature.ReturnValueIsByRef { get { return _underlyingMethod.ReturnValueIsByRef; } } Cci.ITypeReference Cci.ISignature.GetType(EmitContext context) { return _underlyingMethod.GetType(context); } Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context) { return _underlyingMethod.GetContainingType(context); } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { return _underlyingMethod.GetAttributes(context); } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { if (((Cci.IMethodReference)this).AsGenericMethodInstanceReference != null) { visitor.Visit((Cci.IGenericMethodInstanceReference)this); } else if (((Cci.IMethodReference)this).AsSpecializedMethodReference != null) { visitor.Visit((Cci.ISpecializedMethodReference)this); } else { visitor.Visit((Cci.IMethodReference)this); } } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return null; } CodeAnalysis.Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; string Cci.INamedEntity.Name { get { return _underlyingMethod.Name; } } IEnumerable<Cci.ITypeReference> Cci.IGenericMethodInstanceReference.GetGenericArguments(EmitContext context) { return _underlyingMethod.AsGenericMethodInstanceReference.GetGenericArguments(context); } Cci.IMethodReference Cci.IGenericMethodInstanceReference.GetGenericMethod(EmitContext context) { return new ExpandedVarargsMethodReference(_underlyingMethod.AsGenericMethodInstanceReference.GetGenericMethod(context), _argListParams); } Cci.IMethodReference Cci.ISpecializedMethodReference.UnspecializedVersion { get { return new ExpandedVarargsMethodReference(_underlyingMethod.AsSpecializedMethodReference.UnspecializedVersion, _argListParams); } } public override string ToString() { var result = PooledStringBuilder.GetInstance(); Append(result, _underlyingMethod.GetInternalSymbol() ?? (object)_underlyingMethod); result.Builder.Append(" with __arglist( "); bool first = true; foreach (var p in _argListParams) { if (first) { first = false; } else { result.Builder.Append(", "); } if (p.IsByReference) { result.Builder.Append("ref "); } Append(result, p.GetType(new EmitContext())); } result.Builder.Append(")"); return result.ToStringAndFree(); } private static void Append(PooledStringBuilder result, object value) { Debug.Assert(!(value is ISymbol)); var symbol = (value as ISymbolInternal)?.GetISymbol(); if (symbol != null) { result.Builder.Append(symbol.ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat)); } else { result.Builder.Append(value); } } public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.CSharp.Emit { internal sealed class ExpandedVarargsMethodReference : Cci.IMethodReference, Cci.IGenericMethodInstanceReference, Cci.ISpecializedMethodReference { private readonly Cci.IMethodReference _underlyingMethod; private readonly ImmutableArray<Cci.IParameterTypeInformation> _argListParams; public ExpandedVarargsMethodReference(Cci.IMethodReference underlyingMethod, ImmutableArray<Cci.IParameterTypeInformation> argListParams) { Debug.Assert(underlyingMethod.AcceptsExtraArguments); Debug.Assert(!argListParams.IsEmpty); _underlyingMethod = underlyingMethod; _argListParams = argListParams; } bool Cci.IMethodReference.AcceptsExtraArguments { get { return _underlyingMethod.AcceptsExtraArguments; } } ushort Cci.IMethodReference.GenericParameterCount { get { return _underlyingMethod.GenericParameterCount; } } bool Cci.IMethodReference.IsGeneric { get { return _underlyingMethod.IsGeneric; } } Cci.IMethodDefinition Cci.IMethodReference.GetResolvedMethod(EmitContext context) { return _underlyingMethod.GetResolvedMethod(context); } ImmutableArray<Cci.IParameterTypeInformation> Cci.IMethodReference.ExtraParameters { get { return _argListParams; } } Cci.IGenericMethodInstanceReference Cci.IMethodReference.AsGenericMethodInstanceReference { get { if (_underlyingMethod.AsGenericMethodInstanceReference == null) { return null; } Debug.Assert(_underlyingMethod.AsGenericMethodInstanceReference == _underlyingMethod); return this; } } Cci.ISpecializedMethodReference Cci.IMethodReference.AsSpecializedMethodReference { get { if (_underlyingMethod.AsSpecializedMethodReference == null) { return null; } Debug.Assert(_underlyingMethod.AsSpecializedMethodReference == _underlyingMethod); return this; } } Cci.CallingConvention Cci.ISignature.CallingConvention { get { return _underlyingMethod.CallingConvention; } } ushort Cci.ISignature.ParameterCount { get { return _underlyingMethod.ParameterCount; } } ImmutableArray<Cci.IParameterTypeInformation> Cci.ISignature.GetParameters(EmitContext context) { return _underlyingMethod.GetParameters(context); } ImmutableArray<Cci.ICustomModifier> Cci.ISignature.ReturnValueCustomModifiers { get { return _underlyingMethod.ReturnValueCustomModifiers; } } ImmutableArray<Cci.ICustomModifier> Cci.ISignature.RefCustomModifiers { get { return _underlyingMethod.RefCustomModifiers; } } bool Cci.ISignature.ReturnValueIsByRef { get { return _underlyingMethod.ReturnValueIsByRef; } } Cci.ITypeReference Cci.ISignature.GetType(EmitContext context) { return _underlyingMethod.GetType(context); } Cci.ITypeReference Cci.ITypeMemberReference.GetContainingType(EmitContext context) { return _underlyingMethod.GetContainingType(context); } IEnumerable<Cci.ICustomAttribute> Cci.IReference.GetAttributes(EmitContext context) { return _underlyingMethod.GetAttributes(context); } void Cci.IReference.Dispatch(Cci.MetadataVisitor visitor) { if (((Cci.IMethodReference)this).AsGenericMethodInstanceReference != null) { visitor.Visit((Cci.IGenericMethodInstanceReference)this); } else if (((Cci.IMethodReference)this).AsSpecializedMethodReference != null) { visitor.Visit((Cci.ISpecializedMethodReference)this); } else { visitor.Visit((Cci.IMethodReference)this); } } Cci.IDefinition Cci.IReference.AsDefinition(EmitContext context) { return null; } CodeAnalysis.Symbols.ISymbolInternal Cci.IReference.GetInternalSymbol() => null; string Cci.INamedEntity.Name { get { return _underlyingMethod.Name; } } IEnumerable<Cci.ITypeReference> Cci.IGenericMethodInstanceReference.GetGenericArguments(EmitContext context) { return _underlyingMethod.AsGenericMethodInstanceReference.GetGenericArguments(context); } Cci.IMethodReference Cci.IGenericMethodInstanceReference.GetGenericMethod(EmitContext context) { return new ExpandedVarargsMethodReference(_underlyingMethod.AsGenericMethodInstanceReference.GetGenericMethod(context), _argListParams); } Cci.IMethodReference Cci.ISpecializedMethodReference.UnspecializedVersion { get { return new ExpandedVarargsMethodReference(_underlyingMethod.AsSpecializedMethodReference.UnspecializedVersion, _argListParams); } } public override string ToString() { var result = PooledStringBuilder.GetInstance(); Append(result, _underlyingMethod.GetInternalSymbol() ?? (object)_underlyingMethod); result.Builder.Append(" with __arglist( "); bool first = true; foreach (var p in _argListParams) { if (first) { first = false; } else { result.Builder.Append(", "); } if (p.IsByReference) { result.Builder.Append("ref "); } Append(result, p.GetType(new EmitContext())); } result.Builder.Append(")"); return result.ToStringAndFree(); } private static void Append(PooledStringBuilder result, object value) { Debug.Assert(!(value is ISymbol)); var symbol = (value as ISymbolInternal)?.GetISymbol(); if (symbol != null) { result.Builder.Append(symbol.ToDisplayString(SymbolDisplayFormat.ILVisualizationFormat)); } else { result.Builder.Append(value); } } public sealed override bool Equals(object obj) { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } public sealed override int GetHashCode() { // It is not supported to rely on default equality of these Cci objects, an explicit way to compare and hash them should be used. throw Roslyn.Utilities.ExceptionUtilities.Unreachable; } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/VisualStudioWorkspaceImpl.AbstractAddDocumentUndoUnit.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.OLE.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal partial class VisualStudioWorkspaceImpl { private abstract class AbstractAddDocumentUndoUnit : AbstractAddRemoveUndoUnit { protected readonly DocumentInfo DocumentInfo; protected readonly SourceText Text; protected AbstractAddDocumentUndoUnit( VisualStudioWorkspaceImpl workspace, DocumentInfo docInfo, SourceText text) : base(workspace, docInfo.Id.ProjectId) { DocumentInfo = docInfo; Text = text; } public override void Do(IOleUndoManager pUndoManager) { var currentSolution = Workspace.CurrentSolution; var fromProject = currentSolution.GetProject(FromProjectId); if (fromProject != null) { var updatedProject = AddDocument(fromProject); Workspace.TryApplyChanges(updatedProject.Solution); } } protected abstract Project AddDocument(Project fromProject); public override void GetDescription(out string pBstr) => pBstr = string.Format(FeaturesResources.Add_document_0, DocumentInfo.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. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.OLE.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem { internal partial class VisualStudioWorkspaceImpl { private abstract class AbstractAddDocumentUndoUnit : AbstractAddRemoveUndoUnit { protected readonly DocumentInfo DocumentInfo; protected readonly SourceText Text; protected AbstractAddDocumentUndoUnit( VisualStudioWorkspaceImpl workspace, DocumentInfo docInfo, SourceText text) : base(workspace, docInfo.Id.ProjectId) { DocumentInfo = docInfo; Text = text; } public override void Do(IOleUndoManager pUndoManager) { var currentSolution = Workspace.CurrentSolution; var fromProject = currentSolution.GetProject(FromProjectId); if (fromProject != null) { var updatedProject = AddDocument(fromProject); Workspace.TryApplyChanges(updatedProject.Solution); } } protected abstract Project AddDocument(Project fromProject); public override void GetDescription(out string pBstr) => pBstr = string.Format(FeaturesResources.Add_document_0, DocumentInfo.Name); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/CSharp/Portable/BoundTree/BoundMethodGroupFlags.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.CSharp { [Flags] internal enum BoundMethodGroupFlags { None = 0, SearchExtensionMethods = 1, /// <summary> /// Set if the group has a receiver but one was not specified in syntax. /// </summary> HasImplicitReceiver = 2, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.CSharp { [Flags] internal enum BoundMethodGroupFlags { None = 0, SearchExtensionMethods = 1, /// <summary> /// Set if the group has a receiver but one was not specified in syntax. /// </summary> HasImplicitReceiver = 2, } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/Core/IBraceMatchingService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor { internal interface IBraceMatchingService { Task<BraceMatchingResult?> GetMatchingBracesAsync(Document document, int position, CancellationToken cancellationToken = default); } internal struct BraceMatchingResult { public TextSpan LeftSpan { get; } public TextSpan RightSpan { get; } public BraceMatchingResult(TextSpan leftSpan, TextSpan rightSpan) : this() { this.LeftSpan = leftSpan; this.RightSpan = rightSpan; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor { internal interface IBraceMatchingService { Task<BraceMatchingResult?> GetMatchingBracesAsync(Document document, int position, CancellationToken cancellationToken = default); } internal struct BraceMatchingResult { public TextSpan LeftSpan { get; } public TextSpan RightSpan { get; } public BraceMatchingResult(TextSpan leftSpan, TextSpan rightSpan) : this() { this.LeftSpan = leftSpan; this.RightSpan = rightSpan; } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/TestUtilities/Threading/WpfTheoryTestCaseRunner.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using System.Threading; using Xunit.Abstractions; using Xunit.Sdk; namespace Roslyn.Test.Utilities { public class WpfTheoryTestCaseRunner : XunitTheoryTestCaseRunner { public WpfTestSharedData SharedData { get; } public WpfTheoryTestCaseRunner( WpfTestSharedData sharedData, IXunitTestCase testCase, string displayName, string skipReason, object[] constructorArguments, IMessageSink diagnosticMessageSink, IMessageBus messageBus, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) : base(testCase, displayName, skipReason, constructorArguments, diagnosticMessageSink, messageBus, aggregator, cancellationTokenSource) { SharedData = sharedData; } protected override XunitTestRunner CreateTestRunner(ITest test, IMessageBus messageBus, Type testClass, object[] constructorArguments, MethodInfo testMethod, object[] testMethodArguments, string skipReason, IReadOnlyList<BeforeAfterTestAttribute> beforeAfterAttributes, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) { var runner = new WpfTestRunner(SharedData, test, messageBus, testClass, constructorArguments, testMethod, testMethodArguments, skipReason, beforeAfterAttributes, aggregator, cancellationTokenSource); return runner; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection; using System.Threading; using Xunit.Abstractions; using Xunit.Sdk; namespace Roslyn.Test.Utilities { public class WpfTheoryTestCaseRunner : XunitTheoryTestCaseRunner { public WpfTestSharedData SharedData { get; } public WpfTheoryTestCaseRunner( WpfTestSharedData sharedData, IXunitTestCase testCase, string displayName, string skipReason, object[] constructorArguments, IMessageSink diagnosticMessageSink, IMessageBus messageBus, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) : base(testCase, displayName, skipReason, constructorArguments, diagnosticMessageSink, messageBus, aggregator, cancellationTokenSource) { SharedData = sharedData; } protected override XunitTestRunner CreateTestRunner(ITest test, IMessageBus messageBus, Type testClass, object[] constructorArguments, MethodInfo testMethod, object[] testMethodArguments, string skipReason, IReadOnlyList<BeforeAfterTestAttribute> beforeAfterAttributes, ExceptionAggregator aggregator, CancellationTokenSource cancellationTokenSource) { var runner = new WpfTestRunner(SharedData, test, messageBus, testClass, constructorArguments, testMethod, testMethodArguments, skipReason, beforeAfterAttributes, aggregator, cancellationTokenSource); return runner; } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Tools/PrepareTests/Program.cs
// Licensed to the .NET Foundation under one or more agreements. // 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 Mono.Options; internal static class Program { internal const int ExitFailure = 1; internal const int ExitSuccess = 0; public static int Main(string[] args) { string? source = null; string? destination = null; bool isUnix = false; var options = new OptionSet() { { "source=", "Path to binaries", (string s) => source = s }, { "destination=", "Output path", (string s) => destination = s }, { "unix", "If true, prepares tests for unix environment instead of Windows", o => isUnix = o is object } }; options.Parse(args); if (source is null) { Console.Error.WriteLine("--source argument must be provided"); return ExitFailure; } if (destination is null) { Console.Error.WriteLine("--destination argument must be provided"); return ExitFailure; } MinimizeUtil.Run(source, destination, isUnix); return ExitSuccess; } }
// Licensed to the .NET Foundation under one or more agreements. // 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 Mono.Options; internal static class Program { internal const int ExitFailure = 1; internal const int ExitSuccess = 0; public static int Main(string[] args) { string? source = null; string? destination = null; bool isUnix = false; var options = new OptionSet() { { "source=", "Path to binaries", (string s) => source = s }, { "destination=", "Output path", (string s) => destination = s }, { "unix", "If true, prepares tests for unix environment instead of Windows", o => isUnix = o is object } }; options.Parse(args); if (source is null) { Console.Error.WriteLine("--source argument must be provided"); return ExitFailure; } if (destination is null) { Console.Error.WriteLine("--destination argument must be provided"); return ExitFailure; } MinimizeUtil.Run(source, destination, isUnix); return ExitSuccess; } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/VisualBasic/Test/Emit/Emit/EditAndContinue/SymbolMatcherTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Roslyn.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports System.Threading.Tasks Imports System.Threading Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SymbolMatcherTests Inherits EditAndContinueTestBase <Fact> Public Sub ConcurrentAccess() Dim source = " Class A Dim F As B Property P As D Sub M(a As A, b As B, s As S, i As I) : End Sub Delegate Sub D(s As S) Class B : End Class Structure S : End Structure Interface I : End Interface End Class Class B Function M(Of T, U)() As A Return Nothing End Function Event E As D Delegate Sub D(s As S) Structure S : End Structure Interface I : End Interface End Class" Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() compilation0.VerifyDiagnostics() Dim builder = New List(Of Symbol)() Dim type = compilation1.GetMember(Of NamedTypeSymbol)("A") builder.Add(type) builder.AddRange(type.GetMembers()) type = compilation1.GetMember(Of NamedTypeSymbol)("B") builder.Add(type) builder.AddRange(type.GetMembers()) Dim members = builder.ToImmutableArray() Assert.True(members.Length > 10) For i = 0 To 10 - 1 Dim matcher = CreateMatcher(compilation1, compilation0) Dim tasks(10) As Task For j = 0 To tasks.Length - 1 Dim startAt As Integer = i + j + 1 tasks(j) = Task.Run(Sub() MatchAll(matcher, members, startAt) Thread.Sleep(10) End Sub) Next Task.WaitAll(tasks) Next End Sub Private Shared Sub MatchAll(matcher As VisualBasicSymbolMatcher, members As ImmutableArray(Of Symbol), startAt As Integer) Dim n As Integer = members.Length For i = 0 To n - 1 Dim member = members((i + startAt) Mod n) Dim other = matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IDefinition)) Assert.NotNull(other) Next End Sub <Fact> Public Sub TypeArguments() Dim source = " Class A(Of T) Class B(Of U) Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of Object).S) As A(Of V) Return Nothing End Function Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of V).S) As A(Of V) Return Nothing End Function End Class Structure S End Structure End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() compilation0.VerifyDiagnostics() Dim matcher = CreateMatcher(compilation1, compilation0) Dim members = compilation1.GetMember(Of NamedTypeSymbol)("A.B").GetMembers("M") Assert.Equal(members.Length, 2) For Each member In members Dim other = matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IMethodDefinition)) Assert.NotNull(other) Next End Sub <Fact> Public Sub Constraints() Dim source = " Interface I(Of T AS I(Of T)) End Interface Class C Shared Sub M(Of T As I(Of T))(o As I(Of T)) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source) Dim matcher = CreateMatcher(compilation1, compilation0) Dim member = compilation1.GetMember(Of MethodSymbol)("C.M") Dim other = matcher.MapDefinition(member.GetCciAdapter()) Assert.NotNull(other) End Sub <Fact> Public Sub CustomModifiers() Dim ilSource = " .class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object modopt(A) [] F(int32 modopt(object) p) { } } " Dim metadataRef = CompileIL(ilSource) Dim source = " Class B Inherits A Public Overrides Function F(p As Integer) As Object() Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, references:={metadataRef}) Dim compilation1 = compilation0.Clone() compilation0.VerifyDiagnostics() Dim member1 = compilation1.GetMember(Of MethodSymbol)("B.F") Assert.Equal(DirectCast(member1.ReturnType, ArrayTypeSymbol).CustomModifiers.Length, 1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim other = DirectCast(matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) Assert.Equal(DirectCast(other.ReturnType, ArrayTypeSymbol).CustomModifiers.Length, 1) End Sub <Fact> Public Sub VaryingCompilationReferences() Dim libSource = " Public Class D End Class " Dim source = " Public Class C Public Sub F(a As D) End Sub End Class " Dim lib0 = CreateCompilationWithMscorlib40({libSource}, options:=TestOptions.DebugDll, assemblyName:="Lib") Dim lib1 = CreateCompilationWithMscorlib40({libSource}, options:=TestOptions.DebugDll, assemblyName:="Lib") Dim compilation0 = CreateCompilationWithMscorlib40({source}, {lib0.ToMetadataReference()}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source).WithReferences(MscorlibRef, lib1.ToMetadataReference()) Dim matcher = CreateMatcher(compilation1, compilation0) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim mf1 = matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol() Assert.Equal(f0, mf1) End Sub <WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")> <Fact> Public Sub PreviousType_ArrayType() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As Integer = 0 End Sub Class D : End Class End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x() As D = Nothing End Sub Class D : End Class End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim elementType = compilation1.GetMember(Of TypeSymbol)("C.D") Dim member = compilation1.CreateArrayTypeSymbol(elementType) Dim other = matcher.MapReference(member.GetCciAdapter()) Assert.NotNull(other) End Sub <WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")> <Fact> Public Sub NoPreviousType_ArrayType() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As Integer = 0 End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x() As D = Nothing End Sub Class D : End Class End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim elementType = compilation1.GetMember(Of TypeSymbol)("C.D") Dim member = compilation1.CreateArrayTypeSymbol(elementType) Dim other = matcher.MapReference(member.GetCciAdapter()) ' For a newly added type, there is no match in the previous generation. Assert.Null(other) End Sub <WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")> <Fact> Public Sub NoPreviousType_GenericType() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Class C Shared Sub M() Dim x As Integer = 0 End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Class C Shared Sub M() Dim x As List(Of D) = Nothing End Sub Class D : End Class Dim y As List(Of D) End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim member = compilation1.GetMember(Of FieldSymbol)("C.y") Dim other = matcher.MapReference(DirectCast(member.Type.GetCciAdapter(), Cci.ITypeReference)) ' For a newly added type, there is no match in the previous generation. Assert.Null(other) End Sub <Fact> Public Sub HoistedAnonymousTypes() Dim source0 = " Imports System Class C Shared Sub F() Dim x1 = New With { .A = 1 } Dim x2 = New With { .B = 1 } Dim y = New Func(Of Integer)(Function() x1.A + x2.B) End Sub End Class " Dim source1 = " Imports System Class C Shared Sub F() Dim x1 = New With { .A = 1 } Dim x2 = New With { .C = 1 } Dim y = New Func(Of Integer)(Function() x1.A + x2.C) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll) Dim peRef0 = compilation0.EmitToImageReference() Dim peAssemblySymbol0 = DirectCast(CreateCompilationWithMscorlib40({""}, {peRef0}).GetReferencedAssemblySymbol(peRef0), PEAssemblySymbol) Dim peModule0 = DirectCast(peAssemblySymbol0.Modules(0), PEModuleSymbol) Dim reader0 = peModule0.Module.MetadataReader Dim decoder0 = New MetadataDecoder(peModule0) Dim anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0) Assert.Equal("VB$AnonymousType_0", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("A", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal("VB$AnonymousType_1", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("B", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal(2, anonymousTypeMap0.Count) Dim compilation1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim testData = New CompilationTestData() compilation1.EmitToArray(testData:=testData) Dim peAssemblyBuilder = DirectCast(testData.Module, PEAssemblyBuilder) Dim c = compilation1.GetMember(Of NamedTypeSymbol)("C") Dim displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single() Assert.Equal("_Closure$__1-0", displayClass.Name) Dim emitContext = New EmitContext(peAssemblyBuilder, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) Dim fields = displayClass.GetFields(emitContext).ToArray() Dim x1 = fields(0) Dim x2 = fields(1) Assert.Equal("$VB$Local_x1", x1.Name) Assert.Equal("$VB$Local_x2", x2.Name) Dim matcher = New VisualBasicSymbolMatcher( anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0) Dim mappedX1 = DirectCast(matcher.MapDefinition(x1), Cci.IFieldDefinition) Dim mappedX2 = DirectCast(matcher.MapDefinition(x2), Cci.IFieldDefinition) Assert.Equal("$VB$Local_x1", mappedX1.Name) Assert.Null(mappedX2) End Sub <Fact> Public Sub HoistedAnonymousTypes_Complex() Dim source0 = " Imports System Class C Shared Sub F() Dim x1 = { New With { .A = New With { .X = 1 } } } Dim x2 = { New With { .A = New With { .Y = 1 } } } Dim y = New Func(Of Integer)(Function() x1(0).A.X + x2(0).A.Y) End Sub End Class " Dim source1 = " Imports System Class C Shared Sub F() Dim x1 = { New With { .A = New With { .X = 1 } } } Dim x2 = { New With { .A = New With { .Z = 1 } } } Dim y = New Func(Of Integer)(Function() x1(0).A.X + x2(0).A.Z) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll) Dim peRef0 = compilation0.EmitToImageReference() Dim peAssemblySymbol0 = DirectCast(CreateCompilationWithMscorlib40({""}, {peRef0}).GetReferencedAssemblySymbol(peRef0), PEAssemblySymbol) Dim peModule0 = DirectCast(peAssemblySymbol0.Modules(0), PEModuleSymbol) Dim reader0 = peModule0.Module.MetadataReader Dim decoder0 = New MetadataDecoder(peModule0) Dim anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0) Assert.Equal("VB$AnonymousType_0", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("A", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal("VB$AnonymousType_1", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("X", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal("VB$AnonymousType_2", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("Y", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal(3, anonymousTypeMap0.Count) Dim compilation1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim testData = New CompilationTestData() compilation1.EmitToArray(testData:=testData) Dim peAssemblyBuilder = DirectCast(testData.Module, PEAssemblyBuilder) Dim c = compilation1.GetMember(Of NamedTypeSymbol)("C") Dim displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single() Assert.Equal("_Closure$__1-0", displayClass.Name) Dim emitContext = New EmitContext(peAssemblyBuilder, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) Dim fields = displayClass.GetFields(emitContext).ToArray() Dim x1 = fields(0) Dim x2 = fields(1) Assert.Equal("$VB$Local_x1", x1.Name) Assert.Equal("$VB$Local_x2", x2.Name) Dim matcher = New VisualBasicSymbolMatcher( anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0) Dim mappedX1 = DirectCast(matcher.MapDefinition(x1), Cci.IFieldDefinition) Dim mappedX2 = DirectCast(matcher.MapDefinition(x2), Cci.IFieldDefinition) Assert.Equal("$VB$Local_x1", mappedX1.Name) Assert.Null(mappedX2) End Sub <Fact> Public Sub HoistedAnonymousDelegate() Dim source0 = " Imports System Class C Shared Sub F() Dim x1 = Function(a As Integer) 1 Dim x2 = Function(b As Integer) 1 Dim y = New Func(Of Integer)(Function() x1(1) + x2(1)) End Sub End Class " Dim source1 = " Imports System Class C Shared Sub F() Dim x1 = Function(a As Integer) 1 Dim x2 = Function(c As Integer) 1 Dim y = New Func(Of Integer)(Function() x1(1) + x2(1)) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll) Dim peRef0 = compilation0.EmitToImageReference() Dim peAssemblySymbol0 = DirectCast(CreateCompilationWithMscorlib40({""}, {peRef0}).GetReferencedAssemblySymbol(peRef0), PEAssemblySymbol) Dim peModule0 = DirectCast(peAssemblySymbol0.Modules(0), PEModuleSymbol) Dim reader0 = peModule0.Module.MetadataReader Dim decoder0 = New MetadataDecoder(peModule0) Dim anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0) Assert.Equal("VB$AnonymousDelegate_0", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create( New AnonymousTypeKeyField("A", isKey:=False, ignoreCase:=True), New AnonymousTypeKeyField(AnonymousTypeDescriptor.FunctionReturnParameterName, isKey:=False, ignoreCase:=True)), isDelegate:=True)).Name) Assert.Equal("VB$AnonymousDelegate_1", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create( New AnonymousTypeKeyField("B", isKey:=False, ignoreCase:=True), New AnonymousTypeKeyField(AnonymousTypeDescriptor.FunctionReturnParameterName, isKey:=False, ignoreCase:=True)), isDelegate:=True)).Name) Assert.Equal(2, anonymousTypeMap0.Count) Dim compilation1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim testData = New CompilationTestData() compilation1.EmitToArray(testData:=testData) Dim peAssemblyBuilder = DirectCast(testData.Module, PEAssemblyBuilder) Dim c = compilation1.GetMember(Of NamedTypeSymbol)("C") Dim displayClasses = peAssemblyBuilder.GetSynthesizedTypes(c).ToArray() Assert.Equal("_Closure$__1-0", displayClasses(0).Name) Assert.Equal("_Closure$__", displayClasses(1).Name) Dim emitContext = New EmitContext(peAssemblyBuilder, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) Dim fields = displayClasses(0).GetFields(emitContext).ToArray() Dim x1 = fields(0) Dim x2 = fields(1) Assert.Equal("$VB$Local_x1", x1.Name) Assert.Equal("$VB$Local_x2", x2.Name) Dim matcher = New VisualBasicSymbolMatcher( anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0) Dim mappedX1 = DirectCast(matcher.MapDefinition(x1), Cci.IFieldDefinition) Dim mappedX2 = DirectCast(matcher.MapDefinition(x2), Cci.IFieldDefinition) Assert.Equal("$VB$Local_x1", mappedX1.Name) Assert.Null(mappedX2) End Sub <Fact> Public Sub Method_RenameParameter() Dim source0 = " Class C Public Function X(a As Integer) As Integer Return a End Function End Class " Dim source1 = " Class C Public Function X(b As Integer) As Integer Return b End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) Assert.NotNull(other) End Sub <Fact> Public Sub TupleField_TypeChange() Dim source0 = " Class C { Public x As (a As Integer, b As Integer) }" Dim source1 = " Class C { Public x As (a As Integer, b As Boolean) }" Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("C.x") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleField_NameChange() Dim source0 = " Class C { Public x As (a As Integer, b As Integer) }" Dim source1 = " Class C { Public x As (a As Integer, c As Integer) }" Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("C.x") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceFieldSymbol) Assert.NotNull(otherSymbol) Assert.Equal("C.x As (a As System.Int32, b As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleMethod_TypeToNoTupleChange() Dim source0 = " Class C Public Function X() As (a As Integer, b As Integer) Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As Integer() Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types should not match: one is tuple and another is not. Assert.Null(other) End Sub <Fact> Public Sub TupleMethod_TypeFromNoTupleChange() Dim source0 = " Class C Public Function X() As Integer() Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As (a As Integer, b As Boolean) Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types should not match: one is tuple and another is not. Assert.Null(other) End Sub <Fact> Public Sub TupleMethod_TypeChange() Dim source0 = " Class C Public Function X() As (a As Integer, b As Integer) Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As (a As Integer, b As Boolean) Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleMethod_NameChange() Dim source0 = " Class C Public Function X() As (a As Integer, b As Integer) Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As (a As Integer, c As Integer) Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceMemberMethodSymbol) Assert.NotNull(otherSymbol) Assert.Equal("Function C.X() As (a As System.Int32, b As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleProperty_TypeChange() Dim source0 = " Class C Public ReadOnly Property X As (a As Integer, b As Integer) Get Return Nothing End Get End Property End Class " Dim source1 = " Class C Public ReadOnly Property X As (a As Integer, b As Boolean) Get Return Nothing End Get End Property End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of PropertySymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleProperty_NameChange() Dim source0 = " Class C Public ReadOnly Property X As (a As Integer, b As Integer) Get Return Nothing End Get End Property End Class " Dim source1 = " Class C Public ReadOnly Property X As (a As Integer, c As Integer) Get Return Nothing End Get End Property End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of PropertySymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourcePropertySymbol) Assert.NotNull(otherSymbol) Assert.Equal("ReadOnly Property C.X As (a As System.Int32, b As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleStructField_TypeChange() Dim source0 = " Public Structure Vector Public Coordinates As (x As Integer, y As Integer) End Structure " Dim source1 = " Public Structure Vector Public Coordinates As (x As Integer, y As Integer, z As Integer) End Structure " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("Vector.Coordinates") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleStructField_NameChange() Dim source0 = " Public Structure Vector Public Coordinates As (x As Integer, y As Integer) End Structure " Dim source1 = " Public Structure Vector Public Coordinates As (x As Integer, z As Integer) End Structure " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("Vector.Coordinates") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceFieldSymbol) Assert.NotNull(otherSymbol) Assert.Equal("Vector.Coordinates As (x As System.Int32, y As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleDelegate_TypeChange() Dim source0 = " Public Class C Public Delegate Function F() As (Integer, Integer) End Class " Dim source1 = " Public Class C Public Delegate Function F() As (Integer, Boolean) End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of SourceNamedTypeSymbol)("C.F") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Tuple delegate defines a type. We should be able to match old and new types by name. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceNamedTypeSymbol) Assert.NotNull(otherSymbol) Assert.Equal("C.F", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleDelegate_NameChange() Dim source0 = " Public Class C Public Delegate Function F() As (x as Integer, y as Integer) End Class " Dim source1 = " Public Class C Public Delegate Function F() As (x as Integer, z as Integer) End Class" Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of SourceNamedTypeSymbol)("C.F") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceNamedTypeSymbol) Assert.NotNull(otherSymbol) Assert.Equal("C.F", otherSymbol.ToTestDisplayString()) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Emit Imports Roslyn.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports System.Threading.Tasks Imports System.Threading Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class SymbolMatcherTests Inherits EditAndContinueTestBase <Fact> Public Sub ConcurrentAccess() Dim source = " Class A Dim F As B Property P As D Sub M(a As A, b As B, s As S, i As I) : End Sub Delegate Sub D(s As S) Class B : End Class Structure S : End Structure Interface I : End Interface End Class Class B Function M(Of T, U)() As A Return Nothing End Function Event E As D Delegate Sub D(s As S) Structure S : End Structure Interface I : End Interface End Class" Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() compilation0.VerifyDiagnostics() Dim builder = New List(Of Symbol)() Dim type = compilation1.GetMember(Of NamedTypeSymbol)("A") builder.Add(type) builder.AddRange(type.GetMembers()) type = compilation1.GetMember(Of NamedTypeSymbol)("B") builder.Add(type) builder.AddRange(type.GetMembers()) Dim members = builder.ToImmutableArray() Assert.True(members.Length > 10) For i = 0 To 10 - 1 Dim matcher = CreateMatcher(compilation1, compilation0) Dim tasks(10) As Task For j = 0 To tasks.Length - 1 Dim startAt As Integer = i + j + 1 tasks(j) = Task.Run(Sub() MatchAll(matcher, members, startAt) Thread.Sleep(10) End Sub) Next Task.WaitAll(tasks) Next End Sub Private Shared Sub MatchAll(matcher As VisualBasicSymbolMatcher, members As ImmutableArray(Of Symbol), startAt As Integer) Dim n As Integer = members.Length For i = 0 To n - 1 Dim member = members((i + startAt) Mod n) Dim other = matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IDefinition)) Assert.NotNull(other) Next End Sub <Fact> Public Sub TypeArguments() Dim source = " Class A(Of T) Class B(Of U) Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of Object).S) As A(Of V) Return Nothing End Function Shared Function M(Of V)(x As A(Of U).B(Of T), y As A(Of V).S) As A(Of V) Return Nothing End Function End Class Structure S End Structure End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.Clone() compilation0.VerifyDiagnostics() Dim matcher = CreateMatcher(compilation1, compilation0) Dim members = compilation1.GetMember(Of NamedTypeSymbol)("A.B").GetMembers("M") Assert.Equal(members.Length, 2) For Each member In members Dim other = matcher.MapDefinition(DirectCast(member.GetCciAdapter(), Cci.IMethodDefinition)) Assert.NotNull(other) Next End Sub <Fact> Public Sub Constraints() Dim source = " Interface I(Of T AS I(Of T)) End Interface Class C Shared Sub M(Of T As I(Of T))(o As I(Of T)) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source) Dim matcher = CreateMatcher(compilation1, compilation0) Dim member = compilation1.GetMember(Of MethodSymbol)("C.M") Dim other = matcher.MapDefinition(member.GetCciAdapter()) Assert.NotNull(other) End Sub <Fact> Public Sub CustomModifiers() Dim ilSource = " .class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object modopt(A) [] F(int32 modopt(object) p) { } } " Dim metadataRef = CompileIL(ilSource) Dim source = " Class B Inherits A Public Overrides Function F(p As Integer) As Object() Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source}, options:=TestOptions.DebugDll, references:={metadataRef}) Dim compilation1 = compilation0.Clone() compilation0.VerifyDiagnostics() Dim member1 = compilation1.GetMember(Of MethodSymbol)("B.F") Assert.Equal(DirectCast(member1.ReturnType, ArrayTypeSymbol).CustomModifiers.Length, 1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim other = DirectCast(matcher.MapDefinition(member1.GetCciAdapter()).GetInternalSymbol(), MethodSymbol) Assert.NotNull(other) Assert.Equal(DirectCast(other.ReturnType, ArrayTypeSymbol).CustomModifiers.Length, 1) End Sub <Fact> Public Sub VaryingCompilationReferences() Dim libSource = " Public Class D End Class " Dim source = " Public Class C Public Sub F(a As D) End Sub End Class " Dim lib0 = CreateCompilationWithMscorlib40({libSource}, options:=TestOptions.DebugDll, assemblyName:="Lib") Dim lib1 = CreateCompilationWithMscorlib40({libSource}, options:=TestOptions.DebugDll, assemblyName:="Lib") Dim compilation0 = CreateCompilationWithMscorlib40({source}, {lib0.ToMetadataReference()}, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(source).WithReferences(MscorlibRef, lib1.ToMetadataReference()) Dim matcher = CreateMatcher(compilation1, compilation0) Dim f0 = compilation0.GetMember(Of MethodSymbol)("C.F") Dim f1 = compilation1.GetMember(Of MethodSymbol)("C.F") Dim mf1 = matcher.MapDefinition(f1.GetCciAdapter()).GetInternalSymbol() Assert.Equal(f0, mf1) End Sub <WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")> <Fact> Public Sub PreviousType_ArrayType() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As Integer = 0 End Sub Class D : End Class End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x() As D = Nothing End Sub Class D : End Class End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim elementType = compilation1.GetMember(Of TypeSymbol)("C.D") Dim member = compilation1.CreateArrayTypeSymbol(elementType) Dim other = matcher.MapReference(member.GetCciAdapter()) Assert.NotNull(other) End Sub <WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")> <Fact> Public Sub NoPreviousType_ArrayType() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x As Integer = 0 End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Class C Shared Sub M() Dim x() As D = Nothing End Sub Class D : End Class End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim elementType = compilation1.GetMember(Of TypeSymbol)("C.D") Dim member = compilation1.CreateArrayTypeSymbol(elementType) Dim other = matcher.MapReference(member.GetCciAdapter()) ' For a newly added type, there is no match in the previous generation. Assert.Null(other) End Sub <WorkItem(1533, "https://github.com/dotnet/roslyn/issues/1533")> <Fact> Public Sub NoPreviousType_GenericType() Dim sources0 = <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Class C Shared Sub M() Dim x As Integer = 0 End Sub End Class ]]></file> </compilation> Dim sources1 = <compilation> <file name="a.vb"><![CDATA[ Imports System.Collections.Generic Class C Shared Sub M() Dim x As List(Of D) = Nothing End Sub Class D : End Class Dim y As List(Of D) End Class ]]></file> </compilation> Dim compilation0 = CreateCompilationWithMscorlib40(sources0, options:=TestOptions.DebugDll) Dim compilation1 = compilation0.WithSource(sources1) Dim matcher = CreateMatcher(compilation1, compilation0) Dim member = compilation1.GetMember(Of FieldSymbol)("C.y") Dim other = matcher.MapReference(DirectCast(member.Type.GetCciAdapter(), Cci.ITypeReference)) ' For a newly added type, there is no match in the previous generation. Assert.Null(other) End Sub <Fact> Public Sub HoistedAnonymousTypes() Dim source0 = " Imports System Class C Shared Sub F() Dim x1 = New With { .A = 1 } Dim x2 = New With { .B = 1 } Dim y = New Func(Of Integer)(Function() x1.A + x2.B) End Sub End Class " Dim source1 = " Imports System Class C Shared Sub F() Dim x1 = New With { .A = 1 } Dim x2 = New With { .C = 1 } Dim y = New Func(Of Integer)(Function() x1.A + x2.C) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll) Dim peRef0 = compilation0.EmitToImageReference() Dim peAssemblySymbol0 = DirectCast(CreateCompilationWithMscorlib40({""}, {peRef0}).GetReferencedAssemblySymbol(peRef0), PEAssemblySymbol) Dim peModule0 = DirectCast(peAssemblySymbol0.Modules(0), PEModuleSymbol) Dim reader0 = peModule0.Module.MetadataReader Dim decoder0 = New MetadataDecoder(peModule0) Dim anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0) Assert.Equal("VB$AnonymousType_0", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("A", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal("VB$AnonymousType_1", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("B", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal(2, anonymousTypeMap0.Count) Dim compilation1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim testData = New CompilationTestData() compilation1.EmitToArray(testData:=testData) Dim peAssemblyBuilder = DirectCast(testData.Module, PEAssemblyBuilder) Dim c = compilation1.GetMember(Of NamedTypeSymbol)("C") Dim displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single() Assert.Equal("_Closure$__1-0", displayClass.Name) Dim emitContext = New EmitContext(peAssemblyBuilder, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) Dim fields = displayClass.GetFields(emitContext).ToArray() Dim x1 = fields(0) Dim x2 = fields(1) Assert.Equal("$VB$Local_x1", x1.Name) Assert.Equal("$VB$Local_x2", x2.Name) Dim matcher = New VisualBasicSymbolMatcher( anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0) Dim mappedX1 = DirectCast(matcher.MapDefinition(x1), Cci.IFieldDefinition) Dim mappedX2 = DirectCast(matcher.MapDefinition(x2), Cci.IFieldDefinition) Assert.Equal("$VB$Local_x1", mappedX1.Name) Assert.Null(mappedX2) End Sub <Fact> Public Sub HoistedAnonymousTypes_Complex() Dim source0 = " Imports System Class C Shared Sub F() Dim x1 = { New With { .A = New With { .X = 1 } } } Dim x2 = { New With { .A = New With { .Y = 1 } } } Dim y = New Func(Of Integer)(Function() x1(0).A.X + x2(0).A.Y) End Sub End Class " Dim source1 = " Imports System Class C Shared Sub F() Dim x1 = { New With { .A = New With { .X = 1 } } } Dim x2 = { New With { .A = New With { .Z = 1 } } } Dim y = New Func(Of Integer)(Function() x1(0).A.X + x2(0).A.Z) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll) Dim peRef0 = compilation0.EmitToImageReference() Dim peAssemblySymbol0 = DirectCast(CreateCompilationWithMscorlib40({""}, {peRef0}).GetReferencedAssemblySymbol(peRef0), PEAssemblySymbol) Dim peModule0 = DirectCast(peAssemblySymbol0.Modules(0), PEModuleSymbol) Dim reader0 = peModule0.Module.MetadataReader Dim decoder0 = New MetadataDecoder(peModule0) Dim anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0) Assert.Equal("VB$AnonymousType_0", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("A", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal("VB$AnonymousType_1", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("X", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal("VB$AnonymousType_2", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create(New AnonymousTypeKeyField("Y", isKey:=False, ignoreCase:=True)))).Name) Assert.Equal(3, anonymousTypeMap0.Count) Dim compilation1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim testData = New CompilationTestData() compilation1.EmitToArray(testData:=testData) Dim peAssemblyBuilder = DirectCast(testData.Module, PEAssemblyBuilder) Dim c = compilation1.GetMember(Of NamedTypeSymbol)("C") Dim displayClass = peAssemblyBuilder.GetSynthesizedTypes(c).Single() Assert.Equal("_Closure$__1-0", displayClass.Name) Dim emitContext = New EmitContext(peAssemblyBuilder, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) Dim fields = displayClass.GetFields(emitContext).ToArray() Dim x1 = fields(0) Dim x2 = fields(1) Assert.Equal("$VB$Local_x1", x1.Name) Assert.Equal("$VB$Local_x2", x2.Name) Dim matcher = New VisualBasicSymbolMatcher( anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0) Dim mappedX1 = DirectCast(matcher.MapDefinition(x1), Cci.IFieldDefinition) Dim mappedX2 = DirectCast(matcher.MapDefinition(x2), Cci.IFieldDefinition) Assert.Equal("$VB$Local_x1", mappedX1.Name) Assert.Null(mappedX2) End Sub <Fact> Public Sub HoistedAnonymousDelegate() Dim source0 = " Imports System Class C Shared Sub F() Dim x1 = Function(a As Integer) 1 Dim x2 = Function(b As Integer) 1 Dim y = New Func(Of Integer)(Function() x1(1) + x2(1)) End Sub End Class " Dim source1 = " Imports System Class C Shared Sub F() Dim x1 = Function(a As Integer) 1 Dim x2 = Function(c As Integer) 1 Dim y = New Func(Of Integer)(Function() x1(1) + x2(1)) End Sub End Class " Dim compilation0 = CreateCompilationWithMscorlib40({source0}, options:=TestOptions.DebugDll) Dim peRef0 = compilation0.EmitToImageReference() Dim peAssemblySymbol0 = DirectCast(CreateCompilationWithMscorlib40({""}, {peRef0}).GetReferencedAssemblySymbol(peRef0), PEAssemblySymbol) Dim peModule0 = DirectCast(peAssemblySymbol0.Modules(0), PEModuleSymbol) Dim reader0 = peModule0.Module.MetadataReader Dim decoder0 = New MetadataDecoder(peModule0) Dim anonymousTypeMap0 = PEDeltaAssemblyBuilder.GetAnonymousTypeMapFromMetadata(reader0, decoder0) Assert.Equal("VB$AnonymousDelegate_0", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create( New AnonymousTypeKeyField("A", isKey:=False, ignoreCase:=True), New AnonymousTypeKeyField(AnonymousTypeDescriptor.FunctionReturnParameterName, isKey:=False, ignoreCase:=True)), isDelegate:=True)).Name) Assert.Equal("VB$AnonymousDelegate_1", anonymousTypeMap0(New AnonymousTypeKey(ImmutableArray.Create( New AnonymousTypeKeyField("B", isKey:=False, ignoreCase:=True), New AnonymousTypeKeyField(AnonymousTypeDescriptor.FunctionReturnParameterName, isKey:=False, ignoreCase:=True)), isDelegate:=True)).Name) Assert.Equal(2, anonymousTypeMap0.Count) Dim compilation1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll) Dim testData = New CompilationTestData() compilation1.EmitToArray(testData:=testData) Dim peAssemblyBuilder = DirectCast(testData.Module, PEAssemblyBuilder) Dim c = compilation1.GetMember(Of NamedTypeSymbol)("C") Dim displayClasses = peAssemblyBuilder.GetSynthesizedTypes(c).ToArray() Assert.Equal("_Closure$__1-0", displayClasses(0).Name) Assert.Equal("_Closure$__", displayClasses(1).Name) Dim emitContext = New EmitContext(peAssemblyBuilder, Nothing, New DiagnosticBag(), metadataOnly:=False, includePrivateMembers:=True) Dim fields = displayClasses(0).GetFields(emitContext).ToArray() Dim x1 = fields(0) Dim x2 = fields(1) Assert.Equal("$VB$Local_x1", x1.Name) Assert.Equal("$VB$Local_x2", x2.Name) Dim matcher = New VisualBasicSymbolMatcher( anonymousTypeMap0, compilation1.SourceAssembly, emitContext, peAssemblySymbol0) Dim mappedX1 = DirectCast(matcher.MapDefinition(x1), Cci.IFieldDefinition) Dim mappedX2 = DirectCast(matcher.MapDefinition(x2), Cci.IFieldDefinition) Assert.Equal("$VB$Local_x1", mappedX1.Name) Assert.Null(mappedX2) End Sub <Fact> Public Sub Method_RenameParameter() Dim source0 = " Class C Public Function X(a As Integer) As Integer Return a End Function End Class " Dim source1 = " Class C Public Function X(b As Integer) As Integer Return b End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) Assert.NotNull(other) End Sub <Fact> Public Sub TupleField_TypeChange() Dim source0 = " Class C { Public x As (a As Integer, b As Integer) }" Dim source1 = " Class C { Public x As (a As Integer, b As Boolean) }" Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("C.x") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleField_NameChange() Dim source0 = " Class C { Public x As (a As Integer, b As Integer) }" Dim source1 = " Class C { Public x As (a As Integer, c As Integer) }" Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("C.x") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceFieldSymbol) Assert.NotNull(otherSymbol) Assert.Equal("C.x As (a As System.Int32, b As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleMethod_TypeToNoTupleChange() Dim source0 = " Class C Public Function X() As (a As Integer, b As Integer) Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As Integer() Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types should not match: one is tuple and another is not. Assert.Null(other) End Sub <Fact> Public Sub TupleMethod_TypeFromNoTupleChange() Dim source0 = " Class C Public Function X() As Integer() Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As (a As Integer, b As Boolean) Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types should not match: one is tuple and another is not. Assert.Null(other) End Sub <Fact> Public Sub TupleMethod_TypeChange() Dim source0 = " Class C Public Function X() As (a As Integer, b As Integer) Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As (a As Integer, b As Boolean) Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleMethod_NameChange() Dim source0 = " Class C Public Function X() As (a As Integer, b As Integer) Return Nothing End Function End Class " Dim source1 = " Class C Public Function X() As (a As Integer, c As Integer) Return Nothing End Function End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of MethodSymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceMemberMethodSymbol) Assert.NotNull(otherSymbol) Assert.Equal("Function C.X() As (a As System.Int32, b As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleProperty_TypeChange() Dim source0 = " Class C Public ReadOnly Property X As (a As Integer, b As Integer) Get Return Nothing End Get End Property End Class " Dim source1 = " Class C Public ReadOnly Property X As (a As Integer, b As Boolean) Get Return Nothing End Get End Property End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of PropertySymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleProperty_NameChange() Dim source0 = " Class C Public ReadOnly Property X As (a As Integer, b As Integer) Get Return Nothing End Get End Property End Class " Dim source1 = " Class C Public ReadOnly Property X As (a As Integer, c As Integer) Get Return Nothing End Get End Property End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of PropertySymbol)("C.X") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourcePropertySymbol) Assert.NotNull(otherSymbol) Assert.Equal("ReadOnly Property C.X As (a As System.Int32, b As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleStructField_TypeChange() Dim source0 = " Public Structure Vector Public Coordinates As (x As Integer, y As Integer) End Structure " Dim source1 = " Public Structure Vector Public Coordinates As (x As Integer, y As Integer, z As Integer) End Structure " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("Vector.Coordinates") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' If a type changes within a tuple, we do not expect types to match. Assert.Null(other) End Sub <Fact> Public Sub TupleStructField_NameChange() Dim source0 = " Public Structure Vector Public Coordinates As (x As Integer, y As Integer) End Structure " Dim source1 = " Public Structure Vector Public Coordinates As (x As Integer, z As Integer) End Structure " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of FieldSymbol)("Vector.Coordinates") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceFieldSymbol) Assert.NotNull(otherSymbol) Assert.Equal("Vector.Coordinates As (x As System.Int32, y As System.Int32)", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleDelegate_TypeChange() Dim source0 = " Public Class C Public Delegate Function F() As (Integer, Integer) End Class " Dim source1 = " Public Class C Public Delegate Function F() As (Integer, Boolean) End Class " Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of SourceNamedTypeSymbol)("C.F") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Tuple delegate defines a type. We should be able to match old and new types by name. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceNamedTypeSymbol) Assert.NotNull(otherSymbol) Assert.Equal("C.F", otherSymbol.ToTestDisplayString()) End Sub <Fact> Public Sub TupleDelegate_NameChange() Dim source0 = " Public Class C Public Delegate Function F() As (x as Integer, y as Integer) End Class " Dim source1 = " Public Class C Public Delegate Function F() As (x as Integer, z as Integer) End Class" Dim compilation0 = CreateCompilationWithMscorlib40(source0, options:=TestOptions.DebugDll, references:=ValueTupleRefs) Dim compilation1 = compilation0.WithSource(source1) Dim matcher = New VisualBasicSymbolMatcher( Nothing, compilation1.SourceAssembly, New EmitContext(), compilation0.SourceAssembly, New EmitContext(), Nothing) Dim member = compilation1.GetMember(Of SourceNamedTypeSymbol)("C.F") Dim other = matcher.MapDefinition(member.GetCciAdapter()) ' Types must match because just an element name was changed. Dim otherSymbol = DirectCast(other.GetInternalSymbol(), SourceNamedTypeSymbol) Assert.NotNull(otherSymbol) Assert.Equal("C.F", otherSymbol.ToTestDisplayString()) End Sub End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Features/Core/Portable/NavigateTo/RoslynNavigateToItem.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.IO; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.NavigateTo { /// <summary> /// Data about a navigate to match. Only intended for use by C# and VB. Carries enough rich information to /// rehydrate everything needed quickly on either the host or remote side. /// </summary> [DataContract] internal readonly struct RoslynNavigateToItem { [DataMember(Order = 0)] public readonly bool IsStale; [DataMember(Order = 1)] public readonly DocumentId DocumentId; [DataMember(Order = 2)] public readonly ImmutableArray<ProjectId> AdditionalMatchingProjects; [DataMember(Order = 3)] public readonly DeclaredSymbolInfo DeclaredSymbolInfo; /// <summary> /// Will be one of the values from <see cref="NavigateToItemKind"/>. /// </summary> [DataMember(Order = 4)] public readonly string Kind; [DataMember(Order = 5)] public readonly NavigateToMatchKind MatchKind; [DataMember(Order = 6)] public readonly bool IsCaseSensitive; [DataMember(Order = 7)] public readonly ImmutableArray<TextSpan> NameMatchSpans; public RoslynNavigateToItem( bool isStale, DocumentId documentId, ImmutableArray<ProjectId> additionalMatchingProjects, DeclaredSymbolInfo declaredSymbolInfo, string kind, NavigateToMatchKind matchKind, bool isCaseSensitive, ImmutableArray<TextSpan> nameMatchSpans) { IsStale = isStale; DocumentId = documentId; AdditionalMatchingProjects = additionalMatchingProjects; DeclaredSymbolInfo = declaredSymbolInfo; Kind = kind; MatchKind = matchKind; IsCaseSensitive = isCaseSensitive; NameMatchSpans = nameMatchSpans; } public async Task<INavigateToSearchResult?> TryCreateSearchResultAsync(Solution solution, CancellationToken cancellationToken) { if (IsStale) { // may refer to a document that doesn't exist anymore. Bail out gracefully in that case. var document = solution.GetDocument(DocumentId); if (document == null) return null; return new NavigateToSearchResult(this, document); } else { var document = await solution.GetRequiredDocumentAsync( DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); return new NavigateToSearchResult(this, document); } } private class NavigateToSearchResult : INavigateToSearchResult, INavigableItem { private static readonly char[] s_dotArray = { '.' }; private readonly RoslynNavigateToItem _item; private readonly Document _document; private readonly string _additionalInformation; public NavigateToSearchResult(RoslynNavigateToItem item, Document document) { _item = item; _document = document; _additionalInformation = ComputeAdditionalInformation(); } private string ComputeAdditionalInformation() { // For partial types, state what file they're in so the user can disambiguate the results. var combinedProjectName = ComputeCombinedProjectName(); return (_item.DeclaredSymbolInfo.IsPartial, IsNonNestedNamedType()) switch { (true, true) => string.Format(FeaturesResources._0_dash_1, _document.Name, combinedProjectName), (true, false) => string.Format(FeaturesResources.in_0_1_2, _item.DeclaredSymbolInfo.ContainerDisplayName, _document.Name, combinedProjectName), (false, true) => string.Format(FeaturesResources.project_0, combinedProjectName), (false, false) => string.Format(FeaturesResources.in_0_project_1, _item.DeclaredSymbolInfo.ContainerDisplayName, combinedProjectName), }; } private string ComputeCombinedProjectName() { // If there aren't any additional matches in other projects, we don't need to merge anything. if (_item.AdditionalMatchingProjects.Length > 0) { // First get the simple project name and flavor for the actual project we got a hit in. If we can't // figure this out, we can't create a merged name. var firstProject = _document.Project; var (firstProjectName, firstProjectFlavor) = firstProject.State.NameAndFlavor; if (firstProjectName != null) { var solution = firstProject.Solution; using var _ = ArrayBuilder<string>.GetInstance(out var flavors); flavors.Add(firstProjectFlavor!); // Now, do the same for the other projects where we had a match. As above, if we can't figure out the // simple name/flavor, or if the simple project name doesn't match the simple project name we started // with then we can't merge these. foreach (var additionalProjectId in _item.AdditionalMatchingProjects) { var additionalProject = solution.GetRequiredProject(additionalProjectId); var (projectName, projectFlavor) = additionalProject.State.NameAndFlavor; if (projectName == firstProjectName) flavors.Add(projectFlavor!); } flavors.RemoveDuplicates(); flavors.Sort(); return $"{firstProjectName} ({string.Join(", ", flavors)})"; } } // Couldn't compute a merged project name (or only had one project). Just return the name of hte project itself. return _document.Project.Name; } string INavigateToSearchResult.AdditionalInformation => _additionalInformation; private bool IsNonNestedNamedType() => !_item.DeclaredSymbolInfo.IsNestedType && IsNamedType(); private bool IsNamedType() { switch (_item.DeclaredSymbolInfo.Kind) { case DeclaredSymbolInfoKind.Class: case DeclaredSymbolInfoKind.Record: case DeclaredSymbolInfoKind.Enum: case DeclaredSymbolInfoKind.Interface: case DeclaredSymbolInfoKind.Module: case DeclaredSymbolInfoKind.Struct: case DeclaredSymbolInfoKind.RecordStruct: return true; default: return false; } } string INavigateToSearchResult.Kind => _item.Kind; NavigateToMatchKind INavigateToSearchResult.MatchKind => _item.MatchKind; bool INavigateToSearchResult.IsCaseSensitive => _item.IsCaseSensitive; string INavigateToSearchResult.Name => _item.DeclaredSymbolInfo.Name; ImmutableArray<TextSpan> INavigateToSearchResult.NameMatchSpans => _item.NameMatchSpans; string INavigateToSearchResult.SecondarySort { get { // For partial types, we break up the file name into pieces. i.e. If we have // Outer.cs and Outer.Inner.cs then we add "Outer" and "Outer Inner" to // the secondary sort string. That way "Outer.cs" will be weighted above // "Outer.Inner.cs" var fileName = Path.GetFileNameWithoutExtension(_document.FilePath ?? ""); using var _ = ArrayBuilder<string>.GetInstance(out var parts); parts.Add(_item.DeclaredSymbolInfo.ParameterCount.ToString("X4")); parts.Add(_item.DeclaredSymbolInfo.TypeParameterCount.ToString("X4")); parts.Add(_item.DeclaredSymbolInfo.Name); parts.AddRange(fileName.Split(s_dotArray)); return string.Join(" ", parts); } } string? INavigateToSearchResult.Summary => null; INavigableItem INavigateToSearchResult.NavigableItem => this; #region INavigableItem Glyph INavigableItem.Glyph => GetGlyph(_item.DeclaredSymbolInfo.Kind, _item.DeclaredSymbolInfo.Accessibility); private static Glyph GetPublicGlyph(DeclaredSymbolInfoKind kind) => kind switch { DeclaredSymbolInfoKind.Class => Glyph.ClassPublic, DeclaredSymbolInfoKind.Constant => Glyph.ConstantPublic, DeclaredSymbolInfoKind.Constructor => Glyph.MethodPublic, DeclaredSymbolInfoKind.Delegate => Glyph.DelegatePublic, DeclaredSymbolInfoKind.Enum => Glyph.EnumPublic, DeclaredSymbolInfoKind.EnumMember => Glyph.EnumMemberPublic, DeclaredSymbolInfoKind.Event => Glyph.EventPublic, DeclaredSymbolInfoKind.ExtensionMethod => Glyph.ExtensionMethodPublic, DeclaredSymbolInfoKind.Field => Glyph.FieldPublic, DeclaredSymbolInfoKind.Indexer => Glyph.PropertyPublic, DeclaredSymbolInfoKind.Interface => Glyph.InterfacePublic, DeclaredSymbolInfoKind.Method => Glyph.MethodPublic, DeclaredSymbolInfoKind.Module => Glyph.ModulePublic, DeclaredSymbolInfoKind.Property => Glyph.PropertyPublic, DeclaredSymbolInfoKind.Struct => Glyph.StructurePublic, DeclaredSymbolInfoKind.RecordStruct => Glyph.StructurePublic, _ => Glyph.ClassPublic, }; private static Glyph GetGlyph(DeclaredSymbolInfoKind kind, Accessibility accessibility) { // Glyphs are stored in this order: // ClassPublic, // ClassProtected, // ClassPrivate, // ClassInternal, var rawGlyph = GetPublicGlyph(kind); switch (accessibility) { case Accessibility.Private: rawGlyph += (Glyph.ClassPrivate - Glyph.ClassPublic); break; case Accessibility.Internal: rawGlyph += (Glyph.ClassInternal - Glyph.ClassPublic); break; case Accessibility.Protected: case Accessibility.ProtectedOrInternal: case Accessibility.ProtectedAndInternal: rawGlyph += (Glyph.ClassProtected - Glyph.ClassPublic); break; } return rawGlyph; } ImmutableArray<TaggedText> INavigableItem.DisplayTaggedParts => ImmutableArray.Create(new TaggedText( TextTags.Text, _item.DeclaredSymbolInfo.Name + _item.DeclaredSymbolInfo.NameSuffix)); bool INavigableItem.DisplayFileLocation => false; /// <summary> /// DeclaredSymbolInfos always come from some actual declaration in source. So they're /// never implicitly declared. /// </summary> bool INavigableItem.IsImplicitlyDeclared => false; Document INavigableItem.Document => _document; TextSpan INavigableItem.SourceSpan => _item.DeclaredSymbolInfo.Span; bool INavigableItem.IsStale => _item.IsStale; ImmutableArray<INavigableItem> INavigableItem.ChildItems => ImmutableArray<INavigableItem>.Empty; #endregion } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.NavigateTo { /// <summary> /// Data about a navigate to match. Only intended for use by C# and VB. Carries enough rich information to /// rehydrate everything needed quickly on either the host or remote side. /// </summary> [DataContract] internal readonly struct RoslynNavigateToItem { [DataMember(Order = 0)] public readonly bool IsStale; [DataMember(Order = 1)] public readonly DocumentId DocumentId; [DataMember(Order = 2)] public readonly ImmutableArray<ProjectId> AdditionalMatchingProjects; [DataMember(Order = 3)] public readonly DeclaredSymbolInfo DeclaredSymbolInfo; /// <summary> /// Will be one of the values from <see cref="NavigateToItemKind"/>. /// </summary> [DataMember(Order = 4)] public readonly string Kind; [DataMember(Order = 5)] public readonly NavigateToMatchKind MatchKind; [DataMember(Order = 6)] public readonly bool IsCaseSensitive; [DataMember(Order = 7)] public readonly ImmutableArray<TextSpan> NameMatchSpans; public RoslynNavigateToItem( bool isStale, DocumentId documentId, ImmutableArray<ProjectId> additionalMatchingProjects, DeclaredSymbolInfo declaredSymbolInfo, string kind, NavigateToMatchKind matchKind, bool isCaseSensitive, ImmutableArray<TextSpan> nameMatchSpans) { IsStale = isStale; DocumentId = documentId; AdditionalMatchingProjects = additionalMatchingProjects; DeclaredSymbolInfo = declaredSymbolInfo; Kind = kind; MatchKind = matchKind; IsCaseSensitive = isCaseSensitive; NameMatchSpans = nameMatchSpans; } public async Task<INavigateToSearchResult?> TryCreateSearchResultAsync(Solution solution, CancellationToken cancellationToken) { if (IsStale) { // may refer to a document that doesn't exist anymore. Bail out gracefully in that case. var document = solution.GetDocument(DocumentId); if (document == null) return null; return new NavigateToSearchResult(this, document); } else { var document = await solution.GetRequiredDocumentAsync( DocumentId, includeSourceGenerated: true, cancellationToken).ConfigureAwait(false); return new NavigateToSearchResult(this, document); } } private class NavigateToSearchResult : INavigateToSearchResult, INavigableItem { private static readonly char[] s_dotArray = { '.' }; private readonly RoslynNavigateToItem _item; private readonly Document _document; private readonly string _additionalInformation; public NavigateToSearchResult(RoslynNavigateToItem item, Document document) { _item = item; _document = document; _additionalInformation = ComputeAdditionalInformation(); } private string ComputeAdditionalInformation() { // For partial types, state what file they're in so the user can disambiguate the results. var combinedProjectName = ComputeCombinedProjectName(); return (_item.DeclaredSymbolInfo.IsPartial, IsNonNestedNamedType()) switch { (true, true) => string.Format(FeaturesResources._0_dash_1, _document.Name, combinedProjectName), (true, false) => string.Format(FeaturesResources.in_0_1_2, _item.DeclaredSymbolInfo.ContainerDisplayName, _document.Name, combinedProjectName), (false, true) => string.Format(FeaturesResources.project_0, combinedProjectName), (false, false) => string.Format(FeaturesResources.in_0_project_1, _item.DeclaredSymbolInfo.ContainerDisplayName, combinedProjectName), }; } private string ComputeCombinedProjectName() { // If there aren't any additional matches in other projects, we don't need to merge anything. if (_item.AdditionalMatchingProjects.Length > 0) { // First get the simple project name and flavor for the actual project we got a hit in. If we can't // figure this out, we can't create a merged name. var firstProject = _document.Project; var (firstProjectName, firstProjectFlavor) = firstProject.State.NameAndFlavor; if (firstProjectName != null) { var solution = firstProject.Solution; using var _ = ArrayBuilder<string>.GetInstance(out var flavors); flavors.Add(firstProjectFlavor!); // Now, do the same for the other projects where we had a match. As above, if we can't figure out the // simple name/flavor, or if the simple project name doesn't match the simple project name we started // with then we can't merge these. foreach (var additionalProjectId in _item.AdditionalMatchingProjects) { var additionalProject = solution.GetRequiredProject(additionalProjectId); var (projectName, projectFlavor) = additionalProject.State.NameAndFlavor; if (projectName == firstProjectName) flavors.Add(projectFlavor!); } flavors.RemoveDuplicates(); flavors.Sort(); return $"{firstProjectName} ({string.Join(", ", flavors)})"; } } // Couldn't compute a merged project name (or only had one project). Just return the name of hte project itself. return _document.Project.Name; } string INavigateToSearchResult.AdditionalInformation => _additionalInformation; private bool IsNonNestedNamedType() => !_item.DeclaredSymbolInfo.IsNestedType && IsNamedType(); private bool IsNamedType() { switch (_item.DeclaredSymbolInfo.Kind) { case DeclaredSymbolInfoKind.Class: case DeclaredSymbolInfoKind.Record: case DeclaredSymbolInfoKind.Enum: case DeclaredSymbolInfoKind.Interface: case DeclaredSymbolInfoKind.Module: case DeclaredSymbolInfoKind.Struct: case DeclaredSymbolInfoKind.RecordStruct: return true; default: return false; } } string INavigateToSearchResult.Kind => _item.Kind; NavigateToMatchKind INavigateToSearchResult.MatchKind => _item.MatchKind; bool INavigateToSearchResult.IsCaseSensitive => _item.IsCaseSensitive; string INavigateToSearchResult.Name => _item.DeclaredSymbolInfo.Name; ImmutableArray<TextSpan> INavigateToSearchResult.NameMatchSpans => _item.NameMatchSpans; string INavigateToSearchResult.SecondarySort { get { // For partial types, we break up the file name into pieces. i.e. If we have // Outer.cs and Outer.Inner.cs then we add "Outer" and "Outer Inner" to // the secondary sort string. That way "Outer.cs" will be weighted above // "Outer.Inner.cs" var fileName = Path.GetFileNameWithoutExtension(_document.FilePath ?? ""); using var _ = ArrayBuilder<string>.GetInstance(out var parts); parts.Add(_item.DeclaredSymbolInfo.ParameterCount.ToString("X4")); parts.Add(_item.DeclaredSymbolInfo.TypeParameterCount.ToString("X4")); parts.Add(_item.DeclaredSymbolInfo.Name); parts.AddRange(fileName.Split(s_dotArray)); return string.Join(" ", parts); } } string? INavigateToSearchResult.Summary => null; INavigableItem INavigateToSearchResult.NavigableItem => this; #region INavigableItem Glyph INavigableItem.Glyph => GetGlyph(_item.DeclaredSymbolInfo.Kind, _item.DeclaredSymbolInfo.Accessibility); private static Glyph GetPublicGlyph(DeclaredSymbolInfoKind kind) => kind switch { DeclaredSymbolInfoKind.Class => Glyph.ClassPublic, DeclaredSymbolInfoKind.Constant => Glyph.ConstantPublic, DeclaredSymbolInfoKind.Constructor => Glyph.MethodPublic, DeclaredSymbolInfoKind.Delegate => Glyph.DelegatePublic, DeclaredSymbolInfoKind.Enum => Glyph.EnumPublic, DeclaredSymbolInfoKind.EnumMember => Glyph.EnumMemberPublic, DeclaredSymbolInfoKind.Event => Glyph.EventPublic, DeclaredSymbolInfoKind.ExtensionMethod => Glyph.ExtensionMethodPublic, DeclaredSymbolInfoKind.Field => Glyph.FieldPublic, DeclaredSymbolInfoKind.Indexer => Glyph.PropertyPublic, DeclaredSymbolInfoKind.Interface => Glyph.InterfacePublic, DeclaredSymbolInfoKind.Method => Glyph.MethodPublic, DeclaredSymbolInfoKind.Module => Glyph.ModulePublic, DeclaredSymbolInfoKind.Property => Glyph.PropertyPublic, DeclaredSymbolInfoKind.Struct => Glyph.StructurePublic, DeclaredSymbolInfoKind.RecordStruct => Glyph.StructurePublic, _ => Glyph.ClassPublic, }; private static Glyph GetGlyph(DeclaredSymbolInfoKind kind, Accessibility accessibility) { // Glyphs are stored in this order: // ClassPublic, // ClassProtected, // ClassPrivate, // ClassInternal, var rawGlyph = GetPublicGlyph(kind); switch (accessibility) { case Accessibility.Private: rawGlyph += (Glyph.ClassPrivate - Glyph.ClassPublic); break; case Accessibility.Internal: rawGlyph += (Glyph.ClassInternal - Glyph.ClassPublic); break; case Accessibility.Protected: case Accessibility.ProtectedOrInternal: case Accessibility.ProtectedAndInternal: rawGlyph += (Glyph.ClassProtected - Glyph.ClassPublic); break; } return rawGlyph; } ImmutableArray<TaggedText> INavigableItem.DisplayTaggedParts => ImmutableArray.Create(new TaggedText( TextTags.Text, _item.DeclaredSymbolInfo.Name + _item.DeclaredSymbolInfo.NameSuffix)); bool INavigableItem.DisplayFileLocation => false; /// <summary> /// DeclaredSymbolInfos always come from some actual declaration in source. So they're /// never implicitly declared. /// </summary> bool INavigableItem.IsImplicitlyDeclared => false; Document INavigableItem.Document => _document; TextSpan INavigableItem.SourceSpan => _item.DeclaredSymbolInfo.Span; bool INavigableItem.IsStale => _item.IsStale; ImmutableArray<INavigableItem> INavigableItem.ChildItems => ImmutableArray<INavigableItem>.Empty; #endregion } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/AsyncKeywordRecommenderTests.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 AsyncKeywordRecommenderTests Inherits RecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub KeywordsAfterAsyncTest() VerifyRecommendationsAreExactly(<ClassDeclaration>Async |</ClassDeclaration>, "Friend", "Function", "Private", "Protected", "Protected Friend", "Public", "Sub") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInMethodStatementTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InMethodExpressionTest() VerifyRecommendationsContain(<MethodBody>Dim z = |</MethodBody>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FunctionDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AlreadyAsyncFunctionDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>| Async</ClassDeclaration>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SubDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>| Sub bar()</ClassDeclaration>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FunctionDeclarationInInterfaceTest() VerifyRecommendationsContain(<InterfaceDeclaration>|</InterfaceDeclaration>, "Async") End Sub <WorkItem(547254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547254")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterAsyncTest() VerifyRecommendationsMissing(<ClassDeclaration>Async |</ClassDeclaration>, "Async") End Sub <WorkItem(645060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645060")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterConstInClassTest() VerifyRecommendationsMissing(<ClassDeclaration>Const |</ClassDeclaration>, "Async") End Sub <WorkItem(645060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645060")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterConstInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>Const |</ModuleDeclaration>, "Async") End Sub <WorkItem(645060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645060")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterWithEventsInClassTest() VerifyRecommendationsMissing(<ClassDeclaration>WithEvents |</ClassDeclaration>, "Async") End Sub <WorkItem(645060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645060")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterWithEventsInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>WithEvents |</ModuleDeclaration>, "Async") End Sub <WorkItem(674791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674791")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterHashTest() VerifyRecommendationsMissing(<File> Imports System #| Module Module1 End Module </File>, "Async") 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 AsyncKeywordRecommenderTests Inherits RecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub KeywordsAfterAsyncTest() VerifyRecommendationsAreExactly(<ClassDeclaration>Async |</ClassDeclaration>, "Friend", "Function", "Private", "Protected", "Protected Friend", "Public", "Sub") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotInMethodStatementTest() VerifyRecommendationsMissing(<MethodBody>|</MethodBody>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub InMethodExpressionTest() VerifyRecommendationsContain(<MethodBody>Dim z = |</MethodBody>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FunctionDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>|</ClassDeclaration>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AlreadyAsyncFunctionDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>| Async</ClassDeclaration>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub SubDeclarationTest() VerifyRecommendationsContain(<ClassDeclaration>| Sub bar()</ClassDeclaration>, "Async") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FunctionDeclarationInInterfaceTest() VerifyRecommendationsContain(<InterfaceDeclaration>|</InterfaceDeclaration>, "Async") End Sub <WorkItem(547254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547254")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterAsyncTest() VerifyRecommendationsMissing(<ClassDeclaration>Async |</ClassDeclaration>, "Async") End Sub <WorkItem(645060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645060")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterConstInClassTest() VerifyRecommendationsMissing(<ClassDeclaration>Const |</ClassDeclaration>, "Async") End Sub <WorkItem(645060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645060")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterConstInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>Const |</ModuleDeclaration>, "Async") End Sub <WorkItem(645060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645060")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterWithEventsInClassTest() VerifyRecommendationsMissing(<ClassDeclaration>WithEvents |</ClassDeclaration>, "Async") End Sub <WorkItem(645060, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645060")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterWithEventsInModuleTest() VerifyRecommendationsMissing(<ModuleDeclaration>WithEvents |</ModuleDeclaration>, "Async") End Sub <WorkItem(674791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674791")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterHashTest() VerifyRecommendationsMissing(<File> Imports System #| Module Module1 End Module </File>, "Async") End Sub End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Analyzers/CSharp/CodeFixes/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.RemoveConfusingSuppression { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveConfusingSuppression), Shared] internal sealed partial class CSharpRemoveConfusingSuppressionCodeFixProvider : CodeFixProvider { public const string RemoveOperator = nameof(RemoveOperator); public const string NegateExpression = nameof(NegateExpression); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpRemoveConfusingSuppressionCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveConfusingSuppressionForIsExpressionDiagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostics = context.Diagnostics; var cancellationToken = context.CancellationToken; context.RegisterCodeFix( new MyCodeAction( CSharpAnalyzersResources.Remove_operator_preserves_semantics, c => FixAllAsync(document, diagnostics, negate: false, c), RemoveOperator), context.Diagnostics); context.RegisterCodeFix( new MyCodeAction( CSharpAnalyzersResources.Negate_expression_changes_semantics, c => FixAllAsync(document, diagnostics, negate: true, c), NegateExpression), context.Diagnostics); return Task.CompletedTask; } private static async Task<Document> FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, bool negate, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var generator = editor.Generator; var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>(); foreach (var diagnostic in diagnostics) { var node = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken); Debug.Assert(node.IsKind(SyntaxKind.IsExpression) || node.IsKind(SyntaxKind.IsPatternExpression)); // Negate the result if requested. var updatedNode = negate ? generator.Negate(generatorInternal, node, semanticModel, cancellationToken) : node; var isNode = updatedNode.DescendantNodesAndSelf().First( n => n.IsKind(SyntaxKind.IsExpression) || n.IsKind(SyntaxKind.IsPatternExpression)); var left = isNode switch { BinaryExpressionSyntax binary => binary.Left, IsPatternExpressionSyntax isPattern => isPattern.Expression, _ => throw ExceptionUtilities.UnexpectedValue(node), }; // Remove the suppression operator. var suppression = (PostfixUnaryExpressionSyntax)left; var withoutSuppression = suppression.Operand.WithAppendedTrailingTrivia(suppression.OperatorToken.GetAllTrivia()); var isWithoutSuppression = updatedNode.ReplaceNode(suppression, withoutSuppression); editor.ReplaceNode(node, isWithoutSuppression); } return document.WithSyntaxRoot(editor.GetChangedRoot()); } public override FixAllProvider GetFixAllProvider() => FixAllProvider.Create(async (context, document, diagnostics) => await FixAllAsync( document, diagnostics, context.CodeActionEquivalenceKey == NegateExpression, context.CancellationToken).ConfigureAwait(false)); private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(title, createChangedDocument, equivalenceKey) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.RemoveConfusingSuppression { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveConfusingSuppression), Shared] internal sealed partial class CSharpRemoveConfusingSuppressionCodeFixProvider : CodeFixProvider { public const string RemoveOperator = nameof(RemoveOperator); public const string NegateExpression = nameof(NegateExpression); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpRemoveConfusingSuppressionCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveConfusingSuppressionForIsExpressionDiagnosticId); public override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var diagnostics = context.Diagnostics; var cancellationToken = context.CancellationToken; context.RegisterCodeFix( new MyCodeAction( CSharpAnalyzersResources.Remove_operator_preserves_semantics, c => FixAllAsync(document, diagnostics, negate: false, c), RemoveOperator), context.Diagnostics); context.RegisterCodeFix( new MyCodeAction( CSharpAnalyzersResources.Negate_expression_changes_semantics, c => FixAllAsync(document, diagnostics, negate: true, c), NegateExpression), context.Diagnostics); return Task.CompletedTask; } private static async Task<Document> FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, bool negate, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(root, document.Project.Solution.Workspace); var generator = editor.Generator; var generatorInternal = document.GetRequiredLanguageService<SyntaxGeneratorInternal>(); foreach (var diagnostic in diagnostics) { var node = diagnostic.AdditionalLocations[0].FindNode(getInnermostNodeForTie: true, cancellationToken); Debug.Assert(node.IsKind(SyntaxKind.IsExpression) || node.IsKind(SyntaxKind.IsPatternExpression)); // Negate the result if requested. var updatedNode = negate ? generator.Negate(generatorInternal, node, semanticModel, cancellationToken) : node; var isNode = updatedNode.DescendantNodesAndSelf().First( n => n.IsKind(SyntaxKind.IsExpression) || n.IsKind(SyntaxKind.IsPatternExpression)); var left = isNode switch { BinaryExpressionSyntax binary => binary.Left, IsPatternExpressionSyntax isPattern => isPattern.Expression, _ => throw ExceptionUtilities.UnexpectedValue(node), }; // Remove the suppression operator. var suppression = (PostfixUnaryExpressionSyntax)left; var withoutSuppression = suppression.Operand.WithAppendedTrailingTrivia(suppression.OperatorToken.GetAllTrivia()); var isWithoutSuppression = updatedNode.ReplaceNode(suppression, withoutSuppression); editor.ReplaceNode(node, isWithoutSuppression); } return document.WithSyntaxRoot(editor.GetChangedRoot()); } public override FixAllProvider GetFixAllProvider() => FixAllProvider.Create(async (context, document, diagnostics) => await FixAllAsync( document, diagnostics, context.CodeActionEquivalenceKey == NegateExpression, context.CancellationToken).ConfigureAwait(false)); private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(title, createChangedDocument, equivalenceKey) { } } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./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 CanBeCapturedByLocalFunction { get; } public abstract bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken); public abstract SyntaxAnnotation IdentifierTokenAnnotation { get; } public abstract SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken); public abstract void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken); protected abstract int CompareTo(VariableSymbol right); /// <summary> /// return true if original type had anonymous type or delegate somewhere in the type /// </summary> public bool OriginalTypeHadAnonymousTypeOrDelegate { get; } /// <summary> /// get the original type with anonymous type removed /// </summary> public ITypeSymbol OriginalType { get; } public static int Compare( VariableSymbol left, VariableSymbol right, INamedTypeSymbol cancellationTokenType) { // CancellationTokens always go at the end of method signature. var leftIsCancellationToken = left.OriginalType.Equals(cancellationTokenType); var rightIsCancellationToken = right.OriginalType.Equals(cancellationTokenType); if (leftIsCancellationToken && !rightIsCancellationToken) { return 1; } else if (!leftIsCancellationToken && rightIsCancellationToken) { return -1; } if (left.DisplayOrder == right.DisplayOrder) { return left.CompareTo(right); } return left.DisplayOrder - right.DisplayOrder; } } protected abstract class NotMovableVariableSymbol : VariableSymbol { public NotMovableVariableSymbol(Compilation compilation, ITypeSymbol type) : base(compilation, type) { } public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken) { // decl never get moved return false; } public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken) => throw ExceptionUtilities.Unreachable; public override SyntaxAnnotation IdentifierTokenAnnotation => throw ExceptionUtilities.Unreachable; public override void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken) { // do nothing for parameter } } protected class ParameterVariableSymbol : NotMovableVariableSymbol, IComparable<ParameterVariableSymbol> { private readonly IParameterSymbol _parameterSymbol; public ParameterVariableSymbol(Compilation compilation, IParameterSymbol parameterSymbol, ITypeSymbol type) : base(compilation, type) { Contract.ThrowIfNull(parameterSymbol); _parameterSymbol = parameterSymbol; } public override int DisplayOrder => 0; protected override int CompareTo(VariableSymbol right) => CompareTo((ParameterVariableSymbol)right); public int CompareTo(ParameterVariableSymbol other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } var compare = CompareMethodParameters((IMethodSymbol)_parameterSymbol.ContainingSymbol, (IMethodSymbol)other._parameterSymbol.ContainingSymbol); if (compare != 0) { return compare; } Contract.ThrowIfFalse(_parameterSymbol.Ordinal != other._parameterSymbol.Ordinal); return (_parameterSymbol.Ordinal > other._parameterSymbol.Ordinal) ? 1 : -1; } private static int CompareMethodParameters(IMethodSymbol left, IMethodSymbol right) { if (left == null && right == null) { // not method parameters return 0; } if (left.Equals(right)) { // parameter of same method return 0; } // these methods can be either regular one, anonymous function, local function and etc // but all must belong to same outer regular method. // so, it should have location pointing to same tree var leftLocations = left.Locations; var rightLocations = right.Locations; var commonTree = leftLocations.Select(l => l.SourceTree).Intersect(rightLocations.Select(l => l.SourceTree)).WhereNotNull().First(); var leftLocation = leftLocations.First(l => l.SourceTree == commonTree); var rightLocation = rightLocations.First(l => l.SourceTree == commonTree); return leftLocation.SourceSpan.Start - rightLocation.SourceSpan.Start; } public override string Name { get { return _parameterSymbol.ToDisplayString( new SymbolDisplayFormat( parameterOptions: SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } public override bool CanBeCapturedByLocalFunction => true; } protected class LocalVariableSymbol<T> : VariableSymbol, IComparable<LocalVariableSymbol<T>> where T : SyntaxNode { private readonly SyntaxAnnotation _annotation; private readonly ILocalSymbol _localSymbol; private readonly HashSet<int> _nonNoisySet; public LocalVariableSymbol(Compilation compilation, ILocalSymbol localSymbol, ITypeSymbol type, HashSet<int> nonNoisySet) : base(compilation, type) { Contract.ThrowIfNull(localSymbol); Contract.ThrowIfNull(nonNoisySet); _annotation = new SyntaxAnnotation(); _localSymbol = localSymbol; _nonNoisySet = nonNoisySet; } public override int DisplayOrder => 1; protected override int CompareTo(VariableSymbol right) => CompareTo((LocalVariableSymbol<T>)right); public int CompareTo(LocalVariableSymbol<T> other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(other._localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource); Contract.ThrowIfFalse(other._localSymbol.Locations[0].IsInSource); Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceTree == other._localSymbol.Locations[0].SourceTree); Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceSpan.Start != other._localSymbol.Locations[0].SourceSpan.Start); return _localSymbol.Locations[0].SourceSpan.Start - other._localSymbol.Locations[0].SourceSpan.Start; } public override string Name { get { return _localSymbol.ToDisplayString( new SymbolDisplayFormat( miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken) { Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource); Contract.ThrowIfNull(_localSymbol.Locations[0].SourceTree); var tree = _localSymbol.Locations[0].SourceTree; var span = _localSymbol.Locations[0].SourceSpan; var token = tree.GetRoot(cancellationToken).FindToken(span.Start); Contract.ThrowIfFalse(token.Span.Equals(span)); return token; } public override SyntaxAnnotation IdentifierTokenAnnotation => _annotation; public override bool CanBeCapturedByLocalFunction => true; public override void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken) { annotations.Add(Tuple.Create(GetOriginalIdentifierToken(cancellationToken), _annotation)); } public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken) { var identifier = GetOriginalIdentifierToken(cancellationToken); // check whether there is a noisy trivia around the token. if (ContainsNoisyTrivia(identifier.LeadingTrivia)) { return true; } if (ContainsNoisyTrivia(identifier.TrailingTrivia)) { return true; } var declStatement = identifier.Parent.FirstAncestorOrSelf<T>(); if (declStatement == null) { return true; } foreach (var token in declStatement.DescendantTokens()) { if (ContainsNoisyTrivia(token.LeadingTrivia)) { return true; } if (ContainsNoisyTrivia(token.TrailingTrivia)) { return true; } } return false; } private bool ContainsNoisyTrivia(SyntaxTriviaList list) => list.Any(t => !_nonNoisySet.Contains(t.RawKind)); } protected class QueryVariableSymbol : NotMovableVariableSymbol, IComparable<QueryVariableSymbol> { private readonly IRangeVariableSymbol _symbol; public QueryVariableSymbol(Compilation compilation, IRangeVariableSymbol symbol, ITypeSymbol type) : base(compilation, type) { Contract.ThrowIfNull(symbol); _symbol = symbol; } public override int DisplayOrder => 2; protected override int CompareTo(VariableSymbol right) => CompareTo((QueryVariableSymbol)right); public int CompareTo(QueryVariableSymbol other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } var locationLeft = _symbol.Locations.First(); var locationRight = other._symbol.Locations.First(); Contract.ThrowIfFalse(locationLeft.IsInSource); Contract.ThrowIfFalse(locationRight.IsInSource); Contract.ThrowIfFalse(locationLeft.SourceTree == locationRight.SourceTree); Contract.ThrowIfFalse(locationLeft.SourceSpan.Start != locationRight.SourceSpan.Start); return locationLeft.SourceSpan.Start - locationRight.SourceSpan.Start; } public override string Name { get { return _symbol.ToDisplayString( new SymbolDisplayFormat( miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } public override bool CanBeCapturedByLocalFunction => false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { /// <summary> /// temporary symbol until we have a symbol that can hold onto both local and parameter symbol /// </summary> protected abstract class VariableSymbol { protected VariableSymbol(Compilation compilation, ITypeSymbol type) { OriginalTypeHadAnonymousTypeOrDelegate = type.ContainsAnonymousType(); OriginalType = OriginalTypeHadAnonymousTypeOrDelegate ? type.RemoveAnonymousTypes(compilation) : type; } public abstract int DisplayOrder { get; } public abstract string Name { get; } public abstract bool CanBeCapturedByLocalFunction { get; } public abstract bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken); public abstract SyntaxAnnotation IdentifierTokenAnnotation { get; } public abstract SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken); public abstract void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken); protected abstract int CompareTo(VariableSymbol right); /// <summary> /// return true if original type had anonymous type or delegate somewhere in the type /// </summary> public bool OriginalTypeHadAnonymousTypeOrDelegate { get; } /// <summary> /// get the original type with anonymous type removed /// </summary> public ITypeSymbol OriginalType { get; } public static int Compare( VariableSymbol left, VariableSymbol right, INamedTypeSymbol cancellationTokenType) { // CancellationTokens always go at the end of method signature. var leftIsCancellationToken = left.OriginalType.Equals(cancellationTokenType); var rightIsCancellationToken = right.OriginalType.Equals(cancellationTokenType); if (leftIsCancellationToken && !rightIsCancellationToken) { return 1; } else if (!leftIsCancellationToken && rightIsCancellationToken) { return -1; } if (left.DisplayOrder == right.DisplayOrder) { return left.CompareTo(right); } return left.DisplayOrder - right.DisplayOrder; } } protected abstract class NotMovableVariableSymbol : VariableSymbol { public NotMovableVariableSymbol(Compilation compilation, ITypeSymbol type) : base(compilation, type) { } public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken) { // decl never get moved return false; } public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken) => throw ExceptionUtilities.Unreachable; public override SyntaxAnnotation IdentifierTokenAnnotation => throw ExceptionUtilities.Unreachable; public override void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken) { // do nothing for parameter } } protected class ParameterVariableSymbol : NotMovableVariableSymbol, IComparable<ParameterVariableSymbol> { private readonly IParameterSymbol _parameterSymbol; public ParameterVariableSymbol(Compilation compilation, IParameterSymbol parameterSymbol, ITypeSymbol type) : base(compilation, type) { Contract.ThrowIfNull(parameterSymbol); _parameterSymbol = parameterSymbol; } public override int DisplayOrder => 0; protected override int CompareTo(VariableSymbol right) => CompareTo((ParameterVariableSymbol)right); public int CompareTo(ParameterVariableSymbol other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } var compare = CompareMethodParameters((IMethodSymbol)_parameterSymbol.ContainingSymbol, (IMethodSymbol)other._parameterSymbol.ContainingSymbol); if (compare != 0) { return compare; } Contract.ThrowIfFalse(_parameterSymbol.Ordinal != other._parameterSymbol.Ordinal); return (_parameterSymbol.Ordinal > other._parameterSymbol.Ordinal) ? 1 : -1; } private static int CompareMethodParameters(IMethodSymbol left, IMethodSymbol right) { if (left == null && right == null) { // not method parameters return 0; } if (left.Equals(right)) { // parameter of same method return 0; } // these methods can be either regular one, anonymous function, local function and etc // but all must belong to same outer regular method. // so, it should have location pointing to same tree var leftLocations = left.Locations; var rightLocations = right.Locations; var commonTree = leftLocations.Select(l => l.SourceTree).Intersect(rightLocations.Select(l => l.SourceTree)).WhereNotNull().First(); var leftLocation = leftLocations.First(l => l.SourceTree == commonTree); var rightLocation = rightLocations.First(l => l.SourceTree == commonTree); return leftLocation.SourceSpan.Start - rightLocation.SourceSpan.Start; } public override string Name { get { return _parameterSymbol.ToDisplayString( new SymbolDisplayFormat( parameterOptions: SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } public override bool CanBeCapturedByLocalFunction => true; } protected class LocalVariableSymbol<T> : VariableSymbol, IComparable<LocalVariableSymbol<T>> where T : SyntaxNode { private readonly SyntaxAnnotation _annotation; private readonly ILocalSymbol _localSymbol; private readonly HashSet<int> _nonNoisySet; public LocalVariableSymbol(Compilation compilation, ILocalSymbol localSymbol, ITypeSymbol type, HashSet<int> nonNoisySet) : base(compilation, type) { Contract.ThrowIfNull(localSymbol); Contract.ThrowIfNull(nonNoisySet); _annotation = new SyntaxAnnotation(); _localSymbol = localSymbol; _nonNoisySet = nonNoisySet; } public override int DisplayOrder => 1; protected override int CompareTo(VariableSymbol right) => CompareTo((LocalVariableSymbol<T>)right); public int CompareTo(LocalVariableSymbol<T> other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(other._localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource); Contract.ThrowIfFalse(other._localSymbol.Locations[0].IsInSource); Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceTree == other._localSymbol.Locations[0].SourceTree); Contract.ThrowIfFalse(_localSymbol.Locations[0].SourceSpan.Start != other._localSymbol.Locations[0].SourceSpan.Start); return _localSymbol.Locations[0].SourceSpan.Start - other._localSymbol.Locations[0].SourceSpan.Start; } public override string Name { get { return _localSymbol.ToDisplayString( new SymbolDisplayFormat( miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } public override SyntaxToken GetOriginalIdentifierToken(CancellationToken cancellationToken) { Contract.ThrowIfFalse(_localSymbol.Locations.Length == 1); Contract.ThrowIfFalse(_localSymbol.Locations[0].IsInSource); Contract.ThrowIfNull(_localSymbol.Locations[0].SourceTree); var tree = _localSymbol.Locations[0].SourceTree; var span = _localSymbol.Locations[0].SourceSpan; var token = tree.GetRoot(cancellationToken).FindToken(span.Start); Contract.ThrowIfFalse(token.Span.Equals(span)); return token; } public override SyntaxAnnotation IdentifierTokenAnnotation => _annotation; public override bool CanBeCapturedByLocalFunction => true; public override void AddIdentifierTokenAnnotationPair( List<Tuple<SyntaxToken, SyntaxAnnotation>> annotations, CancellationToken cancellationToken) { annotations.Add(Tuple.Create(GetOriginalIdentifierToken(cancellationToken), _annotation)); } public override bool GetUseSaferDeclarationBehavior(CancellationToken cancellationToken) { var identifier = GetOriginalIdentifierToken(cancellationToken); // check whether there is a noisy trivia around the token. if (ContainsNoisyTrivia(identifier.LeadingTrivia)) { return true; } if (ContainsNoisyTrivia(identifier.TrailingTrivia)) { return true; } var declStatement = identifier.Parent.FirstAncestorOrSelf<T>(); if (declStatement == null) { return true; } foreach (var token in declStatement.DescendantTokens()) { if (ContainsNoisyTrivia(token.LeadingTrivia)) { return true; } if (ContainsNoisyTrivia(token.TrailingTrivia)) { return true; } } return false; } private bool ContainsNoisyTrivia(SyntaxTriviaList list) => list.Any(t => !_nonNoisySet.Contains(t.RawKind)); } protected class QueryVariableSymbol : NotMovableVariableSymbol, IComparable<QueryVariableSymbol> { private readonly IRangeVariableSymbol _symbol; public QueryVariableSymbol(Compilation compilation, IRangeVariableSymbol symbol, ITypeSymbol type) : base(compilation, type) { Contract.ThrowIfNull(symbol); _symbol = symbol; } public override int DisplayOrder => 2; protected override int CompareTo(VariableSymbol right) => CompareTo((QueryVariableSymbol)right); public int CompareTo(QueryVariableSymbol other) { Contract.ThrowIfNull(other); if (this == other) { return 0; } var locationLeft = _symbol.Locations.First(); var locationRight = other._symbol.Locations.First(); Contract.ThrowIfFalse(locationLeft.IsInSource); Contract.ThrowIfFalse(locationRight.IsInSource); Contract.ThrowIfFalse(locationLeft.SourceTree == locationRight.SourceTree); Contract.ThrowIfFalse(locationLeft.SourceSpan.Start != locationRight.SourceSpan.Start); return locationLeft.SourceSpan.Start - locationRight.SourceSpan.Start; } public override string Name { get { return _symbol.ToDisplayString( new SymbolDisplayFormat( miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers)); } } public override bool CanBeCapturedByLocalFunction => false; } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Features/Core/Portable/GenerateMember/GenerateParameterizedMember/IGenerateParameterizedMemberService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember { internal interface IGenerateParameterizedMemberService : ILanguageService { Task<ImmutableArray<CodeAction>> GenerateMethodAsync(Document document, SyntaxNode node, 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.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember { internal interface IGenerateParameterizedMemberService : ILanguageService { Task<ImmutableArray<CodeAction>> GenerateMethodAsync(Document document, SyntaxNode node, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Analyzers/VisualBasic/Analyzers/RemoveUnnecessarySuppressions/VisualBasicRemoveUnnecessaryPragmaSuppressionsDiagnosticAnalyzer.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.Reflection Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessarySuppressions #If Not CODE_STYLE Then ' Not exported in CodeStyle layer: https://github.com/dotnet/roslyn/issues/47942 <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend NotInheritable Class VisualBasicRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer #Else Friend NotInheritable Class VisualBasicRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer #End If Inherits AbstractRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer Protected Overrides ReadOnly Property CompilerErrorCodePrefix As String = "BC" Protected Overrides ReadOnly Property CompilerErrorCodeDigitCount As Integer = 5 Protected Overrides ReadOnly Property SyntaxFacts As ISyntaxFacts = VisualBasicSyntaxFacts.Instance Protected Overrides ReadOnly Property SemanticFacts As ISemanticFacts = VisualBasicSemanticFacts.Instance Protected Overrides Function GetCompilerDiagnosticAnalyzerInfo() As (assembly As Assembly, typeName As String) Return (GetType(SyntaxKind).Assembly, CompilerDiagnosticAnalyzerNames.VisualBasicCompilerAnalyzerTypeName) 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.Reflection Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.LanguageServices Imports Microsoft.CodeAnalysis.RemoveUnnecessarySuppressions Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessarySuppressions #If Not CODE_STYLE Then ' Not exported in CodeStyle layer: https://github.com/dotnet/roslyn/issues/47942 <DiagnosticAnalyzer(LanguageNames.VisualBasic)> Friend NotInheritable Class VisualBasicRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer #Else Friend NotInheritable Class VisualBasicRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer #End If Inherits AbstractRemoveUnnecessaryInlineSuppressionsDiagnosticAnalyzer Protected Overrides ReadOnly Property CompilerErrorCodePrefix As String = "BC" Protected Overrides ReadOnly Property CompilerErrorCodeDigitCount As Integer = 5 Protected Overrides ReadOnly Property SyntaxFacts As ISyntaxFacts = VisualBasicSyntaxFacts.Instance Protected Overrides ReadOnly Property SemanticFacts As ISemanticFacts = VisualBasicSemanticFacts.Instance Protected Overrides Function GetCompilerDiagnosticAnalyzerInfo() As (assembly As Assembly, typeName As String) Return (GetType(SyntaxKind).Assembly, CompilerDiagnosticAnalyzerNames.VisualBasicCompilerAnalyzerTypeName) End Function End Class End Namespace
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/RestoreKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 RestoreKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public RestoreKeywordRecommender() : base(SyntaxKind.RestoreKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var previousToken1 = context.TargetToken; var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true); var previousToken3 = previousToken2.GetPreviousToken(includeSkipped: true); return // # pragma warning | // # pragma warning r| (previousToken1.Kind() == SyntaxKind.WarningKeyword && previousToken2.Kind() == SyntaxKind.PragmaKeyword && previousToken3.Kind() == SyntaxKind.HashToken) || // # nullable | // # nullable r| (previousToken1.Kind() == SyntaxKind.NullableKeyword && previousToken2.Kind() == SyntaxKind.HashToken); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 RestoreKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public RestoreKeywordRecommender() : base(SyntaxKind.RestoreKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var previousToken1 = context.TargetToken; var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true); var previousToken3 = previousToken2.GetPreviousToken(includeSkipped: true); return // # pragma warning | // # pragma warning r| (previousToken1.Kind() == SyntaxKind.WarningKeyword && previousToken2.Kind() == SyntaxKind.PragmaKeyword && previousToken3.Kind() == SyntaxKind.HashToken) || // # nullable | // # nullable r| (previousToken1.Kind() == SyntaxKind.NullableKeyword && previousToken2.Kind() == SyntaxKind.HashToken); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/Compilers/Server/VBCSCompilerTests/BuildProtocolTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class BuildProtocolTest : TestBase { private void VerifyShutdownRequest(BuildRequest request) { Assert.Equal(1, request.Arguments.Count); var argument = request.Arguments[0]; Assert.Equal(BuildProtocolConstants.ArgumentId.Shutdown, argument.ArgumentId); Assert.Equal(0, argument.ArgumentIndex); Assert.Equal("", argument.Value); } [Fact] public async Task ReadWriteCompleted() { var response = new CompletedBuildResponse(42, utf8output: false, output: "a string"); var memoryStream = new MemoryStream(); await response.WriteAsync(memoryStream, default(CancellationToken)); Assert.True(memoryStream.Position > 0); memoryStream.Position = 0; var read = (CompletedBuildResponse)(await BuildResponse.ReadAsync(memoryStream, default(CancellationToken))); Assert.Equal(42, read.ReturnCode); Assert.False(read.Utf8Output); Assert.Equal("a string", read.Output); } [Fact] public async Task ReadWriteRequest() { var request = new BuildRequest( RequestLanguage.VisualBasicCompile, "HashValue", ImmutableArray.Create( new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CurrentDirectory, argumentIndex: 0, value: "directory"), new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CommandLineArgument, argumentIndex: 1, value: "file"))); var memoryStream = new MemoryStream(); await request.WriteAsync(memoryStream, default(CancellationToken)); Assert.True(memoryStream.Position > 0); memoryStream.Position = 0; var read = await BuildRequest.ReadAsync(memoryStream, default(CancellationToken)); Assert.Equal(RequestLanguage.VisualBasicCompile, read.Language); Assert.Equal("HashValue", read.CompilerHash); Assert.Equal(2, read.Arguments.Count); Assert.Equal(BuildProtocolConstants.ArgumentId.CurrentDirectory, read.Arguments[0].ArgumentId); Assert.Equal(0, read.Arguments[0].ArgumentIndex); Assert.Equal("directory", read.Arguments[0].Value); Assert.Equal(BuildProtocolConstants.ArgumentId.CommandLineArgument, read.Arguments[1].ArgumentId); Assert.Equal(1, read.Arguments[1].ArgumentIndex); Assert.Equal("file", read.Arguments[1].Value); } [Fact] public void ShutdownMessage() { var request = BuildRequest.CreateShutdown(); VerifyShutdownRequest(request); Assert.Equal(1, request.Arguments.Count); var argument = request.Arguments[0]; Assert.Equal(BuildProtocolConstants.ArgumentId.Shutdown, argument.ArgumentId); Assert.Equal(0, argument.ArgumentIndex); Assert.Equal("", argument.Value); } [Fact] public async Task ShutdownRequestWriteRead() { var memoryStream = new MemoryStream(); var request = BuildRequest.CreateShutdown(); await request.WriteAsync(memoryStream, CancellationToken.None); memoryStream.Position = 0; var read = await BuildRequest.ReadAsync(memoryStream, CancellationToken.None); VerifyShutdownRequest(read); } [Fact] public async Task ShutdownResponseWriteRead() { var response = new ShutdownBuildResponse(42); Assert.Equal(BuildResponse.ResponseType.Shutdown, response.Type); var memoryStream = new MemoryStream(); await response.WriteAsync(memoryStream, CancellationToken.None); memoryStream.Position = 0; var read = await BuildResponse.ReadAsync(memoryStream, CancellationToken.None); Assert.Equal(BuildResponse.ResponseType.Shutdown, read.Type); var typed = (ShutdownBuildResponse)read; Assert.Equal(42, typed.ServerProcessId); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CommandLine; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests { public class BuildProtocolTest : TestBase { private void VerifyShutdownRequest(BuildRequest request) { Assert.Equal(1, request.Arguments.Count); var argument = request.Arguments[0]; Assert.Equal(BuildProtocolConstants.ArgumentId.Shutdown, argument.ArgumentId); Assert.Equal(0, argument.ArgumentIndex); Assert.Equal("", argument.Value); } [Fact] public async Task ReadWriteCompleted() { var response = new CompletedBuildResponse(42, utf8output: false, output: "a string"); var memoryStream = new MemoryStream(); await response.WriteAsync(memoryStream, default(CancellationToken)); Assert.True(memoryStream.Position > 0); memoryStream.Position = 0; var read = (CompletedBuildResponse)(await BuildResponse.ReadAsync(memoryStream, default(CancellationToken))); Assert.Equal(42, read.ReturnCode); Assert.False(read.Utf8Output); Assert.Equal("a string", read.Output); } [Fact] public async Task ReadWriteRequest() { var request = new BuildRequest( RequestLanguage.VisualBasicCompile, "HashValue", ImmutableArray.Create( new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CurrentDirectory, argumentIndex: 0, value: "directory"), new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CommandLineArgument, argumentIndex: 1, value: "file"))); var memoryStream = new MemoryStream(); await request.WriteAsync(memoryStream, default(CancellationToken)); Assert.True(memoryStream.Position > 0); memoryStream.Position = 0; var read = await BuildRequest.ReadAsync(memoryStream, default(CancellationToken)); Assert.Equal(RequestLanguage.VisualBasicCompile, read.Language); Assert.Equal("HashValue", read.CompilerHash); Assert.Equal(2, read.Arguments.Count); Assert.Equal(BuildProtocolConstants.ArgumentId.CurrentDirectory, read.Arguments[0].ArgumentId); Assert.Equal(0, read.Arguments[0].ArgumentIndex); Assert.Equal("directory", read.Arguments[0].Value); Assert.Equal(BuildProtocolConstants.ArgumentId.CommandLineArgument, read.Arguments[1].ArgumentId); Assert.Equal(1, read.Arguments[1].ArgumentIndex); Assert.Equal("file", read.Arguments[1].Value); } [Fact] public void ShutdownMessage() { var request = BuildRequest.CreateShutdown(); VerifyShutdownRequest(request); Assert.Equal(1, request.Arguments.Count); var argument = request.Arguments[0]; Assert.Equal(BuildProtocolConstants.ArgumentId.Shutdown, argument.ArgumentId); Assert.Equal(0, argument.ArgumentIndex); Assert.Equal("", argument.Value); } [Fact] public async Task ShutdownRequestWriteRead() { var memoryStream = new MemoryStream(); var request = BuildRequest.CreateShutdown(); await request.WriteAsync(memoryStream, CancellationToken.None); memoryStream.Position = 0; var read = await BuildRequest.ReadAsync(memoryStream, CancellationToken.None); VerifyShutdownRequest(read); } [Fact] public async Task ShutdownResponseWriteRead() { var response = new ShutdownBuildResponse(42); Assert.Equal(BuildResponse.ResponseType.Shutdown, response.Type); var memoryStream = new MemoryStream(); await response.WriteAsync(memoryStream, CancellationToken.None); memoryStream.Position = 0; var read = await BuildResponse.ReadAsync(memoryStream, CancellationToken.None); Assert.Equal(BuildResponse.ResponseType.Shutdown, read.Type); var typed = (ShutdownBuildResponse)read; Assert.Equal(42, typed.ServerProcessId); } } }
-1
dotnet/roslyn
56,402
Store information about special attributes in the decl table to avoid going back to source unnecessarily.
Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
CyrusNajmabadi
"2021-09-15T02:38:04Z"
"2021-09-24T04:17:33Z"
633346af571d640eeacb2e2fc724f5d25ed20faa
2b7f137ebbfdf33e9eebffe87d036be392815d2b
Store information about special attributes in the decl table to avoid going back to source unnecessarily.. Fixes https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1393763 The compiler sometimes does excess work in an uncancellable fashion, which can impact some IDE scenarios. Specifically, requesting the Assembly symbol for a Compilation will end up parsing all files that have types with attributes on them to determine if any of them have the `System.Runtime.InteropServices.TypeIdentifierAttribute` on them. This can be very costly (as it may require reparsing large files), esp. as it is uncancellable (since Compilation.Assembly has no way to pass a cancellation token through). This PR mitigates the issue here by adding enough information to the compiler's decl tables to allow it to avoid going back to source when it would be entirely unnecessary. Specifically, it effectively encodes in the decl table "is it possible for this type to have that attribute on it". It encodes that by both keeping track of the names referenced directly in the attributes on the types, as well as keeping track of aliases in the file (and global aliases) to know if that type could be brought in by an alias. Todo: - [x] Tests - [x] VB
./src/VisualStudio/Xaml/Impl/Implementation/LanguageServer/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.Editor.Xaml; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler { [ExportLspRequestHandlerProvider(StringConstants.XamlLanguageName), 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(request.Options, context, 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.Editor.Xaml; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.VisualStudio.LanguageServices.Xaml.LanguageServer.Handler { [ExportLspRequestHandlerProvider(StringConstants.XamlLanguageName), 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(request.Options, context, cancellationToken, range: request.Range); } }
-1